Decompiled source of BoplWithFriends v0.3.1

plugins/BoplWithFriends.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BoplFixedMath;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Steamworks;
using Steamworks.Data;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BoplWithFriends")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Uncaps Bopl Battle's 4-player multiplayer limit (2-16 players online).")]
[assembly: AssemblyFileVersion("0.3.1.0")]
[assembly: AssemblyInformationalVersion("0.3.1+7e4bfcdcc3ceda1f3786b192672ed517328eb15e")]
[assembly: AssemblyProduct("BoplWithFriends")]
[assembly: AssemblyTitle("BoplWithFriends")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.3.1.0")]
[module: UnverifiableCode]
[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 BoplWithFriends
{
	public static class AudioPatches
	{
		[HarmonyPatch(typeof(AudioManager), "PlayInterruptable")]
		private static class PlayInterruptable_Remap_Patch
		{
			private static void Prefix(ref string name)
			{
				name = Remap(name);
			}
		}

		[HarmonyPatch(typeof(AudioManager), "Play", new Type[]
		{
			typeof(string),
			typeof(float)
		})]
		private static class Play2_Remap_Patch
		{
			private static void Prefix(ref string name)
			{
				name = Remap(name);
			}
		}

		[HarmonyPatch(typeof(AudioManager), "Play", new Type[]
		{
			typeof(string),
			typeof(float),
			typeof(float)
		})]
		private static class Play3_Remap_Patch
		{
			private static void Prefix(ref string name)
			{
				name = Remap(name);
			}
		}

		private static readonly Regex PerPlayerSound = new Regex("^(beamCharge|slimeJump|slimeLand)(\\d+)$", RegexOptions.Compiled);

		internal static string Remap(string name)
		{
			if (name == null)
			{
				return null;
			}
			Match match = PerPlayerSound.Match(name);
			if (!match.Success || !int.TryParse(match.Groups[2].Value, out var result) || result <= 4)
			{
				return name;
			}
			return match.Groups[1].Value + ((result - 1) % 4 + 1);
		}
	}
	public static class Bwf
	{
		public sealed class ExtraPlayer
		{
			public int Slot;

			public ulong SteamId;

			public int Color;

			public int Team;

			public int Ab1;

			public int Ab2;

			public int Ab3;
		}

		public static ConfigEntry<int> MaxPlayersConfig;

		public static ManualLogSource Log;

		public static readonly Dictionary<int, ExtraPlayer> Extras = new Dictionary<int, ExtraPlayer>();

		public static bool IsHost;

		public static bool FakeTestMode;

		public const byte Marker = 170;

		public const int VanillaPacketSize = 105;

		public const int BytesPerExtra = 14;

		private static readonly Dictionary<(Type, string), FieldInfo> fieldCache = new Dictionary<(Type, string), FieldInfo>();

		private static readonly Dictionary<(Type, string), MethodInfo> methodCache = new Dictionary<(Type, string), MethodInfo>();

		public static int MaxPlayers
		{
			get
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				int num = MaxPlayersConfig?.Value ?? 8;
				try
				{
					SteamManager instance = SteamManager.instance;
					if ((Object)(object)instance != (Object)null && ((Lobby)(ref instance.currentLobby)).Id.Value != 0L)
					{
						num = Math.Max(num, ((Lobby)(ref instance.currentLobby)).MaxMembers);
					}
				}
				catch
				{
				}
				return Math.Clamp(num, 2, 16);
			}
		}

		public static int ConfiguredMaxPlayers => Math.Clamp(MaxPlayersConfig?.Value ?? 8, 2, 16);

		public static void ResetExtras()
		{
			Extras.Clear();
		}

		public static void ResetMatchState()
		{
			Extras.Clear();
			FakeTestMode = false;
			InputPatches.ResetExtraInputs();
		}

		public static byte[] EncodeExtrasPacket(List<ExtraPlayer> extras)
		{
			int num = extras?.Count ?? 0;
			if (num == 0)
			{
				return null;
			}
			byte[] array = new byte[2 + num * 14];
			array[0] = 170;
			array[1] = (byte)num;
			int num2 = 2;
			foreach (ExtraPlayer item in extras.OrderBy((ExtraPlayer x) => x.Slot))
			{
				array[num2++] = (byte)item.Slot;
				Array.Copy(BitConverter.GetBytes(item.SteamId), 0, array, num2, 8);
				num2 += 8;
				array[num2++] = (byte)item.Color;
				array[num2++] = (byte)item.Team;
				array[num2++] = (byte)item.Ab1;
				array[num2++] = (byte)item.Ab2;
				array[num2++] = (byte)item.Ab3;
			}
			return array;
		}

		public static List<ExtraPlayer> DecodeExtras(byte[] data)
		{
			List<ExtraPlayer> list = new List<ExtraPlayer>();
			if (data == null || data.Length < 2 || data[0] != 170)
			{
				return list;
			}
			int num = data[1];
			if (data.Length < 2 + num * 14)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)$"corrupt start-request extension: claimed {num} extras, buffer {data.Length} bytes");
				}
				return list;
			}
			int num2 = 2;
			for (int i = 0; i < num; i++)
			{
				ExtraPlayer extraPlayer = new ExtraPlayer
				{
					Slot = data[num2++]
				};
				extraPlayer.SteamId = BitConverter.ToUInt64(data, num2);
				num2 += 8;
				extraPlayer.Color = data[num2++];
				extraPlayer.Team = data[num2++];
				extraPlayer.Ab1 = data[num2++];
				extraPlayer.Ab2 = data[num2++];
				extraPlayer.Ab3 = data[num2++];
				list.Add(extraPlayer);
			}
			return list;
		}

		public static FieldInfo F(Type t, string name)
		{
			(Type, string) key = (t, name);
			if (!fieldCache.TryGetValue(key, out var value))
			{
				value = t.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingFieldException(t.Name, name);
				fieldCache[key] = value;
			}
			return value;
		}

		public static object Get(object o, Type t, string name)
		{
			return F(t, name).GetValue(o);
		}

		public static object Get(Type t, string name)
		{
			return F(t, name).GetValue(null);
		}

		public static void Set(object o, Type t, string name, object v)
		{
			F(t, name).SetValue(o, v);
		}

		public static void Set(Type t, string name, object v)
		{
			F(t, name).SetValue(null, v);
		}

		public static MethodInfo M(Type t, string name)
		{
			(Type, string) key = (t, name);
			if (!methodCache.TryGetValue(key, out var value))
			{
				value = t.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingMethodException(t.Name, name);
				methodCache[key] = value;
			}
			return value;
		}

		public static void ApplyExtraInput(int slot, InputPacket input)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Player player = PlayerHandler.Get().GetPlayer(slot);
			if (player != null)
			{
				player.OverrideInputWithNetworkInput(input);
			}
		}

		public static void ResetExtraInputQueues()
		{
			InputPatches.ResetExtraInputs();
		}

		public static void Info(object o)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo(o ?? "null");
			}
		}

		public static void Warn(object o)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogWarning(o ?? "null");
			}
		}

		public static void Error(object o)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogError(o ?? "null");
			}
		}
	}
	public static class BwfDriver
	{
		private static int frames;

		private static int heartbeatsLogged;

		private static float nextHeartbeat;

		private static Scene lastScene;

		private static bool sceneHandlerSubscribed;

		private const string VersionKey = "bwf_version";

		private static float nextVersionPublish;

		public static void Create()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (!sceneHandlerSubscribed)
			{
				SceneManager.sceneLoaded += OnSceneLoadedStatic;
				sceneHandlerSubscribed = true;
			}
			lastScene = SceneManager.GetActiveScene();
			Bwf.Info("driver created (Harmony-driven)");
		}

		public static void OnFrame()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			frames++;
			if (Time.realtimeSinceStartup >= nextHeartbeat && heartbeatsLogged < 3)
			{
				nextHeartbeat = Time.realtimeSinceStartup + 5f;
				heartbeatsLogged++;
				Bwf.Info($"heartbeat: Update postfix running (frames={frames}, inMenus={GameSession.inMenus})");
			}
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).handle != ((Scene)(ref lastScene)).handle)
			{
				lastScene = activeScene;
				OnSceneChanged(activeScene);
			}
			TestMode.OnUpdate();
			if (Time.realtimeSinceStartup >= nextVersionPublish)
			{
				nextVersionPublish = Time.realtimeSinceStartup + 2f;
				SteamManager instance = SteamManager.instance;
				if ((Object)(object)instance != (Object)null && ((Lobby)(ref instance.currentLobby)).Id.Value != 0L && ((Lobby)(ref instance.currentLobby)).IsOwnedBy(SteamClient.SteamId))
				{
					CheckLobbyModVersion();
				}
			}
		}

		private static void OnSceneLoadedStatic(Scene scene, LoadSceneMode mode)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			OnSceneChanged(scene);
		}

		private static void OnSceneChanged(Scene scene)
		{
			Bwf.Info($"scene loaded: {((Scene)(ref scene)).name} (build index {((Scene)(ref scene)).buildIndex})");
			Plugin.RaiseCaps();
			Plugin.EnsurePalettes();
			Plugin.LogPalettes();
			CheckLobbyModVersion();
		}

		private static void CheckLobbyModVersion()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				SteamManager instance = SteamManager.instance;
				if ((Object)(object)instance == (Object)null || ((Lobby)(ref instance.currentLobby)).Id.Value == 0L)
				{
					return;
				}
				if (((Lobby)(ref instance.currentLobby)).IsOwnedBy(SteamClient.SteamId))
				{
					if (((Lobby)(ref instance.currentLobby)).GetData("bwf_version") != "0.3.1")
					{
						((Lobby)(ref instance.currentLobby)).SetData("bwf_version", "0.3.1");
					}
					return;
				}
				string data = ((Lobby)(ref instance.currentLobby)).GetData("bwf_version");
				if (!string.IsNullOrEmpty(data) && !(data == "0.3.1"))
				{
					string text = "BoplWithFriends version mismatch: host has " + data + ", you have 0.3.1. Everyone needs the same version.";
					Bwf.Warn(text);
					TestMode.Toast(text, 15f);
				}
			}
			catch (Exception ex)
			{
				Bwf.Warn("lobby version check failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(SteamManager), "Update")]
	internal static class SteamManager_Update_Driver_Patch
	{
		private static void Postfix()
		{
			BwfDriver.OnFrame();
		}
	}
	public static class FakeSafeLoadPatches
	{
		[HarmonyPatch(typeof(SteamManager), "ForceLoadNextLevel")]
		private static class ForceLoadNextLevel_FakeSafe_Patch
		{
			private static bool Prefix()
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_015d: Unknown result type (might be due to invalid IL or missing references)
				//IL_016b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0179: Unknown result type (might be due to invalid IL or missing references)
				//IL_0187: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_021b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0229: Unknown result type (might be due to invalid IL or missing references)
				//IL_0237: Unknown result type (might be due to invalid IL or missing references)
				//IL_0245: Unknown result type (might be due to invalid IL or missing references)
				//IL_0277: Unknown result type (might be due to invalid IL or missing references)
				//IL_0285: Unknown result type (might be due to invalid IL or missing references)
				//IL_0293: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
				ApplyExtraAbilities();
				if (!Bwf.FakeTestMode)
				{
					return true;
				}
				SteamManager instance = SteamManager.instance;
				Host networkClientHandle = SteamManager.networkClientHandle;
				if (networkClientHandle != null)
				{
					networkClientHandle.DeInit();
				}
				StartRequestPacket startParameters = SteamManager.startParameters;
				List<Player> list = PlayerHandler.Get().PlayerList();
				if (startParameters.nrOfPlayers <= 1)
				{
					GameSessionHandler.LeaveGame(true, false);
					return false;
				}
				for (int num = list.Count - 1; num >= 0; num--)
				{
					if (!list[num].IsLocalPlayer && !Bwf.Extras.ContainsKey(list[num].Id))
					{
						bool flag = false;
						foreach (SteamConnection connectedPlayer in instance.connectedPlayers)
						{
							flag |= connectedPlayer.id.Value == SteamId.op_Implicit(list[num].steamId);
						}
						if (!flag)
						{
							list.RemoveAt(num);
							Debug.Log((object)"dropping player because they were disconnected");
						}
					}
				}
				MethodInfo methodInfo = Bwf.M(typeof(SteamManager), "ChangePlayerAbilites");
				for (int i = 0; i < list.Count; i++)
				{
					switch (list[i].Id)
					{
					case 1:
						methodInfo.Invoke(null, new object[6]
						{
							list[i],
							startParameters.p1_ability1,
							startParameters.p1_ability2,
							startParameters.p1_ability3,
							startParameters.nrOfAbilites,
							instance.abilityIcons
						});
						break;
					case 2:
						methodInfo.Invoke(null, new object[6]
						{
							list[i],
							startParameters.p2_ability1,
							startParameters.p2_ability2,
							startParameters.p2_ability3,
							startParameters.nrOfAbilites,
							instance.abilityIcons
						});
						break;
					case 3:
						methodInfo.Invoke(null, new object[6]
						{
							list[i],
							startParameters.p3_ability1,
							startParameters.p3_ability2,
							startParameters.p3_ability3,
							startParameters.nrOfAbilites,
							instance.abilityIcons
						});
						break;
					case 4:
						methodInfo.Invoke(null, new object[6]
						{
							list[i],
							startParameters.p4_ability1,
							startParameters.p4_ability2,
							startParameters.p4_ability3,
							startParameters.nrOfAbilites,
							instance.abilityIcons
						});
						break;
					}
				}
				GameSession.SetCurrentLevel(startParameters.currentLevel);
				if (!GameSessionHandler.GameIsPaused)
				{
					CharacterStatsList.ForceNextLevelImmediately();
				}
				else
				{
					CharacterStatsList.ForceNextLevelLoad();
				}
				Bwf.Info($"ForceLoadNextLevel (fake-safe): {list.Count} players kept");
				return false;
			}
		}

		[HarmonyPatch(typeof(SteamManager), "ForceBacktoAbilitySelect")]
		private static class ForceBacktoAbilitySelect_FakeSafe_Patch
		{
			private static bool Prefix()
			{
				if (Bwf.FakeTestMode && (Object)(object)SteamManager.networkClientHandle != (Object)null)
				{
					return ((List<Client>)Bwf.Get(SteamManager.networkClientHandle, typeof(Host), "clients")).Count != 0;
				}
				return true;
			}
		}

		internal static void ApplyExtraAbilities()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			if (Bwf.Extras.Count == 0)
			{
				return;
			}
			SteamManager instance = SteamManager.instance;
			StartRequestPacket startParameters = SteamManager.startParameters;
			MethodInfo methodInfo = Bwf.M(typeof(SteamManager), "ChangePlayerAbilites");
			foreach (Player item in PlayerHandler.Get().PlayerList())
			{
				if ((item.Id > 4 || Bwf.FakeTestMode) && Bwf.Extras.TryGetValue(item.Id, out var value) && value.Ab1 != 0)
				{
					methodInfo.Invoke(null, new object[6]
					{
						item,
						(byte)value.Ab1,
						(byte)value.Ab2,
						(byte)value.Ab3,
						(int)startParameters.nrOfAbilites,
						instance.abilityIcons
					});
				}
			}
		}
	}
	public static class InputPatches
	{
		[HarmonyPatch(typeof(Host), "Init")]
		private static class Host_Init_Patch
		{
			private static void Postfix()
			{
				ExtraBuf.Clear();
			}
		}

		[HarmonyPatch(typeof(Host), "ProcessNetworkPackets")]
		private static class Host_ProcessNetworkPackets_Patch
		{
			private static bool Prefix(Host __instance)
			{
				//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_0235: Unknown result type (might be due to invalid IL or missing references)
				//IL_0266: Unknown result type (might be due to invalid IL or missing references)
				//IL_026b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0303: Unknown result type (might be due to invalid IL or missing references)
				//IL_0308: Unknown result type (might be due to invalid IL or missing references)
				//IL_0299: Unknown result type (might be due to invalid IL or missing references)
				//IL_029b: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02af: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0327: Unknown result type (might be due to invalid IL or missing references)
				//IL_0329: Unknown result type (might be due to invalid IL or missing references)
				//IL_0332: Unknown result type (might be due to invalid IL or missing references)
				//IL_0334: Unknown result type (might be due to invalid IL or missing references)
				//IL_033d: Unknown result type (might be due to invalid IL or missing references)
				//IL_033f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0348: Unknown result type (might be due to invalid IL or missing references)
				//IL_034a: Unknown result type (might be due to invalid IL or missing references)
				//IL_037e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0380: Unknown result type (might be due to invalid IL or missing references)
				//IL_039c: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_02da: Unknown result type (might be due to invalid IL or missing references)
				//IL_0361: Unknown result type (might be due to invalid IL or missing references)
				//IL_0363: Unknown result type (might be due to invalid IL or missing references)
				//IL_0368: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_0373: Unknown result type (might be due to invalid IL or missing references)
				List<Client> list = (List<Client>)Bwf.Get(__instance, typeof(Host), "clients");
				TimedInputPacket[] array = (TimedInputPacket[])Bwf.Get(__instance, typeof(Host), "inputHistory");
				bool adaptiveInputDelayBuffer = __instance.AdaptiveInputDelayBuffer;
				uint inputPacketsSent = __instance.inputPacketsSent;
				int num = (int)Bwf.Get(__instance, typeof(Host), "localPlayerId");
				Queue<InputPacketQuad> queue = (Queue<InputPacketQuad>)Bwf.Get(__instance, typeof(Host), "InputBuffer");
				Queue<InputPacket> queue2 = (Queue<InputPacket>)Bwf.Get(__instance, typeof(Host), "sentPacketHistory");
				int num2 = (int)Bwf.Get(__instance, typeof(Host), "UpdatesPlacedInDelayBuffer");
				int num3 = (int)Bwf.Get(typeof(Host), "delayBufferSize");
				bool flag = (bool)Bwf.Get(__instance, typeof(Host), "allClientsSynced");
				if (list.Count == 0)
				{
					MonoBehaviour.print((object)"There are no clients");
				}
				for (int i = 0; i < list.Count; i++)
				{
					if (!((ConnectionManager)list[i].steamConnection).Connected && !((ConnectionManager)list[i].steamConnection).Connecting)
					{
						MonoBehaviour.print((object)" a client is not connected nor connecting");
					}
				}
				bool flag2 = true;
				for (int j = 0; j < list.Count; j++)
				{
					list[j].ProcessNetworkPackets(Time.unscaledTime, array, adaptiveInputDelayBuffer, (byte)num);
					flag2 &= list[j].HasReceivedSyncAck;
					flag2 &= list[j].HasSentSyncAck;
				}
				if (flag2 && !flag)
				{
					flag = true;
					for (int k = 0; k < num3; k++)
					{
						queue.Enqueue(default(InputPacketQuad));
						ExtraBuf.Enqueue(null);
					}
				}
				if (!flag)
				{
					PersistState(__instance, flag);
					return false;
				}
				uint num4 = uint.MaxValue;
				for (int l = 0; l < list.Count; l++)
				{
					if (list[l].InputPacketsReceived < num4)
					{
						num4 = list[l].InputPacketsReceived;
					}
				}
				if (inputPacketsSent < num4)
				{
					num4 = inputPacketsSent;
				}
				int num5 = (int)num4 - num2;
				int num6 = MaxExtraSlot();
				for (int m = 0; m < num5; m++)
				{
					InputPacketQuad val = default(InputPacketQuad);
					InputPacket[] array2 = (InputPacket[])(object)((num6 > 4) ? new InputPacket[num6 + 1] : null);
					byte b = 0;
					for (int n = 0; n < list.Count; n++)
					{
						InputPacket val2 = list[n].inputHistory.Dequeue();
						int playerId = list[n].PlayerId;
						switch (playerId)
						{
						case 1:
							val.p1 = val2;
							continue;
						case 2:
							val.p2 = val2;
							continue;
						case 3:
							val.p3 = val2;
							continue;
						case 4:
							val.p4 = val2;
							continue;
						}
						if (array2 != null && playerId < array2.Length)
						{
							array2[playerId] = val2;
							if (val2.targetDelayBufferSize > b)
							{
								b = val2.targetDelayBufferSize;
							}
						}
					}
					InputPacket val3 = queue2.Dequeue();
					switch (num)
					{
					case 1:
						val.p1 = val3;
						break;
					case 2:
						val.p2 = val3;
						break;
					case 3:
						val.p3 = val3;
						break;
					case 4:
						val.p4 = val3;
						break;
					default:
						if (array2 != null && num < array2.Length)
						{
							array2[num] = val3;
							if (val3.targetDelayBufferSize > b)
							{
								b = val3.targetDelayBufferSize;
							}
						}
						break;
					}
					if (b > val.p1.targetDelayBufferSize)
					{
						val.p1.targetDelayBufferSize = b;
					}
					queue.Enqueue(val);
					ExtraBuf.Enqueue(array2);
					num2++;
				}
				Bwf.Set(__instance, typeof(Host), "UpdatesPlacedInDelayBuffer", num2);
				if (ExtraBuf.Count != queue.Count && bufMismatchLogs++ < 10)
				{
					Bwf.Error($"lockstep side buffer out of step: extras {ExtraBuf.Count} vs quads {queue.Count}");
				}
				try
				{
					if (num == 1)
					{
						for (int num7 = 0; num7 < list.Count; num7++)
						{
							list[num7].CheckForDesyncs();
						}
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("Desync occured, ending game " + ex));
					GameSessionHandler.EndGameImmediately();
				}
				PersistState(__instance, flag);
				return false;
			}

			private static void PersistState(Host __instance, bool allClientsSynced)
			{
				Bwf.Set(__instance, typeof(Host), "allClientsSynced", allClientsSynced);
			}
		}

		[HarmonyPatch(typeof(Updater), "TickSimulation")]
		private static class Updater_TickSimulation_Extras_Patch
		{
			private static void Prefix()
			{
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0094: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				if (!GameLobby.isOnlineGame || GameLobby.isPlayingAReplay)
				{
					return;
				}
				Host networkClientHandle = SteamManager.networkClientHandle;
				if ((Object)(object)networkClientHandle == (Object)null || !networkClientHandle.hasBeenInitialized || (Bwf.Extras.Count == 0 && ExtraBuf.Count == 0))
				{
					return;
				}
				InputPacket[] array = ((ExtraBuf.Count > 0) ? ExtraBuf.Dequeue() : null);
				List<Player> list = PlayerHandler.Get().PlayerList();
				for (int i = 0; i < list.Count; i++)
				{
					Player val = list[i];
					if (val.Id > 4)
					{
						InputPacket val2 = (InputPacket)((array != null && val.Id < array.Length) ? array[val.Id] : default(InputPacket));
						val.OverrideInputWithNetworkInput(val2);
					}
				}
			}
		}

		private static readonly Queue<InputPacket[]> ExtraBuf = new Queue<InputPacket[]>();

		private static int bufMismatchLogs;

		public static void ResetExtraInputs()
		{
			ExtraBuf.Clear();
		}

		private static int MaxExtraSlot()
		{
			int num = 4;
			foreach (int key in Bwf.Extras.Keys)
			{
				if (key > num)
				{
					num = key;
				}
			}
			return num;
		}
	}
	public static class ModInfo
	{
		public const string PLUGIN_NAME = "BoplWithFriends";

		public const string PLUGIN_GUID = "com.deeroot.boplwithfriends";

		public const string PLUGIN_VERSION = "0.3.1";

		public const int HARD_MAX_PLAYERS = 16;
	}
	public static class NetworkingPatches
	{
		[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
		private static class CreateLobbyAsync_RaiseCap_Patch
		{
			private static void Prefix(ref int __0)
			{
				if (__0 == 4)
				{
					Bwf.Info($"lobby capacity 4 -> {Bwf.ConfiguredMaxPlayers}");
					__0 = Bwf.ConfiguredMaxPlayers;
				}
			}
		}

		[HarmonyPatch(typeof(SteamSocket), "OnMessage")]
		private static class OnMessage_StartRequestExtension_Patch
		{
			private static readonly List<byte[]> helperBuffers = new List<byte[]>();

			private static readonly byte[] buf = new byte[2048];

			private static byte[] ushortHelper = new byte[2];

			private static byte[] uintHelper = new byte[4];

			private static byte[] ulongHelper = new byte[8];

			private static readonly byte[] ackBuf = new byte[6];

			private static bool Prefix(IntPtr data, int size, NetIdentity identity)
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: 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_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_0133: Unknown result type (might be due to invalid IL or missing references)
				if (size == 6)
				{
					return RouteExtraSlotAck(data, identity);
				}
				if (size == 105)
				{
					Bwf.ResetMatchState();
					return true;
				}
				if (size < 105 || size > ExtendedPacketSizeLimit)
				{
					return true;
				}
				Marshal.Copy(data, buf, 0, size);
				if (buf[105] != 170)
				{
					return true;
				}
				SteamManager instance = SteamManager.instance;
				if (!((Lobby)(ref instance.currentLobby)).IsOwnedBy(((NetIdentity)(ref identity)).SteamId))
				{
					return false;
				}
				StartRequestPacket val = (SteamManager.startParameters = NetworkTools.ReadStartRequest(buf, ref uintHelper, ref ulongHelper, ref ushortHelper));
				Bwf.ResetExtras();
				Bwf.FakeTestMode = false;
				byte[] array = new byte[size - 105];
				Array.Copy(buf, 105, array, 0, array.Length);
				foreach (Bwf.ExtraPlayer item in Bwf.DecodeExtras(array))
				{
					Bwf.Extras[item.Slot] = item;
				}
				Bwf.Info(string.Format("received start request: {0} players ({1} extra slots: {2})", val.nrOfPlayers, Bwf.Extras.Count, string.Join(",", Bwf.Extras.Keys)));
				instance.EncodeCurrentStartParameters_forReplay(ref instance.networkClient.EncodedStartRequest, val, false);
				if (GameSession.inMenus)
				{
					CharacterSelectHandler_online.ForceStartGame((PlayerColors)null);
				}
				else
				{
					SteamManager.ForceLoadNextLevel();
				}
				return false;
			}

			private static bool RouteExtraSlotAck(IntPtr data, NetIdentity identity)
			{
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				Marshal.Copy(data, ackBuf, 0, 6);
				byte b = ackBuf[0];
				if (b != 5 && b != 6)
				{
					return true;
				}
				Host networkClientHandle = SteamManager.networkClientHandle;
				if (!((Object)(object)networkClientHandle == (Object)null) && networkClientHandle.hasBeenInitialized)
				{
					Scene activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).buildIndex >= 6)
					{
						List<Client> obj = (List<Client>)Bwf.Get(networkClientHandle, typeof(Host), "clients");
						ulong value = ((NetIdentity)(ref identity)).SteamId.Value;
						foreach (Client item in obj)
						{
							if (item.PlayerId == b && item.Id.Value == value)
							{
								networkClientHandle.ReadPacket(ackBuf, 6);
								return false;
							}
						}
						return true;
					}
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Host), "ReadPacket")]
		private static class Host_ReadPacket_Guard_Patch
		{
			private static bool Prefix(Host __instance, byte[] bytes, int size)
			{
				if (bytes == null || size < 1)
				{
					return true;
				}
				List<Client> list = (List<Client>)Bwf.Get(__instance, typeof(Host), "clients");
				if (list == null || list.Count == 0)
				{
					return true;
				}
				for (int i = 0; i < list.Count; i++)
				{
					if ((byte)list[i].PlayerId == bytes[0])
					{
						return true;
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(SteamManager), "HostGame")]
		private static class HostGame_Patch
		{
			private static bool Prefix(SteamManager __instance, PlayerInit hostPlayer)
			{
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_010d: Unknown result type (might be due to invalid IL or missing references)
				//IL_011e: Unknown result type (might be due to invalid IL or missing references)
				//IL_012c: Unknown result type (might be due to invalid IL or missing references)
				//IL_013a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0148: Unknown result type (might be due to invalid IL or missing references)
				//IL_0156: Unknown result type (might be due to invalid IL or missing references)
				//IL_0192: Unknown result type (might be due to invalid IL or missing references)
				//IL_0193: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_020a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0233: Unknown result type (might be due to invalid IL or missing references)
				//IL_025d: Unknown result type (might be due to invalid IL or missing references)
				Bwf.ResetMatchState();
				foreach (Bwf.ExtraPlayer item in ExtrasFromConnectedPlayers())
				{
					Bwf.Extras[item.Slot] = item;
				}
				((Lobby)(ref __instance.currentLobby)).SetData("LFM", "0");
				((Lobby)(ref __instance.currentLobby)).SetFriendsOnly();
				((Lobby)(ref __instance.currentLobby)).SetJoinable(false);
				StartRequestPacket sp = default(StartRequestPacket);
				ushort num = (ushort)Bwf.F(typeof(SteamManager), "nextStartGameSeq").GetValue(__instance);
				sp.seqNum = num;
				Bwf.F(typeof(SteamManager), "nextStartGameSeq").SetValue(__instance, (ushort)(num + 1));
				sp.nrOfAbilites = (byte)Settings.Get().NumberOfAbilities;
				sp.currentLevel = GameSession.CurrentLevel();
				sp.seed = (uint)Environment.TickCount;
				sp.nrOfPlayers = (byte)(__instance.connectedPlayers.Count + 1);
				sp.p1_id = SteamClient.SteamId.Value;
				sp.p1_team = (byte)hostPlayer.team;
				sp.p1_color = (byte)hostPlayer.color;
				sp.p1_ability1 = (byte)hostPlayer.ability0;
				sp.p1_ability2 = (byte)hostPlayer.ability1;
				sp.p1_ability3 = (byte)hostPlayer.ability2;
				for (int i = 0; i < __instance.connectedPlayers.Count; i++)
				{
					SetConnectionSlots(ref sp, i, __instance.connectedPlayers[i]);
				}
				SteamManager.startParameters = sp;
				byte b = (__instance.dlc.HasDLC() ? ((byte)1) : ((byte)0));
				for (int j = 0; j < __instance.connectedPlayers.Count && j < 7; j++)
				{
					if (__instance.connectedPlayers[j].ownsFullGame)
					{
						b = (byte)(b | (1 << j + 1));
					}
				}
				sp.isDemoMask = b;
				SteamManager.startParameters = sp;
				byte[] array = BuildStartPacket(__instance);
				__instance.EncodeCurrentStartParameters_forReplay(ref __instance.networkClient.EncodedStartRequest, SteamManager.startParameters, false);
				foreach (SteamConnection connectedPlayer in __instance.connectedPlayers)
				{
					((Connection)(ref ((ConnectionManager)connectedPlayer).Connection)).SendMessage(array, (SendType)8);
				}
				Bwf.IsHost = true;
				Bwf.Info(string.Format("HostGame: serving {0} players ({1} extra slots: {2})", sp.nrOfPlayers, Bwf.Extras.Count, string.Join(",", Bwf.Extras.Keys)));
				return false;
			}
		}

		[HarmonyPatch(typeof(SteamManager), "HostNextLevel")]
		private static class HostNextLevel_Patch
		{
			private static bool Prefix(SteamManager __instance, Player hostPlayer, NamedSpriteList abilityIcons)
			{
				//IL_0002: 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_01c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0210: Unknown result type (might be due to invalid IL or missing references)
				//IL_0230: Unknown result type (might be due to invalid IL or missing references)
				StartRequestPacket sp = SteamManager.startParameters;
				sp.frameBufferSize = (byte)Host.CurrentDelayBufferSize;
				sp.seed = (uint)Environment.TickCount;
				sp.nrOfPlayers = (Bwf.FakeTestMode ? ((byte)(Bwf.Extras.Count + 1)) : ((byte)(__instance.connectedPlayers.Count + 1)));
				sp.currentLevel = GameSession.CurrentLevel();
				List<Player> list = PlayerHandler.Get().PlayerList();
				for (int i = 0; i < list.Count; i++)
				{
					if (hostPlayer.Id == list[i].Id)
					{
						SetLocalAbilities(ref sp, list[i].Id, hostPlayer, abilityIcons);
						continue;
					}
					for (int j = 0; j < __instance.connectedPlayers.Count; j++)
					{
						if (SteamId.op_Implicit(list[i].steamId) == SteamId.op_Implicit(__instance.connectedPlayers[j].id))
						{
							SetRemoteAbilities(ref sp, list[i].Id, __instance.connectedPlayers[j]);
							break;
						}
					}
				}
				if (!Bwf.FakeTestMode)
				{
					foreach (Bwf.ExtraPlayer value in Bwf.Extras.Values)
					{
						foreach (SteamConnection connectedPlayer in __instance.connectedPlayers)
						{
							if (connectedPlayer.id.Value == value.SteamId)
							{
								value.Ab1 = connectedPlayer.lobby_ability1;
								value.Ab2 = connectedPlayer.lobby_ability2;
								value.Ab3 = connectedPlayer.lobby_ability3;
								break;
							}
						}
					}
				}
				SteamManager.startParameters = sp;
				ApplyRemoteAbilitiesOnHost(sp, hostPlayer);
				FakeSafeLoadPatches.ApplyExtraAbilities();
				byte[] array = BuildStartPacket(__instance);
				__instance.EncodeCurrentStartParameters_forReplay(ref __instance.networkClient.EncodedStartRequest, SteamManager.startParameters, false);
				for (int k = 0; k < __instance.connectedPlayers.Count; k++)
				{
					((Connection)(ref ((ConnectionManager)__instance.connectedPlayers[k]).Connection)).SendMessage(array, (SendType)8);
				}
				Bwf.Info($"HostNextLevel: serving {sp.nrOfPlayers} players");
				return false;
			}

			private static void ApplyRemoteAbilitiesOnHost(StartRequestPacket sp, Player hostPlayer)
			{
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: 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_0096: 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)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_010a: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo methodInfo = Bwf.M(typeof(SteamManager), "ChangePlayerAbilites");
				NamedSpriteList abilityIcons = SteamManager.instance.abilityIcons;
				foreach (Player item in PlayerHandler.Get().PlayerList())
				{
					if (item.Id != hostPlayer.Id)
					{
						byte b;
						byte b2;
						byte b3;
						switch (item.Id)
						{
						case 1:
							b = sp.p1_ability1;
							b2 = sp.p1_ability2;
							b3 = sp.p1_ability3;
							break;
						case 2:
							b = sp.p2_ability1;
							b2 = sp.p2_ability2;
							b3 = sp.p2_ability3;
							break;
						case 3:
							b = sp.p3_ability1;
							b2 = sp.p3_ability2;
							b3 = sp.p3_ability3;
							break;
						case 4:
							b = sp.p4_ability1;
							b2 = sp.p4_ability2;
							b3 = sp.p4_ability3;
							break;
						default:
							continue;
						}
						if (b != 0)
						{
							methodInfo.Invoke(null, new object[6]
							{
								item,
								b,
								b2,
								b3,
								(int)sp.nrOfAbilites,
								abilityIcons
							});
						}
					}
				}
			}

			private static void SetLocalAbilities(ref StartRequestPacket sp, int playerId, Player p, NamedSpriteList icons)
			{
				byte b = (byte)icons.IndexOf(((Object)p.Abilities[0]).name);
				byte b2 = 0;
				byte b3 = 0;
				if (Settings.Get().NumberOfAbilities > 1)
				{
					b2 = (byte)icons.IndexOf(((Object)p.Abilities[1]).name);
				}
				if (Settings.Get().NumberOfAbilities > 2)
				{
					b3 = (byte)icons.IndexOf(((Object)p.Abilities[2]).name);
				}
				switch (playerId)
				{
				case 1:
					sp.p1_ability1 = b;
					sp.p1_ability2 = b2;
					sp.p1_ability3 = b3;
					break;
				case 2:
					sp.p2_ability1 = b;
					sp.p2_ability2 = b2;
					sp.p2_ability3 = b3;
					break;
				case 3:
					sp.p3_ability1 = b;
					sp.p3_ability2 = b2;
					sp.p3_ability3 = b3;
					break;
				case 4:
					sp.p4_ability1 = b;
					sp.p4_ability2 = b2;
					sp.p4_ability3 = b3;
					break;
				}
			}

			private static void SetRemoteAbilities(ref StartRequestPacket sp, int playerId, SteamConnection conn)
			{
				switch (playerId)
				{
				case 2:
					sp.p2_ability1 = conn.lobby_ability1;
					sp.p2_ability2 = conn.lobby_ability2;
					sp.p2_ability3 = conn.lobby_ability3;
					break;
				case 3:
					sp.p3_ability1 = conn.lobby_ability1;
					sp.p3_ability2 = conn.lobby_ability2;
					sp.p3_ability3 = conn.lobby_ability3;
					break;
				case 4:
					sp.p4_ability1 = conn.lobby_ability1;
					sp.p4_ability2 = conn.lobby_ability2;
					sp.p4_ability3 = conn.lobby_ability3;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(SteamManager), "InitNetworkClient")]
		private static class InitNetworkClient_Patch
		{
			private static bool Prefix(SteamManager __instance)
			{
				//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)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				//IL_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0161: Unknown result type (might be due to invalid IL or missing references)
				//IL_016b: Expected O, but got Unknown
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cd: Expected O, but got Unknown
				//IL_0225: Unknown result type (might be due to invalid IL or missing references)
				//IL_022f: Expected O, but got Unknown
				//IL_0287: Unknown result type (might be due to invalid IL or missing references)
				//IL_0291: Expected O, but got Unknown
				//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02f1: Expected O, but got Unknown
				SteamManager val = __instance;
				if ((Object)(object)val.networkClient == (Object)null)
				{
					val.networkClient = Object.FindObjectOfType<Host>();
				}
				StartRequestPacket sp = SteamManager.startParameters;
				int num = 0;
				if (sp.p1_id == SteamClient.SteamId.Value)
				{
					num = 1;
				}
				else if (sp.p2_id == SteamClient.SteamId.Value)
				{
					num = 2;
				}
				else if (sp.p3_id == SteamClient.SteamId.Value)
				{
					num = 3;
				}
				else if (sp.p4_id == SteamClient.SteamId.Value)
				{
					num = 4;
				}
				else
				{
					foreach (Bwf.ExtraPlayer value in Bwf.Extras.Values)
					{
						if (value.SteamId == SteamClient.SteamId.Value)
						{
							num = value.Slot;
						}
					}
				}
				List<Client> list = new List<Client>();
				int i;
				for (i = 0; i < __instance.connectedPlayers.Count; i++)
				{
					if (__instance.connectedPlayers[i].id.Value == sp.p1_id && sp.nrOfPlayers >= 1)
					{
						list.Add(new Client(1, __instance.connectedPlayers[i]));
						continue;
					}
					if (__instance.connectedPlayers[i].id.Value == sp.p2_id && sp.nrOfPlayers >= 2)
					{
						list.Add(new Client(2, __instance.connectedPlayers[i]));
						continue;
					}
					if (__instance.connectedPlayers[i].id.Value == sp.p3_id && sp.nrOfPlayers >= 3)
					{
						list.Add(new Client(3, __instance.connectedPlayers[i]));
						continue;
					}
					if (__instance.connectedPlayers[i].id.Value == sp.p4_id && sp.nrOfPlayers >= 4)
					{
						list.Add(new Client(4, __instance.connectedPlayers[i]));
						continue;
					}
					Bwf.ExtraPlayer extraPlayer = Bwf.Extras.Values.FirstOrDefault((Bwf.ExtraPlayer x) => sp.nrOfPlayers >= x.Slot && x.SteamId == __instance.connectedPlayers[i].id.Value);
					if (extraPlayer != null)
					{
						list.Add(new Client(extraPlayer.Slot, __instance.connectedPlayers[i]));
					}
				}
				__instance.networkClient.Init(list, num, sp.currentLevel, __instance.startFrameBuffer, __instance.checkForDesyncs);
				SteamManager.networkClientHandle = __instance.networkClient;
				if (num > 4)
				{
					Bwf.Info($"this client sits in extension slot {num}");
				}
				return false;
			}
		}

		private static int ExtendedPacketSizeLimit => 275;

		private static List<Bwf.ExtraPlayer> ExtrasFromConnectedPlayers()
		{
			List<Bwf.ExtraPlayer> list = new List<Bwf.ExtraPlayer>();
			List<SteamConnection> connectedPlayers = SteamManager.instance.connectedPlayers;
			for (int i = 3; i < connectedPlayers.Count; i++)
			{
				list.Add(new Bwf.ExtraPlayer
				{
					Slot = 5 + list.Count,
					SteamId = connectedPlayers[i].id.Value,
					Color = connectedPlayers[i].lobby_color,
					Team = connectedPlayers[i].lobby_team,
					Ab1 = connectedPlayers[i].lobby_ability1,
					Ab2 = connectedPlayers[i].lobby_ability2,
					Ab3 = connectedPlayers[i].lobby_ability3
				});
			}
			return list;
		}

		private static byte[] BuildStartPacket(SteamManager sm)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = Bwf.EncodeExtrasPacket(new List<Bwf.ExtraPlayer>(Bwf.Extras.Values));
			byte[] array2 = new byte[105 + ((array != null) ? array.Length : 0)];
			NetworkTools.EncodeStartRequest(ref array2, SteamManager.startParameters);
			array?.CopyTo(array2, 105);
			Bwf.F(typeof(SteamManager), "startRequestBuffer").SetValue(sm, array2);
			return array2;
		}

		private static void SetConnectionSlots(ref StartRequestPacket sp, int index, SteamConnection conn)
		{
			switch (index)
			{
			case 0:
				sp.p2_id = conn.id.Value;
				sp.p2_team = conn.lobby_team;
				sp.p2_color = (byte)conn.lobby_color;
				sp.p2_ability1 = conn.lobby_ability1;
				sp.p2_ability2 = conn.lobby_ability2;
				sp.p2_ability3 = conn.lobby_ability3;
				break;
			case 1:
				sp.p3_id = conn.id.Value;
				sp.p3_team = conn.lobby_team;
				sp.p3_color = (byte)conn.lobby_color;
				sp.p3_ability1 = conn.lobby_ability1;
				sp.p3_ability2 = conn.lobby_ability2;
				sp.p3_ability3 = conn.lobby_ability3;
				break;
			case 2:
				sp.p4_id = conn.id.Value;
				sp.p4_team = conn.lobby_team;
				sp.p4_color = (byte)conn.lobby_color;
				sp.p4_ability1 = conn.lobby_ability1;
				sp.p4_ability2 = conn.lobby_ability2;
				sp.p4_ability3 = conn.lobby_ability3;
				break;
			}
		}
	}
	[BepInPlugin("com.deeroot.boplwithfriends", "BoplWithFriends", "0.3.1")]
	public class Plugin : BaseUnityPlugin
	{
		private static ManualLogSource _log;

		private static bool palettesLogged;

		private void Awake()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			_log = ((BaseUnityPlugin)this).Logger;
			Bwf.Log = ((BaseUnityPlugin)this).Logger;
			Bwf.MaxPlayersConfig = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxPlayers", 8, new ConfigDescription("Maximum number of players in an online lobby (2-16). All players need this mod; the host's setting is used for the match.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 16), Array.Empty<object>()));
			PatchEverythingIndividually();
			RaiseCaps();
			BwfDriver.Create();
			Bwf.Info(string.Format("{0} {1} loaded (MaxPlayers={2})", "com.deeroot.boplwithfriends", "0.3.1", Bwf.MaxPlayers));
		}

		private static void PatchEverythingIndividually()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			Harmony val = new Harmony("com.deeroot.boplwithfriends");
			List<string> list = new List<string>();
			Type[] types = typeof(Plugin).Assembly.GetTypes();
			Array.Sort(types, (Type a, Type b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
			Type[] array = types;
			foreach (Type type in array)
			{
				if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0)
				{
					try
					{
						new PatchClassProcessor(val, type).Patch();
						Bwf.Info("patched class " + type.Name);
					}
					catch (Exception ex)
					{
						list.Add(type.Name + ": " + ex.Message);
						Bwf.Error($"patch class {type.Name} FAILED: {ex}");
					}
				}
			}
			if (list.Count > 0)
			{
				Bwf.Warn(string.Format("{0} patch class(es) failed: [{1}]", list.Count, string.Join("; ", list)));
			}
		}

		internal static void RaiseCaps()
		{
			typeof(Constants).GetField("MAX_PLAYERS").SetValue(null, Bwf.MaxPlayers);
			FieldInfo fieldInfo = AccessTools.Field(typeof(AchievementHandler), "killsThisFrame");
			if (fieldInfo.GetValue(null) is int[] array && array.Length < Bwf.MaxPlayers)
			{
				fieldInfo.SetValue(null, new int[Bwf.MaxPlayers]);
			}
		}

		public static void LogPalettes()
		{
			if (palettesLogged)
			{
				return;
			}
			palettesLogged = true;
			foreach (TeamColors item in Resources.FindObjectsOfTypeAll(typeof(TeamColors)).Cast<TeamColors>())
			{
				string name = ((Object)item).name;
				TeamColor[] teamColors = item.teamColors;
				Bwf.Info($"TeamColors '{name}': {((teamColors != null) ? teamColors.Length : 0)} entries");
			}
			foreach (PlayerColors item2 in Resources.FindObjectsOfTypeAll(typeof(PlayerColors)).Cast<PlayerColors>())
			{
				string name2 = ((Object)item2).name;
				PlayerColor[] playerColors = item2.playerColors;
				Bwf.Info($"PlayerColors '{name2}': {((playerColors != null) ? playerColors.Length : 0)} entries");
			}
			foreach (ColorPool item3 in Resources.FindObjectsOfTypeAll(typeof(ColorPool)).Cast<ColorPool>())
			{
				Bwf.Info($"ColorPool '{((Object)item3).name}': {item3.colors?.Count ?? 0} colors");
			}
		}

		public static void EnsurePalettes()
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_0089: 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)
			//IL_0097: 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)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			foreach (TeamColors item in Resources.FindObjectsOfTypeAll(typeof(TeamColors)).Cast<TeamColors>())
			{
				if (item.teamColors == null || item.teamColors.Length >= Bwf.MaxPlayers)
				{
					continue;
				}
				int num = item.teamColors.Length;
				TeamColor[] array = (TeamColor[])(object)new TeamColor[Bwf.MaxPlayers];
				for (int i = 0; i < Bwf.MaxPlayers; i++)
				{
					array[i] = item.teamColors[i % num];
					if (i >= num)
					{
						TeamColor val = array[i];
						val.fill = ShiftHue(val.fill, i - num);
						val.border = ShiftHue(val.border, i - num);
						val.saturated = ShiftHue(val.saturated, i - num);
						val.team = i;
						array[i] = val;
					}
				}
				item.teamColors = array;
				Bwf.Info($"TeamColors '{((Object)item).name}' expanded {num} -> {array.Length}");
			}
			foreach (PlayerColors item2 in Resources.FindObjectsOfTypeAll(typeof(PlayerColors)).Cast<PlayerColors>())
			{
				if (item2.playerColors == null || item2.playerColors.Length >= Bwf.MaxPlayers)
				{
					continue;
				}
				int num2 = item2.playerColors.Length;
				PlayerColor[] array2 = (PlayerColor[])(object)new PlayerColor[Bwf.MaxPlayers];
				for (int j = 0; j < Bwf.MaxPlayers; j++)
				{
					PlayerColor val2 = item2.playerColors[j % num2];
					if (j >= num2)
					{
						val2.colorIndex = j;
						if ((Object)(object)val2.uiMaterial != (Object)null)
						{
							val2.uiMaterial = ShiftMaterialHue(val2.uiMaterial, j - num2);
						}
						if ((Object)(object)val2.playerMaterial != (Object)null)
						{
							val2.playerMaterial = ShiftMaterialHue(val2.playerMaterial, j - num2);
						}
					}
					array2[j] = val2;
				}
				item2.playerColors = array2;
				Bwf.Info($"PlayerColors '{((Object)item2).name}' expanded {num2} -> {array2.Length}");
			}
			foreach (ColorPool item3 in Resources.FindObjectsOfTypeAll(typeof(ColorPool)).Cast<ColorPool>())
			{
				if (item3.colors != null && item3.colors.Count < Bwf.MaxPlayers)
				{
					int count = item3.colors.Count;
					List<Material> list = new List<Material>(item3.colors);
					for (int k = count; k < Bwf.MaxPlayers; k++)
					{
						Material val3 = item3.colors[k % count];
						list.Add(((Object)(object)val3 != (Object)null) ? ShiftMaterialHue(val3, k - count) : null);
					}
					item3.colors = list;
					Bwf.Info($"ColorPool '{((Object)item3).name}' expanded {count} -> {list.Count}");
				}
			}
		}

		private static Color ShiftHue(Color c, int step)
		{
			//IL_0000: 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)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			float num2 = default(float);
			float num3 = default(float);
			float num = default(float);
			Color.RGBToHSV(c, ref num, ref num2, ref num3);
			num = (num + 0.618f * (float)step) % 1f;
			if (!(num2 <= 0.01f))
			{
				return Color.HSVToRGB(num, Mathf.Clamp01(num2), num3);
			}
			return c;
		}

		private static Material ShiftMaterialHue(Material m, int step)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			Material val = new Material(m);
			if (val.HasProperty("_Color"))
			{
				val.color = ShiftHue(val.color, step);
			}
			if (val.HasProperty("_BaseColor"))
			{
				val.SetColor("_BaseColor", ShiftHue(val.GetColor("_BaseColor"), step));
			}
			if (val.HasProperty("_ShadowColor"))
			{
				val.SetColor("_ShadowColor", ShiftHue(val.GetColor("_ShadowColor"), step));
			}
			((Object)val).name = ((Object)m).name + $"_bwf{step}";
			return val;
		}
	}
	public static class SpawnPatches
	{
		[HarmonyPatch(typeof(GameSessionHandler), "SpawnPlayers")]
		private static class SpawnPlayers_Patch
		{
			private static bool Prefix(GameSessionHandler __instance)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Expected O, but got Unknown
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Expected O, but got Unknown
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0092: Expected O, but got Unknown
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ae: Expected O, but got Unknown
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_021d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0222: Unknown result type (might be due to invalid IL or missing references)
				//IL_023e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0237: Unknown result type (might be due to invalid IL or missing references)
				//IL_0298: Unknown result type (might be due to invalid IL or missing references)
				//IL_0243: Unknown result type (might be due to invalid IL or missing references)
				//IL_0247: Unknown result type (might be due to invalid IL or missing references)
				//IL_0249: Unknown result type (might be due to invalid IL or missing references)
				//IL_0250: Unknown result type (might be due to invalid IL or missing references)
				//IL_0255: Unknown result type (might be due to invalid IL or missing references)
				//IL_0263: Unknown result type (might be due to invalid IL or missing references)
				//IL_0268: Unknown result type (might be due to invalid IL or missing references)
				//IL_026d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0272: Unknown result type (might be due to invalid IL or missing references)
				//IL_0277: Unknown result type (might be due to invalid IL or missing references)
				//IL_0279: Unknown result type (might be due to invalid IL or missing references)
				//IL_027e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0283: Unknown result type (might be due to invalid IL or missing references)
				//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_034d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0352: Unknown result type (might be due to invalid IL or missing references)
				//IL_0363: Unknown result type (might be due to invalid IL or missing references)
				//IL_036f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0376: Unknown result type (might be due to invalid IL or missing references)
				//IL_048d: Unknown result type (might be due to invalid IL or missing references)
				List<Player> list = PlayerHandler.Get().PlayerList();
				Bwf.Info($"SpawnPlayers: spawning {list.Count} players");
				SlimeController val = (SlimeController)Bwf.Get(__instance, typeof(GameSessionHandler), "PlayerPrefab");
				List<GameObject> list2 = (List<GameObject>)Bwf.Get(__instance, typeof(GameSessionHandler), "AbilityReadyIndicators");
				InputUpdater val2 = (InputUpdater)Bwf.Get(__instance, typeof(GameSessionHandler), "InputUpdaterPrefab");
				GameObject val3 = (GameObject)Bwf.Get(__instance, typeof(GameSessionHandler), "playerSpawnsRoot");
				TeamColors val4 = (TeamColors)Bwf.Get(__instance, typeof(GameSessionHandler), "teamColors");
				Vec2[] array = (Vec2[])Bwf.Get(__instance, typeof(GameSessionHandler), "teamSpawns");
				Fix val5 = (Fix)Bwf.Get(__instance, typeof(GameSessionHandler), "teammateSpawnSpacing");
				SlimeController[] array2 = (SlimeController[])(object)new SlimeController[list.Count];
				Bwf.Set(__instance, typeof(GameSessionHandler), "slimeControllers", array2);
				Bwf.Set(__instance, typeof(GameSessionHandler), "gameInProgress", true);
				int[] array3;
				try
				{
					array3 = (int[])Bwf.M(typeof(GameSessionHandler), "DifferentTeams").Invoke(__instance, null);
				}
				catch (Exception ex)
				{
					Bwf.Error("DifferentTeams failed: " + ex.Message);
					array3 = (from x in list.Select((Player p) => p.Team).Distinct()
						orderby x
						select x).ToArray();
				}
				int[] array4 = new int[Math.Max(array.Length, 1)];
				List<InputUpdater> list3 = new List<InputUpdater>();
				Vec2 val8 = default(Vec2);
				for (int num = 0; num < list.Count; num++)
				{
					int num2 = Array.IndexOf(array3, list[num].Team);
					if (num2 < 0)
					{
						num2 = num;
					}
					int num3 = num2 % array.Length;
					int num4 = array4[num3];
					list[num].playersAndClonesStillAlive = 1;
					Vec2 val6;
					if (num4 == 0)
					{
						val6 = array[num3];
					}
					else
					{
						int num5 = (num4 + 1) / 2;
						Fix val7 = ((num4 % 2 == 1) ? Fix.One : ((Fix)(-1L)));
						((Vec2)(ref val8))..ctor(val5, val5 * (Fix)0.5f);
						val6 = array[num3] + val8 * (Fix)(long)num5 * val7;
					}
					array4[num3]++;
					array2[num] = FixTransform.InstantiateFixed<SlimeController>(val, val6);
					array2[num].playerNumber = list[num].Id;
					((Component)array2[num]).transform.SetParent(val3.transform);
					array2[num].GetPlayerSprite().sprite = null;
					((Renderer)array2[num].GetPlayerSprite()).material = list[num].Color;
					List<AbilityMonoBehaviour> list4 = new List<AbilityMonoBehaviour>();
					list[num].CurrentAbilities = new List<GameObject>();
					for (int num6 = 0; num6 < list[num].Abilities.Count; num6++)
					{
						RandomAbility component = list[num].Abilities[num6].GetComponent<RandomAbility>();
						if ((Object)(object)component != (Object)null)
						{
							NamedSprite randomAbilityPrefab = RandomAbility.GetRandomAbilityPrefab(component.abilityIcons, component.abilityIcons_demo);
							list[num].AbilityIcons[num6] = randomAbilityPrefab.sprite;
							GameObject val9 = FixTransform.InstantiateFixed(randomAbilityPrefab.associatedGameObject, Vec2.zero);
							val9.SetActive(false);
							list[num].CurrentAbilities.Add(val9);
							list4.Add(val9.GetComponent<AbilityMonoBehaviour>());
						}
						else
						{
							GameObject val10 = FixTransform.InstantiateFixed(list[num].Abilities[num6], Vec2.zero);
							val10.SetActive(false);
							list[num].CurrentAbilities.Add(val10);
							list4.Add(val10.GetComponent<AbilityMonoBehaviour>());
						}
					}
					array2[num].abilities = list4;
					AbilityReadyIndicator[] array5 = (AbilityReadyIndicator[])(object)new AbilityReadyIndicator[3];
					for (int num7 = 0; num7 < 3; num7++)
					{
						array5[num7] = Object.Instantiate<GameObject>(list2[num7], val3.transform).GetComponent<AbilityReadyIndicator>();
						array5[num7].Init();
						int num8 = Math.Min(list[num].Team, val4.teamColors.Length - 1);
						array5[num7].SetColor(val4.teamColors[num8].fill);
						((Component)array5[num7]).GetComponent<FollowTransform>().Leader = ((Component)array2[num]).transform;
						((Component)array5[num7]).gameObject.SetActive(false);
						if (num7 < list[num].AbilityIcons.Count)
						{
							array5[num7].SetSprite(list[num].AbilityIcons[num7], true);
						}
					}
					array2[num].AbilityReadyIndicators = array5;
					Bwf.Set(__instance, typeof(GameSessionHandler), "gameOver", false);
					if (list[num].IsLocalPlayer)
					{
						InputUpdater val11 = Object.Instantiate<InputUpdater>(val2);
						PlayerInput component2 = ((Component)val11).GetComponent<PlayerInput>();
						val11.Claim(list[num].Id);
						val11.Init(list[num].Id);
						component2.neverAutoSwitchControlSchemes = true;
						component2.ActivateInput();
						list3.Add(val11);
					}
				}
				return false;
			}
		}
	}
	public static class StartPatches
	{
		[HarmonyPatch(typeof(CharacterSelectHandler_online), "ForceStartGame")]
		private static class ForceStartGame_Patch
		{
			private static bool Prefix(PlayerColors pcs = null)
			{
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Expected O, but got Unknown
				//IL_0058: 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_0069: 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_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e8: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
				//IL_0105: 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_0111: Unknown result type (might be due to invalid IL or missing references)
				//IL_0117: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0123: Unknown result type (might be due to invalid IL or missing references)
				//IL_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
				//IL_0237: Unknown result type (might be due to invalid IL or missing references)
				//IL_024a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0280: Unknown result type (might be due to invalid IL or missing references)
				//IL_0285: Unknown result type (might be due to invalid IL or missing references)
				//IL_0289: Unknown result type (might be due to invalid IL or missing references)
				//IL_0297: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_0301: Unknown result type (might be due to invalid IL or missing references)
				//IL_033c: Unknown result type (might be due to invalid IL or missing references)
				if (SteamManager.startParameters.nrOfPlayers <= 4 && !Bwf.FakeTestMode && Bwf.Extras.Count == 0)
				{
					return true;
				}
				CharacterSelectHandler_online val = (CharacterSelectHandler_online)Bwf.Get(typeof(CharacterSelectHandler_online), "selfRef");
				if ((Object)(object)val == (Object)null)
				{
					return true;
				}
				if ((Object)(object)pcs == (Object)null)
				{
					pcs = val.playerColors;
				}
				StartRequestPacket startParameters = SteamManager.startParameters;
				Updater.ReInit();
				List<Player> list = new List<Player>();
				Updater.InitSeed(startParameters.seed);
				int built = 0;
				InvokeInit(list, 1, startParameters.p1_color, startParameters.p1_team, startParameters.p1_ability1, startParameters.p1_ability2, startParameters.p1_ability3, startParameters.nrOfAbilites, pcs, startParameters, ref built);
				InvokeInit(list, 2, startParameters.p2_color, startParameters.p2_team, startParameters.p2_ability1, startParameters.p2_ability2, startParameters.p2_ability3, startParameters.nrOfAbilites, pcs, startParameters, ref built);
				InvokeInit(list, 3, startParameters.p3_color, startParameters.p3_team, startParameters.p3_ability1, startParameters.p3_ability2, startParameters.p3_ability3, startParameters.nrOfAbilites, pcs, startParameters, ref built);
				InvokeInit(list, 4, startParameters.p4_color, startParameters.p4_team, startParameters.p4_ability1, startParameters.p4_ability2, startParameters.p4_ability3, startParameters.nrOfAbilites, pcs, startParameters, ref built);
				foreach (Bwf.ExtraPlayer item in Bwf.Extras.Values.OrderBy((Bwf.ExtraPlayer x) => x.Slot))
				{
					InvokeInit(list, item.Slot, item.Color, item.Team, (byte)item.Ab1, (byte)item.Ab2, (byte)item.Ab3, startParameters.nrOfAbilites, pcs, startParameters, ref built);
				}
				Player val2 = null;
				ulong value = SteamClient.SteamId.Value;
				if (GameLobby.isPlayingAReplay)
				{
					val2 = list[0];
				}
				else
				{
					foreach (Player item2 in list)
					{
						if (IdForSlot(startParameters, item2.Id) == value)
						{
							val2 = item2;
							break;
						}
					}
				}
				for (int num = 0; num < list.Count; num++)
				{
					list[num].steamId = SteamId.op_Implicit(IdForSlot(startParameters, list[num].Id));
				}
				val2.IsLocalPlayer = true;
				PlayerInit val3 = (PlayerInit)Bwf.Get(typeof(CharacterSelectHandler_online), "localPlayerInit");
				val2.inputDevice = val3.inputDevice;
				val2.UsesKeyboardAndMouse = val3.usesKeyboardMouse;
				val2.CustomKeyBinding = val3.keybindOverride;
				Bwf.Set(typeof(CharacterSelectHandler_online), "startButtonAvailable", false);
				PlayerHandler.Get().SetPlayerList(list);
				SteamManager.instance.StartHostedGame();
				AudioManager obj = AudioManager.Get();
				if (obj != null)
				{
					obj.Play("startGame");
				}
				GameSession.Init();
				if (GameLobby.isPlayingAReplay)
				{
					SceneManager.LoadScene(startParameters.currentLevel + 6);
				}
				else
				{
					SceneManager.LoadScene("Level1");
				}
				if (!WinnerTriangleCanvas.HasBeenSpawned)
				{
					SceneManager.LoadScene("winnerTriangle", (LoadSceneMode)1);
				}
				Bwf.Info($"game started with {list.Count} players ({startParameters.nrOfPlayers} declared)");
				return false;
			}

			private static void InvokeInit(List<Player> list, int slot, int color, int team, byte ab1, byte ab2, byte ab3, byte nrOfAbilites, PlayerColors pcs, StartRequestPacket sp, ref int built)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_0092: Expected O, but got Unknown
				if (ab1 != 0 && sp.nrOfPlayers > built && slot <= sp.nrOfPlayers)
				{
					object[] parameters = new object[8]
					{
						slot,
						(byte)color,
						(byte)team,
						ab1,
						ab2,
						ab3,
						nrOfAbilites,
						pcs
					};
					list.Add((Player)Bwf.M(typeof(CharacterSelectHandler_online), "InitPlayer").Invoke(null, parameters));
					built++;
				}
			}

			private static ulong IdForSlot(StartRequestPacket sp, int slot)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				Bwf.ExtraPlayer value;
				return slot switch
				{
					1 => sp.p1_id, 
					2 => sp.p2_id, 
					3 => sp.p3_id, 
					4 => sp.p4_id, 
					_ => Bwf.Extras.TryGetValue(slot, out value) ? value.SteamId : 0, 
				};
			}
		}
	}
	public static class SteamFramePatches
	{
		[HarmonyPatch(typeof(SteamFrame), "Update")]
		private static class SteamFrame_Update_Grow_Patch
		{
			private static void Prefix(SteamFrame __instance)
			{
				try
				{
					EnsureSquares(__instance, Bwf.MaxPlayers - 1);
				}
				catch (Exception arg)
				{
					Bwf.Error($"SteamFrame grow failed: {arg}");
					grownFailed = true;
				}
			}
		}

		private static bool grownFailed;

		private static void EnsureSquares(SteamFrame frame, int count)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Expected O, but got Unknown
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Expected O, but got Unknown
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Expected O, but got Unknown
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_0394: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
			if (grownFailed || frame.squares.Count >= count || frame.squares.Count < 2)
			{
				return;
			}
			SteamFrameButton c = frame.squares[0];
			Vector2 val = Rect((Component)(object)frame.squares[1]).anchoredPosition - Rect((Component)(object)c).anchoredPosition;
			Image val2 = frame.lookingForPlayersCircles[0];
			Vector2 val3 = ((frame.lookingForPlayersCircles.Length > 1) ? (((Graphic)frame.lookingForPlayersCircles[1]).rectTransform.anchoredPosition - ((Graphic)val2).rectTransform.anchoredPosition) : val);
			int count2 = frame.squares.Count;
			Image[] array = (Image[])(object)new Image[count];
			Array.Copy(frame.lookingForPlayersCircles, array, Math.Min(frame.lookingForPlayersCircles.Length, count));
			SteamFrameButton val4 = frame.squares[count2 - 1];
			Image val5 = frame.lookingForPlayersCircles[Math.Min(count2, frame.lookingForPlayersCircles.Length) - 1];
			for (int i = count2; i < count; i++)
			{
				GameObject obj = Object.Instantiate<GameObject>(((Component)val4).gameObject, ((Component)val4).transform.parent, false);
				((Object)obj).name = $"{((Object)((Component)val4).gameObject).name} (bwf {i})";
				Rect((Component)(object)obj.GetComponent<SteamFrameButton>()).anchoredPosition = Rect((Component)(object)val4).anchoredPosition + val * (float)(i - count2 + 1);
				SteamFrameButton component = obj.GetComponent<SteamFrameButton>();
				if ((Object)(object)((Graphic)component.image).material != (Object)null)
				{
					((Graphic)component.image).material = new Material(((Graphic)component.image).material);
				}
				((Graphic)component.image).material.SetTexture("_ProfileTexture", (Texture)(object)Texture2D.blackTexture);
				((Graphic)component.image).materialForRendering.SetColor("_Blue", Color.white);
				int kickIndex = i;
				component.button.onClick = new ButtonClickedEvent();
				((UnityEvent)component.button.onClick).AddListener((UnityAction)delegate
				{
					frame.ClickKickPlayer(kickIndex);
				});
				obj.SetActive(false);
				frame.squares.Add(component);
				Image component2 = Object.Instantiate<GameObject>(((Component)val5).gameObject, ((Component)val5).transform.parent, false).GetComponent<Image>();
				((Graphic)component2).rectTransform.anchoredPosition = ((Graphic)val5).rectTransform.anchoredPosition + val3 * (float)(i - count2 + 1);
				((Behaviour)component2).enabled = false;
				array[i] = component2;
			}
			frame.lookingForPlayersCircles = array;
			int num = count + 1;
			if (num > 8)
			{
				float num2 = 8f / (float)num;
				Vector2 anchoredPosition = Rect((Component)(object)frame.SelfSquare).anchoredPosition;
				Vector2 val6 = val;
				((Component)frame.SelfSquare).transform.localScale = ((Component)frame.SelfSquare).transform.localScale * num2;
				for (int num3 = 0; num3 < frame.squares.Count; num3++)
				{
					RectTransform val7 = Rect((Component)(object)frame.squares[num3]);
					((Transform)val7).localScale = ((Transform)val7).localScale * num2;
					val7.anchoredPosition = anchoredPosition + val6 * num2 * (float)(num3 + 1);
					RectTransform rectTransform = ((Graphic)array[num3]).rectTransform;
					((Transform)rectTransform).localScale = ((Transform)rectTransform).localScale * num2;
					rectTransform.anchoredPosition = val7.anchoredPosition;
				}
			}
			int[] array2 = new int[count];
			int[] array3 = (int[])Bwf.Get(frame, typeof(SteamFrame), "currentSquareColors");
			for (int num4 = 0; num4 < count; num4++)
			{
				array2[num4] = ((num4 < array3.Length) ? array3[num4] : (-1));
			}
			Bwf.Set(frame, typeof(SteamFrame), "currentSquareColors", array2);
			Bwf.Set(frame, typeof(SteamFrame), "nrOfSquares", -1);
			Bwf.Info($"SteamFrame: avatar squares {count2} -> {count}");
		}

		private static RectTransform Rect(Component c)
		{
			return c.GetComponent<RectTransform>();
		}
	}
	public static class TestMode
	{
		[HarmonyPatch(typeof(CharacterSelectHandler_online), "Awake")]
		private static class CharSelect_TestButton_Patch
		{
			[Serializable]
			[CompilerGenerated]
			private sealed class <>c
			{
				public static readonly <>c <>9 = new <>c();

				public static UnityAction <>9__0_0;

				internal void <Postfix>b__0_0()
				{
					StartFakeGame(Bwf.MaxPlayers);
				}
			}

			private static void Postfix(CharacterSelectHandler_online __instance)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Expected O, but got Unknown
				//IL_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0124: Unknown result type (might be due to invalid IL or missing references)
				//IL_012c: Unknown result type (might be due to invalid IL or missing references)
				//IL_010f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0114: Unknown result type (might be due to invalid IL or missing references)
				//IL_011a: Expected O, but got Unknown
				if (Bwf.MaxPlayers <= 4 || (Object)(object)testButtonRoot != (Object)null)
				{
					return;
				}
				try
				{
					Canvas componentInChildren = ((Component)((Component)__instance).transform.root).GetComponentInChildren<Canvas>();
					Transform val = (((Object)(object)componentInChildren != (Object)null) ? ((Component)componentInChildren).transform : ((Component)__instance).transform.parent);
					GameObject val2 = new GameObject("BWF_TestButton_CharSelect", new Type[3]
					{
						typeof(RectTransform),
						typeof(Image),
						typeof(Button)
					});
					RectTransform component = val2.GetComponent<RectTransform>();
					((Transform)component).SetParent(val, false);
					component.anchorMin = new Vector2(0.43f, 0.01f);
					component.anchorMax = new Vector2(0.57f, 0.055f);
					component.offsetMin = Vector2.zero;
					component.offsetMax = Vector2.zero;
					((Graphic)val2.GetComponent<Image>()).color = new Color(0.6f, 0.3f, 0.35f, 0.9f);
					ButtonClickedEvent onClick = val2.GetComponent<Button>().onClick;
					object obj = <>c.<>9__0_0;
					if (obj == null)
					{
						UnityAction val3 = delegate
						{
							StartFakeGame(Bwf.MaxPlayers);
						};
						<>c.<>9__0_0 = val3;
						obj = (object)val3;
					}
					((UnityEvent)onClick).AddListener((UnityAction)obj);
					MakeLabel(component, Vector2.zero, Vector2.one, (TextAnchor)4, 30, Color.white, $"BWF TEST ({Bwf.MaxPlayers})", "charselect");
					testButtonRoot = val2;
					Bwf.Info("char-select test button created");
				}
				catch (Exception arg)
				{
					Bwf.Error($"char-select test button failed: {arg}");
				}
			}
		}

		[HarmonyPatch(typeof(MainMenu), "Start")]
		private static class MainMenu_Start_Overlay_Patch
		{
			[CompilerGenerated]
			private static class <>O
			{
				public static UnityAction <0>__CycleMaxPlayers;
			}

			[Serializable]
			[CompilerGenerated]
			private sealed class <>c
			{
				public static readonly <>c <>9 = new <>c();

				public static UnityAction <>9__1_0;

				internal void <BuildOverlay>b__1_0()
				{
					if (GameSession.inMenus)
					{
						StartFakeGame(Bwf.MaxPlayers);
					}
				}
			}

			private static void Postfix(MainMenu __instance)
			{
				try
				{
					if ((Object)(object)overlayRoot != (Object)null)
					{
						RefreshOverlayLabel();
						return;
					}
					BuildOverlay(__instance);
					RefreshOverlayLabel();
				}
				catch (Exception arg)
				{
					Bwf.Error($"overlay build failed: {arg}");
				}
			}

			private static void BuildOverlay(MainMenu menu)
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Expected O, but got Unknown
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
				//IL_0103: Unknown result type (might be due to invalid IL or missing references)
				//IL_0108: Unknown result type (might be due to invalid IL or missing references)
				//IL_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0179: Unknown result type (might be due to invalid IL or missing references)
				//IL_017f: Expected O, but got Unknown
				//IL_0198: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_025a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0260: Expected O, but got Unknown
				//IL_0279: Unknown result type (might be due to invalid IL or missing references)
				//IL_028e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0299: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_020c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0211: Unknown result type (might be due to invalid IL or missing references)
				//IL_0217: Expected O, but got Unknown
				//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02fc: Expected O, but got Unknown
				GameObject val = new GameObject("BWF_OverlayCanvas", new Type[3]
				{
					typeof(Canvas),
					typeof(CanvasScaler),
					typeof(GraphicRaycaster)
				});
				Canvas component = val.GetComponent<Canvas>();
				component.renderMode = (RenderMode)0;
				component.sortingOrder = 29000;
				CanvasScaler component2 = val.GetComponent<CanvasScaler>();
				component2.uiScaleMode = (ScaleMode)1;
				component2.referenceResolution = new Vector2(1920f, 1080f);
				component2.matchWidthOrHeight = 0.5f;
				RectTransform component3 = new GameObject("BWF_Overlay", new Type[2]
				{
					typeof(RectTransform),
					typeof(CanvasGroup)
				}).GetComponent<RectTransform>();
				((Transform)component3).SetParent(val.transform, false);
				component3.anchorMin = new Vector2(0.012f, 0.8f);
				component3.anchorMax = new Vector2(0.2f, 0.915f);
				component3.offsetMin = Vector2.zero;
				component3.offsetMax = Vector2.zero;
				overlayLabel = MakeLabel(component3, new Vector2(0f, 0.55f), Vector2.one, (TextAnchor)3, 34, new Color(0.35f, 0.8f, 1f), $"BWF Players: {Bwf.ConfiguredMaxPlayers}", "label");
				GameObject val2 = new GameObject("BWF_CycleButton", new Type[3]
				{
					typeof(RectTransform),
					typeof(Image),
					typeof(Button)
				});
				RectTransform component4 = val2.GetComponent<RectTransform>();
				((Transform)component4).SetParent((Transform)(object)component3, false);
				component4.anchorMin = new Vector2(0f, 0.05f);
				component4.anchorMax = new Vector2(0.48f, 0.5f);
				component4.offsetMin = Vector2.zero;
				component4.offsetMax = Vector2.zero;
				((Graphic)val2.GetComponent<Image>()).color = new Color(0.15f, 0.4f, 0.6f, 0.85f);
				ButtonClickedEvent onClick = val2.GetComponent<Button>().onClick;
				object obj = <>O.<0>__CycleMaxPlayers;
				if (obj == null)
				{
					UnityAction val3 = CycleMaxPlayers;
					<>O.<0>__CycleMaxPlayers = val3;
					obj = (object)val3;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				MakeLabelChild(component4, "cycle", 26);
				GameObject val4 = new GameObject("BWF_TestButton", new Type[3]
				{
					typeof(RectTransform),
					typeof(Image),
					typeof(Button)
				});
				RectTransform component5 = val4.GetComponent<RectTransform>();
				((Transform)component5).SetParent((Transform)(object)component3, false);
				component5.anchorMin = new Vector2(0.52f, 0.05f);
				component5.anchorMax = new Vector2(1f, 0.5f);
				component5.offsetMin = Vector2.zero;
				component5.offsetMax = Vector2.zero;
				((Graphic)val4.GetComponent<Image>()).color = new Color(0.6f, 0.3f, 0.35f, 0.85f);
				ButtonClickedEvent onClick2 = val4.GetComponent<Button>().onClick;
				object obj2 = <>c.<>9__1_0;
				if (obj2 == null)
				{
					UnityAction val5 = delegate
					{
						if (GameSession.inMenus)
						{
							StartFakeGame(Bwf.MaxPlayers);
						}
					};
					<>c.<>9__1_0 = val5;
					obj2 = (object)val5;
				}
				((UnityEvent)onClick2).AddListener((UnityAction)obj2);
				MakeLabelChild(component5, "test", 26);
				overlayRoot = val;
				Bwf.Info("MainMenu overlay built (cycle MaxPlayers / test fake lobby)");
			}
		}

		private static Text overlayLabel;

		private static GameObject overlayRoot;

		private static GameObject toastRoot;

		private static Text toastText;

		private static float toastUntil;

		private static float nextProbe;

		private static string lastProbeState = "";

		private static GameObject testButtonRoot;

		private static void EnsureToastRoot()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			if (!((Object)(object)toastRoot != (Object)null))
			{
				GameObject val = new GameObject("BWF_ToastCanvas", new Type[2]
				{
					typeof(Canvas),
					typeof(CanvasGroup)
				});
				Object.DontDestroyOnLoad((Object)val);
				Canvas component = val.GetComponent<Canvas>();
				component.renderMode = (RenderMode)0;
				component.sortingOrder = 30000;
				Transform transform = ((Component)component).transform;
				toastText = MakeLabel((RectTransform)(object)((transform is RectTransform) ? transform : null), Vector2.zero, Vector2.one, (TextAnchor)4, 34, new Color(1f, 0.85f, 0.3f), "", "toast");
				RectTransform component2 = ((Component)toastText).GetComponent<RectTransform>();
				component2.anchorMin = new Vector2(0.15f, 0.02f);
				component2.anchorMax = new Vector2(0.85f, 0.09f);
				component2.offsetMin = Vector2.zero;
				component2.offsetMax = Vector2.zero;
				toastRoot = val;
				toastRoot.SetActive(false);
			}
		}

		public static void Toast(string msg, float seconds = 6f)
		{
			EnsureToastRoot();
			toastText.text = msg;
			toastRoot.SetActive(true);
			toastUntil = Time.realtimeSinceStartup + seconds;
			Bwf.Info("[toast] " + msg);
		}

		private static void UpdateToast()
		{
			if (!((Object)(object)toastRoot == (Object)null) && toastRoot.activeSelf && Time.realtimeSinceStartup >= toastUntil)
			{
				toastRoot.SetActive(false);
			}
		}

		public static void OnUpdate()
		{
			UpdateToast();
			KeyboardProbe();
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return;
			}
			if (((ButtonControl)current.f7Key).wasPressedThisFrame)
			{
				CycleMaxPlayers();
			}
			if (((ButtonControl)current.f8Key).wasPressedThisFrame)
			{
				StartFakeGame(Bwf.MaxPlayers);
			}
			if ((Object)(object)testButtonRoot != (Object)null)
			{
				bool flag = (Object)(object)SteamManager.instance == (Object)null || SteamManager.instance.connectedPlayers.Count == 0;
				if (testButtonRoot.activeSelf != flag)
				{
					testButtonRoot.SetActive(flag);
				}
			}
		}

		private static bool OthersInLobby()
		{
			if ((Object)(object)SteamManager.instance != (Object)null)
			{
				return SteamManager.instance.connectedPlayers.Count > 0;
			}
			return false;
		}

		private static void KeyboardProbe()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if (GameSession.inMenus && !(Time.realtimeSinceStartup < nextProbe))
			{
				nextProbe = Time.realtimeSinceStartup + 1f;
				Keyboard current = Keyboard.current;
				string text = ((current == null) ? "Keyboard.current=NULL" : $"current={((InputControl)current).displayName ?? ((InputControl)current).name} enabled={((InputDevice)current).enabled} anyKey={((ButtonControl)current.anyKey).wasPressedThisFrame} devices={((IEnumerable<InputDevice>)(object)InputSystem.devices).Count((InputDevice d) => d is Keyboard)}");
				if (text != lastProbeState)
				{
					lastProbeState = text;
					Bwf.Info("keyboard probe: " + text);
				}
			}
		}

		public static void CycleMaxPlayers()
		{
			if (OthersInLobby())
			{
				Toast("BWF: change the player count before friends join (it recreates the lobby)", 5f);
				return;
			}
			int[] array = new int[3] { 4, 8, 16 };
			int num = Array.IndexOf(array, Bwf.ConfiguredMaxPlayers);
			if (num < 0)
			{
				num = 0;
			}
			SetMaxPlayers(array[(num + 1) % array.Length]);
		}

		public static void SetMaxPlayers(int players)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			players = Math.Clamp(players, 2, 16);
			Bwf.MaxPlayersConfig.Value = players;
			Bwf.Info($"MaxPlayers set to {players}");
			Toast($"MaxPlayers set to {players}", 3f);
			if (Bwf.MaxPlayers > 4)
			{
				Plugin.RaiseCaps();
			}
			SteamManager instance = SteamManager.instance;
			if ((Object)(object)instance != (Object)null && SteamId.op_Implicit(((Lobby)(ref instance.currentLobby)).Id) != 0L)
			{
				instance.LeaveLobby();
				Bwf.Info("recreated lobby with new capacity");
				Toast($"lobby recreated, capacity {players}");
			}
			RefreshOverlayLabel();
		}

		public static void StartFakeGame(int players)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				players = Math.Clamp(players, 2, 16);
				if (OthersInLobby())
				{
					Toast("BWF test is solo-only: other players are in your lobby");
					return;
				}
				if (!GameSession.inMenus)
				{
					Toast("BWF test: start a fake match from the menus");
					return;
				}
				if ((Object)(CharacterSelectHandler_online)Bwf.Get(typeof(CharacterSelectHandler_online), "selfRef") == (Object)null)
				{
					Toast("BWF test: go ONLINE (online play -> wait until you see your slime + Ready button), then press F8 again");
					return;
				}
				NamedSpriteList abilityIcons = SteamManager.instance.abilityIcons;
				int num = -1;
				for (int i = 1; i < abilityIcons.sprites.Count; i++)
				{
					if (num >= 0)
					{
						break;
					}
					if ((Object)(object)abilityIcons.sprites[i].sprite != (Object)null && (Object)(object)abilityIcons.sprites[i].associatedGameObject != (Object)null)
					{
						num = i;
					}
				}
				if (num < 0)
				{
					Bwf.Warn("no ability sprite with index >= 1 available; aborting fake lobby");
					Toast("BWF test: no ability icons found");
					return;
				}
				int num2 = CountTeamPalette();
				int num3 = CountColorPalette();
				StartRequestPacket startParameters = new StartRequestPacket
				{
					seqNum = 1,
					seed = (uint)Environment.TickCount,
					frameBufferSize = 8,
					isDemoMask = byte.MaxValue,
					nrOfAbilites = (byte)Settings.Get().NumberOfAbilities,
					currentLevel = GameSession.CurrentLevel(),
					nrOfPlayers = (byte)players,
					p1_id = SteamClient.SteamId.Value,
					p1_color = 1,
					p1_team = 0,
					p1_ability1 = (byte)num,
					p1_ability2 = (byte)num,
					p1_ability3 = (byte)num
				};
				Bwf.ResetExtras();
				Bwf.ResetExtraInputQueues();
				for (int j = 2; j <= players; j++)
				{
					Bwf.Extras[j] = new Bwf.ExtraPlayer
					{
						Slot = j,
						SteamId = 240uL + (ulong)j,
						Color = (j - 1) % num3,
						Team = (j - 1) % num2,
						Ab1 = (byte)num,
						Ab2 = (byte)num,
						Ab3 = (byte)num
					};
				}
				Bwf.FakeTestMode = true;
				PlayerInit val = (PlayerInit)Bwf.Get(typeof(CharacterSelectHandler_online), "localPlayerInit");
				val.usesKeyboardMouse = true;
				val.inputDevice = (InputDevice)(object)Keyboard.current;
				val.keybindOverride = null;
				Bwf.Set(typeof(CharacterSelectHandler_online), "localPlayerInit", val);
				SteamManager.startParameters = startParameters;
				Bwf.Info($"FAKE LOBBY: {players} players (icon {num}, teamPalette {num2}, colorPalette {num3})");
				Toast($"BWF test: {players} players staged. On the ability screen: pick your abilities, press START (jump) to begin the round", 12f);
				CharacterSelectHandler_online.ForceStartGame((PlayerColors)null);
			}
			catch (Exception arg)
			{
				Bwf.Error($"fake lobby failed: {arg}");
				Toast("BWF test failed — check the BepInEx log", 8f);
			}
		}

		private static int CountTeamPalette()
		{
			foreach (TeamColors item in Resources.FindObjectsOfTypeAll(typeof(TeamColors)).Cast<TeamColors>())
			{
				if (item.teamColors != null && item.teamColors.Length != 0)
				{
					return item.teamColors.Length;
				}
			}
			return 4;
		}

		private static int CountColorPalette()
		{
			foreach (PlayerColors item in Resources.FindObjectsOfTypeAll(typeof(PlayerColors)).Cast<PlayerColors>())
			{
				if (item.playerColors != null && item.playerColors.