Decompiled source of ChaosParty v1.2.0

ChaosParty.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using MenuLib;
using MenuLib.MonoBehaviors;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.Localization;
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("ChaosParty")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0+6489070d410b6acfd51c0e305ea5167b5c9d28ef")]
[assembly: AssemblyProduct("ChaosParty")]
[assembly: AssemblyTitle("ChaosParty")]
[assembly: AssemblyVersion("1.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChaosParty
{
	internal static class Banner
	{
		private const byte EventCode = 167;

		private static readonly FieldRef<MoonUI, List<MoonAttribute>> attributes = AccessTools.FieldRefAccess<MoonUI, List<MoonAttribute>>("attributes");

		private static readonly FieldRef<MoonUI, bool> stateImpulse = AccessTools.FieldRefAccess<MoonUI, bool>("stateImpulse");

		private static readonly FieldRef<MoonUI, State> moonState = AccessTools.FieldRefAccess<MoonUI, State>("state");

		internal static bool Showing;

		private static readonly FieldRef<RoundDirector, bool> allExtracted = AccessTools.FieldRefAccess<RoundDirector, bool>("allExtractionPointsCompleted");

		internal static bool MoonIdle
		{
			get
			{
				if (!((Object)(object)MoonUI.instance == (Object)null))
				{
					if ((int)moonState.Invoke(MoonUI.instance) == 0)
					{
						return !stateImpulse.Invoke(MoonUI.instance);
					}
					return false;
				}
				return true;
			}
		}

		private static bool LevelOver
		{
			get
			{
				if (SemiFunc.RunIsLevel() && !((Object)(object)RoundDirector.instance == (Object)null))
				{
					return !allExtracted.Invoke(RoundDirector.instance);
				}
				return true;
			}
		}

		internal static void Init()
		{
			PhotonNetwork.NetworkingClient.EventReceived += OnEvent;
		}

		internal static void Send(string title, string[] lines, bool endOfLevel = false)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			if (SemiFunc.IsMultiplayer() && PhotonNetwork.InRoom)
			{
				try
				{
					PhotonNetwork.RaiseEvent((byte)167, (object)new object[3] { title, lines, endOfLevel }, new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					}, SendOptions.SendReliable);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Banner send failed: " + ex.Message));
				}
			}
			Runner.Run(Show(title, lines, endOfLevel));
		}

		private static void OnEvent(EventData data)
		{
			if (data.Code != 167)
			{
				return;
			}
			try
			{
				if (!(data.CustomData is object[] array) || array.Length < 2)
				{
					return;
				}
				string text = array[0] as string;
				string[] lines = (array[1] as string[]) ?? new string[0];
				if (string.IsNullOrEmpty(text))
				{
					return;
				}
				bool flag = default(bool);
				int num;
				if (array.Length > 2)
				{
					object obj = array[2];
					if (obj is bool)
					{
						flag = (bool)obj;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				bool endOfLevel = (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				Runner.Run(Show(text, lines, endOfLevel));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Banner receive failed: " + ex.Message));
			}
		}

		private static IEnumerator Show(string title, string[] lines, bool endOfLevel)
		{
			float timeout = 90f;
			while (timeout > 0f && (!SemiFunc.RunIsLevel() || !((Object)(object)LevelGenerator.Instance != (Object)null) || !LevelGenerator.Instance.Generated || !((Object)(object)GameDirector.instance != (Object)null) || (int)GameDirector.instance.currentState != 2 || !((Object)(object)MoonUI.instance != (Object)null) || !MoonIdle || Showing))
			{
				if (endOfLevel && LevelOver)
				{
					yield break;
				}
				timeout -= Time.deltaTime;
				yield return null;
			}
			if (!(timeout <= 0f) && (!endOfLevel || !LevelOver))
			{
				MoonUI ui = MoonUI.instance;
				RawImage[] array = (RawImage[])(object)new RawImage[4] { ui.moonGraphicPreviousest, ui.moonGraphicPrevious, ui.moonGraphicCurrent, ui.moonGraphicNext };
				foreach (RawImage obj in array)
				{
					obj.texture = null;
					((Graphic)obj).color = Color.clear;
				}
				((TMP_Text)ui.textTitle).text = title;
				attributes.Invoke(ui) = ((IEnumerable<string>)lines).Select((Func<string, MoonAttribute>)((string l) => new MoonAttribute
				{
					text = l
				})).ToList();
				Showing = true;
				ui.SetState((State)1);
				Plugin.Log.LogInfo((object)("[Banner] " + title + ": " + string.Join(" | ", lines)));
				timeout = 40f;
				yield return null;
				while (timeout > 0f && (Object)(object)MoonUI.instance == (Object)(object)ui && (Object)(object)ui != (Object)null && moonState.Invoke(ui))
				{
					timeout -= Time.deltaTime;
					yield return null;
				}
				Showing = false;
			}
		}
	}
	[HarmonyPatch(typeof(MoonUI), "Tutorials")]
	internal static class BannerTutorialPatch
	{
		private static bool Prefix()
		{
			return !Banner.Showing;
		}
	}
	internal static class Cues
	{
		private static readonly FieldRef<AmbienceBreakers, PhotonView> breakersView = AccessTools.FieldRefAccess<AmbienceBreakers, PhotonView>("photonView");

		internal static void Stinger()
		{
			//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_00e4: 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_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				AmbienceBreakers instance = AmbienceBreakers.instance;
				List<LevelAmbience> list = LevelGenerator.Instance?.Level?.AmbiencePresets?.Where((LevelAmbience a) => (Object)(object)a != (Object)null && a.breakers != null && a.breakers.Count > 0).ToList();
				if ((Object)(object)instance == (Object)null || list == null || list.Count == 0)
				{
					return;
				}
				LevelAmbience val = list[Random.Range(0, list.Count)];
				int num = Random.Range(0, val.breakers.Count);
				List<Vector3> list2 = new List<Vector3>();
				foreach (PlayerAvatar item in Upgrades.Players())
				{
					Vector3 pos = ((Component)item).transform.position;
					if (!list2.Any((Vector3 s) => Vector3.Distance(s, pos) < 12f))
					{
						list2.Add(pos);
					}
				}
				PhotonView val2 = (SemiFunc.IsMultiplayer() ? breakersView.Invoke(instance) : null);
				foreach (Vector3 item2 in list2)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						val2.RPC("PlaySoundRPC", (RpcTarget)0, new object[3]
						{
							item2,
							((Object)val).name,
							num
						});
					}
					else
					{
						instance.PlaySoundRPC(item2, ((Object)val).name, num, default(PhotonMessageInfo));
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Stinger failed: " + ex.Message));
			}
		}

		internal static void Speak(string text)
		{
			if (!Plugin.EventSpeak.Value || string.IsNullOrWhiteSpace(text))
			{
				return;
			}
			try
			{
				PlayerAvatar instance = PlayerAvatar.instance;
				if (instance != null)
				{
					instance.ChatMessageSend(text.TrimStart('/'), (string)null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Speak failed: " + ex.Message));
			}
		}
	}
	internal static class ChaosMenu
	{
		private class Category
		{
			public string Name;

			public Func<ConfigEntry<bool>[]> Features;

			public Action Build;

			public REPOButton Button;
		}

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

			public static BuilderDelegate <>9__8_0;

			public static Func<ConfigEntry<bool>[]> <>9__9_0;

			public static Action <>9__9_1;

			public static Func<ConfigEntry<bool>[]> <>9__9_3;

			public static Action<List<RectTransform>> <>9__9_5;

			public static Action<List<RectTransform>> <>9__9_6;

			public static Action<List<RectTransform>> <>9__9_7;

			public static Action <>9__9_4;

			public static Func<ConfigEntry<bool>[]> <>9__9_8;

			public static Action<List<RectTransform>> <>9__9_10;

			public static Action<List<RectTransform>> <>9__9_11;

			public static Action<List<RectTransform>> <>9__9_12;

			public static Action <>9__9_9;

			public static Func<ConfigEntry<bool>[]> <>9__9_13;

			public static Action<List<RectTransform>> <>9__9_15;

			public static Action<List<RectTransform>> <>9__9_16;

			public static Action<List<RectTransform>> <>9__9_17;

			public static Action<List<RectTransform>> <>9__9_18;

			public static Action <>9__9_14;

			public static Func<Events.Def, ConfigEntry<bool>> <>9__9_22;

			public static Func<ConfigEntry<bool>, bool> <>9__9_23;

			public static Func<ConfigEntry<bool>[]> <>9__9_20;

			public static Action <>9__9_24;

			public static Action <>9__9_25;

			public static Func<Events.Def, bool> <>9__9_26;

			public static Func<Events.Def, bool> <>9__9_27;

			public static Func<Events.Def, bool> <>9__9_28;

			public static Func<Events.Def, bool> <>9__9_29;

			public static Action<bool> <>9__9_31;

			public static Action <>9__9_21;

			public static ShouldCloseMenuDelegate <>9__12_0;

			public static Action <>9__12_7;

			public static BuilderDelegate <>9__12_1;

			public static Action<bool> <>9__12_2;

			public static Action<int> <>9__12_8;

			public static Action<List<RectTransform>> <>9__12_3;

			public static ScrollViewBuilderDelegate <>9__13_0;

			public static Func<ConfigEntry<bool>, bool> <>9__14_0;

			internal void <Register>b__8_0(Transform parent)
			{
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				if (SemiFunc.IsMasterClientOrSingleplayer())
				{
					((TMP_Text)MenuAPI.CreateREPOButton("Chaos Party", (Action)Open, parent, new Vector2(Plugin.LobbyButtonX.Value, Plugin.LobbyButtonY.Value)).labelTMP).fontSize = 28f;
				}
			}

			internal ConfigEntry<bool>[] <Categories>b__9_0()
			{
				return new ConfigEntry<bool>[0];
			}

			internal void <Categories>b__9_1()
			{
				Label("Sets every gameplay setting at once. Lobby size, Base Players and the event list stay as they are.", 16f);
				foreach (Preset item in Presets.All)
				{
					<>c__DisplayClass9_0 CS$<>8__locals1 = new <>c__DisplayClass9_0
					{
						preset = item
					};
					string text = (Presets.Matches(item) ? "  <color=#3dff6e><size=70%>ACTIVE</size></color>" : "");
					Button(item.Name + text, delegate
					{
						ApplyPreset(CS$<>8__locals1.preset);
					});
					Label("<color=#9a9a9a>" + item.Description + "</color>", 15f);
				}
			}

			internal ConfigEntry<bool>[] <Categories>b__9_3()
			{
				return new ConfigEntry<bool>[3]
				{
					Plugin.ScalingEnabled,
					Plugin.HealthEnabled,
					Plugin.HaulEnabled
				};
			}

			internal void <Categories>b__9_4()
			{
				Section("Party Scaling", Plugin.ScalingEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(IntSlider("Base Players", "Scaling starts above this many players.", Plugin.BasePlayers, 1, 20));
					kids.Add(PercentSlider("Map Size", "Extra map size per player above Base Players.", Plugin.MapPerPlayer));
					kids.Add(PercentSlider("Enemies", "Extra enemies per player above Base Players.", Plugin.EnemyPerPlayer));
					kids.Add(PercentSlider("Loot", "Extra loot per player above Base Players. The haul goal follows it.", Plugin.LootPerPlayer));
				});
				Section("Enemy Health", Plugin.HealthEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(FloatSlider("Multiplier", "Base enemy health multiplier.", Plugin.HealthBase, 0.2f, 5f));
					kids.Add(PercentSlider("Per Extra Player", "Extra enemy health per player above Base Players.", Plugin.HealthPerPlayer));
				});
				Section("Haul Goal", Plugin.HaulEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(FloatSlider("Multiplier", "Haul goal multiplier. Stacks with Party Scaling loot.", Plugin.HaulMultiplier, 0.2f, 5f));
				});
			}

			internal void <Categories>b__9_5(List<RectTransform> kids)
			{
				kids.Add(IntSlider("Base Players", "Scaling starts above this many players.", Plugin.BasePlayers, 1, 20));
				kids.Add(PercentSlider("Map Size", "Extra map size per player above Base Players.", Plugin.MapPerPlayer));
				kids.Add(PercentSlider("Enemies", "Extra enemies per player above Base Players.", Plugin.EnemyPerPlayer));
				kids.Add(PercentSlider("Loot", "Extra loot per player above Base Players. The haul goal follows it.", Plugin.LootPerPlayer));
			}

			internal void <Categories>b__9_6(List<RectTransform> kids)
			{
				kids.Add(FloatSlider("Multiplier", "Base enemy health multiplier.", Plugin.HealthBase, 0.2f, 5f));
				kids.Add(PercentSlider("Per Extra Player", "Extra enemy health per player above Base Players.", Plugin.HealthPerPlayer));
			}

			internal void <Categories>b__9_7(List<RectTransform> kids)
			{
				kids.Add(FloatSlider("Multiplier", "Haul goal multiplier. Stacks with Party Scaling loot.", Plugin.HaulMultiplier, 0.2f, 5f));
			}

			internal ConfigEntry<bool>[] <Categories>b__9_8()
			{
				return new ConfigEntry<bool>[3]
				{
					Plugin.SharedUpgrades,
					Plugin.FullReroll,
					Plugin.ShopEnabled
				};
			}

			internal void <Categories>b__9_9()
			{
				Section("Shared Upgrades", Plugin.SharedUpgrades, null, delegate(List<RectTransform> kids)
				{
					kids.Add(PercentSlider("Price Per Extra Player", "Each player above one adds this much of the base price.", Plugin.SharedUpgradeCostPerPlayer, 200));
					kids.Add(PercentSlider("Price Per Level", "Each purchase of an upgrade raises its next price by this much of the base.", Plugin.SharedUpgradeCostPerLevel));
				});
				Section("Full Shop Reroll", Plugin.FullReroll, null, delegate(List<RectTransform> kids)
				{
					kids.Add(Toggle("Unlimited Rerolls", Plugin.UnlimitedRerolls, null, bold: false));
				});
				Section("Bigger Shop", Plugin.ShopEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(FloatSlider("Shop Size", "How much more the shop stocks (items, crystals, upgrades, health packs).", Plugin.ShopSize, 1f, 5f));
				});
			}

			internal void <Categories>b__9_10(List<RectTransform> kids)
			{
				kids.Add(PercentSlider("Price Per Extra Player", "Each player above one adds this much of the base price.", Plugin.SharedUpgradeCostPerPlayer, 200));
				kids.Add(PercentSlider("Price Per Level", "Each purchase of an upgrade raises its next price by this much of the base.", Plugin.SharedUpgradeCostPerLevel));
			}

			internal void <Categories>b__9_11(List<RectTransform> kids)
			{
				kids.Add(Toggle("Unlimited Rerolls", Plugin.UnlimitedRerolls, null, bold: false));
			}

			internal void <Categories>b__9_12(List<RectTransform> kids)
			{
				kids.Add(FloatSlider("Shop Size", "How much more the shop stocks (items, crystals, upgrades, health packs).", Plugin.ShopSize, 1f, 5f));
			}

			internal ConfigEntry<bool>[] <Categories>b__9_13()
			{
				return new ConfigEntry<bool>[4]
				{
					Plugin.EventsEnabled,
					Plugin.BonusEnabled,
					Plugin.TotemEnabled,
					Plugin.RecapEnabled
				};
			}

			internal void <Categories>b__9_14()
			{
				Section("Random Events", Plugin.EventsEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(IntSlider("Chance", "Chance per level that a random event happens.", Plugin.EventChance, 0, 100, "", "%"));
					kids.Add(IntSlider("Boost Strength", "Upgrade levels given by temporary boost events.", Plugin.EventBoost, 1, 10, "+"));
					kids.Add(Toggle("Announce Out Loud", Plugin.EventSpeak, null, bold: false));
				});
				Section("Extraction Bonuses", Plugin.BonusEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(IntSlider("Per Extraction", "Random upgrades for everyone per completed extraction.", Plugin.BonusPerExtraction, 0, 5));
					kids.Add(IntSlider("Full Clear Bonus", "Extra random upgrades when every extraction is done.", Plugin.BonusFullClear, 0, 5));
					kids.Add(Toggle("Same For Everyone", Plugin.BonusSameForAll, null, bold: false));
				});
				Section("Totem of Undying", Plugin.TotemEnabled, null, delegate(List<RectTransform> kids)
				{
					kids.Add(TextInput("Totem Item", Plugin.TotemItem, "Rubber Duck"));
					kids.Add(IntSlider("Health", "Health you come back with.", Plugin.TotemHeal, 1, 200));
					kids.Add(IntSlider("Speed Boost", "Speed levels on pop. They fade one by one.", Plugin.TotemSpeed, 0, 10, "+"));
					kids.Add(FloatSlider("Speed Duration", "Seconds until the speed boost is gone.", Plugin.TotemSpeedDuration, 1f, 20f, "", "s"));
					kids.Add(FloatSlider("Shield", "Seconds after the pop where deaths are undone.", Plugin.TotemShield, 0f, 5f, "", "s"));
				});
				Section("Level Recap", Plugin.RecapEnabled, null, delegate(List<RectTransform> kids)
				{
					//IL_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_002d: Expected O, but got Unknown
					<>c__DisplayClass9_1 CS$<>8__locals3 = new <>c__DisplayClass9_1
					{
						info = null
					};
					target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
					{
						//IL_0008: Unknown result type (might be due to invalid IL or missing references)
						//IL_000e: Unknown result type (might be due to invalid IL or missing references)
						REPOLabel val = MenuAPI.CreateREPOLabel("<color=#9a9a9a>Awards after the last extraction: MVP, top hauler, kills, loot broken, deaths.</color>", p, default(Vector2));
						Wrap(val, 15f);
						CS$<>8__locals3.info = ((REPOElement)val).rectTransform;
						return CS$<>8__locals3.info;
					}, 0f, 0f);
					kids.Add(CS$<>8__locals3.info);
				});
			}

			internal void <Categories>b__9_15(List<RectTransform> kids)
			{
				kids.Add(IntSlider("Chance", "Chance per level that a random event happens.", Plugin.EventChance, 0, 100, "", "%"));
				kids.Add(IntSlider("Boost Strength", "Upgrade levels given by temporary boost events.", Plugin.EventBoost, 1, 10, "+"));
				kids.Add(Toggle("Announce Out Loud", Plugin.EventSpeak, null, bold: false));
			}

			internal void <Categories>b__9_16(List<RectTransform> kids)
			{
				kids.Add(IntSlider("Per Extraction", "Random upgrades for everyone per completed extraction.", Plugin.BonusPerExtraction, 0, 5));
				kids.Add(IntSlider("Full Clear Bonus", "Extra random upgrades when every extraction is done.", Plugin.BonusFullClear, 0, 5));
				kids.Add(Toggle("Same For Everyone", Plugin.BonusSameForAll, null, bold: false));
			}

			internal void <Categories>b__9_17(List<RectTransform> kids)
			{
				kids.Add(TextInput("Totem Item", Plugin.TotemItem, "Rubber Duck"));
				kids.Add(IntSlider("Health", "Health you come back with.", Plugin.TotemHeal, 1, 200));
				kids.Add(IntSlider("Speed Boost", "Speed levels on pop. They fade one by one.", Plugin.TotemSpeed, 0, 10, "+"));
				kids.Add(FloatSlider("Speed Duration", "Seconds until the speed boost is gone.", Plugin.TotemSpeedDuration, 1f, 20f, "", "s"));
				kids.Add(FloatSlider("Shield", "Seconds after the pop where deaths are undone.", Plugin.TotemShield, 0f, 5f, "", "s"));
			}

			internal void <Categories>b__9_18(List<RectTransform> kids)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Expected O, but got Unknown
				<>c__DisplayClass9_1 CS$<>8__locals3 = new <>c__DisplayClass9_1
				{
					info = null
				};
				target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					REPOLabel val = MenuAPI.CreateREPOLabel("<color=#9a9a9a>Awards after the last extraction: MVP, top hauler, kills, loot broken, deaths.</color>", p, default(Vector2));
					Wrap(val, 15f);
					CS$<>8__locals3.info = ((REPOElement)val).rectTransform;
					return CS$<>8__locals3.info;
				}, 0f, 0f);
				kids.Add(CS$<>8__locals3.info);
			}

			internal ConfigEntry<bool>[] <Categories>b__9_20()
			{
				return (from d in Events.All
					select d.Enabled into e
					where e != null
					select e).ToArray();
			}

			internal ConfigEntry<bool> <Categories>b__9_22(Events.Def d)
			{
				return d.Enabled;
			}

			internal bool <Categories>b__9_23(ConfigEntry<bool> e)
			{
				return e != null;
			}

			internal void <Categories>b__9_21()
			{
				if (!Plugin.EventsEnabled.Value)
				{
					Label("<color=#ff7a6b>Random Events is OFF (Chaos page).</color>", 18f);
				}
				Button("All On", delegate
				{
					SetAllEvents(on: true);
				});
				Button("All Off", delegate
				{
					SetAllEvents(on: false);
				});
				(string, Func<Events.Def, bool>)[] array = new(string, Func<Events.Def, bool>)[4]
				{
					("Level Changes", (Events.Def d) => d.Kind == Events.Kind.None && d.Temp == null && d.Gifts == 0),
					("Boosts", (Events.Def d) => d.Kind == Events.Kind.None && d.Temp != null),
					("Gifts", (Events.Def d) => d.Kind == Events.Kind.None && d.Temp == null && d.Gifts > 0),
					("Special", (Events.Def d) => d.Kind != Events.Kind.None)
				};
				for (int num = 0; num < array.Length; num++)
				{
					<>c__DisplayClass9_2 CS$<>8__locals2 = new <>c__DisplayClass9_2
					{
						g = array[num]
					};
					List<Events.Def> list = Events.All.Where((Events.Def d) => d.Enabled != null && CS$<>8__locals2.g.In(d)).ToList();
					if (list.Count == 0)
					{
						continue;
					}
					Label(CS$<>8__locals2.g.Name, 22f, 12f);
					foreach (Events.Def item in list)
					{
						Toggle(item.Name, item.Enabled, delegate
						{
							RefreshLabels();
						}, bold: false);
					}
				}
			}

			internal void <Categories>b__9_24()
			{
				SetAllEvents(on: true);
			}

			internal void <Categories>b__9_25()
			{
				SetAllEvents(on: false);
			}

			internal bool <Categories>b__9_26(Events.Def d)
			{
				if (d.Kind == Events.Kind.None && d.Temp == null)
				{
					return d.Gifts == 0;
				}
				return false;
			}

			internal bool <Categories>b__9_27(Events.Def d)
			{
				if (d.Kind == Events.Kind.None)
				{
					return d.Temp != null;
				}
				return false;
			}

			internal bool <Categories>b__9_28(Events.Def d)
			{
				if (d.Kind == Events.Kind.None && d.Temp == null)
				{
					return d.Gifts > 0;
				}
				return false;
			}

			internal bool <Categories>b__9_29(Events.Def d)
			{
				return d.Kind != Events.Kind.None;
			}

			internal void <Categories>b__9_31(bool _)
			{
				RefreshLabels();
			}

			internal bool <Open>b__12_0()
			{
				MenuAPI.CloseAllPagesAddedOnTop();
				return true;
			}

			internal void <Open>b__12_1(Transform p)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				MenuAPI.CreateREPOButton("Back", (Action)delegate
				{
					left.ClosePage(true);
				}, p, new Vector2(66f, 18f));
			}

			internal void <Open>b__12_7()
			{
				left.ClosePage(true);
			}

			internal void <Open>b__12_2(bool on)
			{
				Players.SyncLiveRoom("Menu");
			}

			internal void <Open>b__12_3(List<RectTransform> kids)
			{
				kids.Add(IntSlider("Max Players", $"Up to {Players.SliderMax} (server limit). Applies right away.", Plugin.MaxPlayers, 2, Players.SliderMax, "", "", delegate
				{
					Players.SyncLiveRoom("Menu");
				}));
			}

			internal void <Open>b__12_8(int _)
			{
				Players.SyncLiveRoom("Menu");
			}

			internal RectTransform <Select>b__13_0(Transform p)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				return ((REPOElement)MenuAPI.CreateREPOSpacer(p, default(Vector2), new Vector2(0f, 10f))).rectTransform;
			}

			internal bool <RefreshLabels>b__14_0(ConfigEntry<bool> f)
			{
				return f.Value;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass9_0
		{
			public Preset preset;

			internal void <Categories>b__2()
			{
				ApplyPreset(preset);
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass9_1
		{
			public RectTransform info;

			internal RectTransform <Categories>b__19(Transform p)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				REPOLabel val = MenuAPI.CreateREPOLabel("<color=#9a9a9a>Awards after the last extraction: MVP, top hauler, kills, loot broken, deaths.</color>", p, default(Vector2));
				Wrap(val, 15f);
				info = ((REPOElement)val).rectTransform;
				return info;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass9_2
		{
			public (string Name, Func<Events.Def, bool> In) g;

			internal bool <Categories>b__30(Events.Def d)
			{
				if (d.Enabled != null)
				{
					return g.In(d);
				}
				return false;
			}
		}

		private static REPOPopupPage left;

		private static REPOPopupPage right;

		private static REPOPopupPage target;

		private static List<Category> categories;

		private static int selected;

		private static readonly Color Selected = new Color(1f, 0.61f, 0f);

		private static readonly Color Normal = Color.white;

		internal static void Register()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			object obj = <>c.<>9__8_0;
			if (obj == null)
			{
				BuilderDelegate val = delegate(Transform parent)
				{
					//IL_003d: Unknown result type (might be due to invalid IL or missing references)
					if (SemiFunc.IsMasterClientOrSingleplayer())
					{
						((TMP_Text)MenuAPI.CreateREPOButton("Chaos Party", (Action)Open, parent, new Vector2(Plugin.LobbyButtonX.Value, Plugin.LobbyButtonY.Value)).labelTMP).fontSize = 28f;
					}
				};
				<>c.<>9__8_0 = val;
				obj = (object)val;
			}
			MenuAPI.AddElementToLobbyMenu((BuilderDelegate)obj);
		}

		private static List<Category> Categories()
		{
			return new List<Category>
			{
				new Category
				{
					Name = "Presets",
					Features = () => new ConfigEntry<bool>[0],
					Build = delegate
					{
						Label("Sets every gameplay setting at once. Lobby size, Base Players and the event list stay as they are.", 16f);
						foreach (Preset item in Presets.All)
						{
							Preset preset = item;
							string text = (Presets.Matches(item) ? "  <color=#3dff6e><size=70%>ACTIVE</size></color>" : "");
							Button(item.Name + text, delegate
							{
								ApplyPreset(preset);
							});
							Label("<color=#9a9a9a>" + item.Description + "</color>", 15f);
						}
					}
				},
				new Category
				{
					Name = "Difficulty",
					Features = () => new ConfigEntry<bool>[3]
					{
						Plugin.ScalingEnabled,
						Plugin.HealthEnabled,
						Plugin.HaulEnabled
					},
					Build = delegate
					{
						Section("Party Scaling", Plugin.ScalingEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(IntSlider("Base Players", "Scaling starts above this many players.", Plugin.BasePlayers, 1, 20));
							kids.Add(PercentSlider("Map Size", "Extra map size per player above Base Players.", Plugin.MapPerPlayer));
							kids.Add(PercentSlider("Enemies", "Extra enemies per player above Base Players.", Plugin.EnemyPerPlayer));
							kids.Add(PercentSlider("Loot", "Extra loot per player above Base Players. The haul goal follows it.", Plugin.LootPerPlayer));
						});
						Section("Enemy Health", Plugin.HealthEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(FloatSlider("Multiplier", "Base enemy health multiplier.", Plugin.HealthBase, 0.2f, 5f));
							kids.Add(PercentSlider("Per Extra Player", "Extra enemy health per player above Base Players.", Plugin.HealthPerPlayer));
						});
						Section("Haul Goal", Plugin.HaulEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(FloatSlider("Multiplier", "Haul goal multiplier. Stacks with Party Scaling loot.", Plugin.HaulMultiplier, 0.2f, 5f));
						});
					}
				},
				new Category
				{
					Name = "Upgrades",
					Features = () => new ConfigEntry<bool>[3]
					{
						Plugin.SharedUpgrades,
						Plugin.FullReroll,
						Plugin.ShopEnabled
					},
					Build = delegate
					{
						Section("Shared Upgrades", Plugin.SharedUpgrades, null, delegate(List<RectTransform> kids)
						{
							kids.Add(PercentSlider("Price Per Extra Player", "Each player above one adds this much of the base price.", Plugin.SharedUpgradeCostPerPlayer, 200));
							kids.Add(PercentSlider("Price Per Level", "Each purchase of an upgrade raises its next price by this much of the base.", Plugin.SharedUpgradeCostPerLevel));
						});
						Section("Full Shop Reroll", Plugin.FullReroll, null, delegate(List<RectTransform> kids)
						{
							kids.Add(Toggle("Unlimited Rerolls", Plugin.UnlimitedRerolls, null, bold: false));
						});
						Section("Bigger Shop", Plugin.ShopEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(FloatSlider("Shop Size", "How much more the shop stocks (items, crystals, upgrades, health packs).", Plugin.ShopSize, 1f, 5f));
						});
					}
				},
				new Category
				{
					Name = "Chaos",
					Features = () => new ConfigEntry<bool>[4]
					{
						Plugin.EventsEnabled,
						Plugin.BonusEnabled,
						Plugin.TotemEnabled,
						Plugin.RecapEnabled
					},
					Build = delegate
					{
						Section("Random Events", Plugin.EventsEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(IntSlider("Chance", "Chance per level that a random event happens.", Plugin.EventChance, 0, 100, "", "%"));
							kids.Add(IntSlider("Boost Strength", "Upgrade levels given by temporary boost events.", Plugin.EventBoost, 1, 10, "+"));
							kids.Add(Toggle("Announce Out Loud", Plugin.EventSpeak, null, bold: false));
						});
						Section("Extraction Bonuses", Plugin.BonusEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(IntSlider("Per Extraction", "Random upgrades for everyone per completed extraction.", Plugin.BonusPerExtraction, 0, 5));
							kids.Add(IntSlider("Full Clear Bonus", "Extra random upgrades when every extraction is done.", Plugin.BonusFullClear, 0, 5));
							kids.Add(Toggle("Same For Everyone", Plugin.BonusSameForAll, null, bold: false));
						});
						Section("Totem of Undying", Plugin.TotemEnabled, null, delegate(List<RectTransform> kids)
						{
							kids.Add(TextInput("Totem Item", Plugin.TotemItem, "Rubber Duck"));
							kids.Add(IntSlider("Health", "Health you come back with.", Plugin.TotemHeal, 1, 200));
							kids.Add(IntSlider("Speed Boost", "Speed levels on pop. They fade one by one.", Plugin.TotemSpeed, 0, 10, "+"));
							kids.Add(FloatSlider("Speed Duration", "Seconds until the speed boost is gone.", Plugin.TotemSpeedDuration, 1f, 20f, "", "s"));
							kids.Add(FloatSlider("Shield", "Seconds after the pop where deaths are undone.", Plugin.TotemShield, 0f, 5f, "", "s"));
						});
						Section("Level Recap", Plugin.RecapEnabled, null, delegate(List<RectTransform> kids)
						{
							//IL_0019: Unknown result type (might be due to invalid IL or missing references)
							//IL_002d: Expected O, but got Unknown
							RectTransform info = null;
							target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
							{
								//IL_0008: Unknown result type (might be due to invalid IL or missing references)
								//IL_000e: Unknown result type (might be due to invalid IL or missing references)
								REPOLabel val = MenuAPI.CreateREPOLabel("<color=#9a9a9a>Awards after the last extraction: MVP, top hauler, kills, loot broken, deaths.</color>", p, default(Vector2));
								Wrap(val, 15f);
								info = ((REPOElement)val).rectTransform;
								return info;
							}, 0f, 0f);
							kids.Add(info);
						});
					}
				},
				new Category
				{
					Name = "Events",
					Features = () => (from d in Events.All
						select d.Enabled into e
						where e != null
						select e).ToArray(),
					Build = delegate
					{
						if (!Plugin.EventsEnabled.Value)
						{
							Label("<color=#ff7a6b>Random Events is OFF (Chaos page).</color>", 18f);
						}
						Button("All On", delegate
						{
							SetAllEvents(on: true);
						});
						Button("All Off", delegate
						{
							SetAllEvents(on: false);
						});
						(string, Func<Events.Def, bool>)[] array = new(string, Func<Events.Def, bool>)[4]
						{
							("Level Changes", (Events.Def d) => d.Kind == Events.Kind.None && d.Temp == null && d.Gifts == 0),
							("Boosts", (Events.Def d) => d.Kind == Events.Kind.None && d.Temp != null),
							("Gifts", (Events.Def d) => d.Kind == Events.Kind.None && d.Temp == null && d.Gifts > 0),
							("Special", (Events.Def d) => d.Kind != Events.Kind.None)
						};
						for (int num = 0; num < array.Length; num++)
						{
							(string Name, Func<Events.Def, bool> In) g = array[num];
							List<Events.Def> list = Events.All.Where((Events.Def d) => d.Enabled != null && g.In(d)).ToList();
							if (list.Count != 0)
							{
								Label(g.Name, 22f, 12f);
								foreach (Events.Def item2 in list)
								{
									Toggle(item2.Name, item2.Enabled, delegate
									{
										RefreshLabels();
									}, bold: false);
								}
							}
						}
					}
				}
			};
		}

		private static void ApplyPreset(Preset p)
		{
			Presets.Apply(p);
			Select(selected);
		}

		private static void SetAllEvents(bool on)
		{
			foreach (Events.Def item in Events.All)
			{
				if (item.Enabled != null)
				{
					item.Enabled.Value = on;
				}
			}
			Select(selected);
		}

		private static void Open()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			MenuAPI.CloseAllPagesAddedOnTop();
			categories = Categories();
			selected = Mathf.Clamp(selected, 0, categories.Count - 1);
			left = MenuAPI.CreateREPOPopupPage("Chaos Party <size=45%><color=#9a9a9a>v1.2.0</color></size>", (PresetSide)0, false, true, 4f);
			REPOPopupPage obj = left;
			object obj2 = <>c.<>9__12_0;
			if (obj2 == null)
			{
				ShouldCloseMenuDelegate val = delegate
				{
					MenuAPI.CloseAllPagesAddedOnTop();
					return true;
				};
				<>c.<>9__12_0 = val;
				obj2 = (object)val;
			}
			obj.onEscapePressed = (ShouldCloseMenuDelegate)obj2;
			REPOPopupPage obj3 = left;
			object obj4 = <>c.<>9__12_1;
			if (obj4 == null)
			{
				BuilderDelegate val2 = delegate(Transform p)
				{
					//IL_002f: Unknown result type (might be due to invalid IL or missing references)
					MenuAPI.CreateREPOButton("Back", (Action)delegate
					{
						left.ClosePage(true);
					}, p, new Vector2(66f, 18f));
				};
				<>c.<>9__12_1 = val2;
				obj4 = (object)val2;
			}
			obj3.AddElement((BuilderDelegate)obj4);
			target = left;
			Section("Unlimited Players", Plugin.PlayersEnabled, delegate
			{
				Players.SyncLiveRoom("Menu");
			}, delegate(List<RectTransform> kids)
			{
				kids.Add(IntSlider("Max Players", $"Up to {Players.SliderMax} (server limit). Applies right away.", Plugin.MaxPlayers, 2, Players.SliderMax, "", "", delegate
				{
					Players.SyncLiveRoom("Menu");
				}));
			});
			List<RectTransform> kitMax = new List<RectTransform>();
			Action showKitMax = delegate
			{
				SetVisible(kitMax, Plugin.LateJoinEnabled.Value && Plugin.StarterKitEnabled.Value);
			};
			Section("Late Join", Plugin.LateJoinEnabled, delegate
			{
				showKitMax();
			}, delegate(List<RectTransform> kids)
			{
				kids.Add(Toggle("Starter Kit", Plugin.StarterKitEnabled, delegate
				{
					showKitMax();
				}, bold: false));
				kitMax.Add(IntSlider("Max Upgrades", "One upgrade per 3 levels, up to this many.", Plugin.StarterKitMax, 0, 10, "+"));
			});
			showKitMax();
			for (int num = 0; num < categories.Count; num++)
			{
				int index = num;
				Category c = categories[num];
				left.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
				{
					//IL_0033: Unknown result type (might be due to invalid IL or missing references)
					//IL_0039: Unknown result type (might be due to invalid IL or missing references)
					c.Button = MenuAPI.CreateREPOButton(c.Name, (Action)delegate
					{
						Select(index);
					}, p, default(Vector2));
					return ((REPOElement)c.Button).rectTransform;
				}, (num == 0) ? 20f : 0f, 0f);
			}
			left.OpenPage(false);
			Select(selected);
		}

		private static void Select(int index)
		{
			//IL_0074: 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_007f: Expected O, but got Unknown
			selected = index;
			Category category = categories[index];
			MenuAPI.CloseAllPagesAddedOnTop();
			right = MenuAPI.CreateREPOPopupPage(category.Name, (PresetSide)1, false, false, 2f);
			right.scrollView.scrollSpeed = 3f;
			target = right;
			category.Build();
			REPOPopupPage obj = right;
			object obj2 = <>c.<>9__13_0;
			if (obj2 == null)
			{
				ScrollViewBuilderDelegate val = (Transform p) => ((REPOElement)MenuAPI.CreateREPOSpacer(p, default(Vector2), new Vector2(0f, 10f))).rectTransform;
				<>c.<>9__13_0 = val;
				obj2 = (object)val;
			}
			obj.AddElementToScrollView((ScrollViewBuilderDelegate)obj2, 0f, 0f);
			right.OpenPage(true);
			RefreshLabels();
		}

		private static void RefreshLabels()
		{
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			if (categories == null)
			{
				return;
			}
			for (int i = 0; i < categories.Count; i++)
			{
				Category category = categories[i];
				if (!((Object)(object)category.Button == (Object)null) && !((Object)(object)category.Button.labelTMP == (Object)null))
				{
					ConfigEntry<bool>[] array = category.Features();
					int num = array.Count((ConfigEntry<bool> f) => f.Value);
					string text = ((array.Length != 0) ? ((array.Length > 1) ? $"{num}/{array.Length}" : ((num > 0) ? "ON" : "OFF")) : (Presets.Active()?.Name ?? "Custom"));
					((TMP_Text)category.Button.labelTMP).text = category.Name + "  <size=70%>" + text + "</size>";
					((Graphic)category.Button.labelTMP).color = ((i == selected) ? Selected : Normal);
				}
			}
		}

		private static void Section(string name, ConfigEntry<bool> enabled, Action<bool> onChanged, Action<List<RectTransform>> buildChildren)
		{
			List<RectTransform> children = new List<RectTransform>();
			Toggle(name, enabled, delegate(bool on)
			{
				SetVisible(children, on);
				onChanged?.Invoke(on);
				RefreshLabels();
			}, bold: true, 8f);
			buildChildren?.Invoke(children);
			SetVisible(children, enabled.Value);
		}

		private static void SetVisible(List<RectTransform> elements, bool visible)
		{
			foreach (RectTransform element in elements)
			{
				if (!((Object)(object)element == (Object)null))
				{
					REPOScrollViewElement component = ((Component)element).GetComponent<REPOScrollViewElement>();
					if ((Object)(object)component != (Object)null)
					{
						component.visibility = visible;
					}
				}
			}
		}

		private static RectTransform Toggle(string label, ConfigEntry<bool> entry, Action<bool> onChanged, bool bold, float topPadding = 0f)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			RectTransform result = null;
			target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: 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)
				REPOToggle val = MenuAPI.CreateREPOToggle(label, (Action<bool>)delegate(bool on)
				{
					entry.Value = on;
					onChanged?.Invoke(on);
				}, p, default(Vector2), "ON", "OFF", entry.Value);
				if (!bold)
				{
					TextMeshProUGUI labelTMP = val.labelTMP;
					((TMP_Text)labelTMP).fontStyle = (FontStyles)(((TMP_Text)labelTMP).fontStyle & -2);
				}
				result = ((REPOElement)val).rectTransform;
				return result;
			}, topPadding, 0f);
			return result;
		}

		private static void Label(string text, float fontSize, float topPadding = 0f)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				REPOLabel obj = MenuAPI.CreateREPOLabel(text, p, default(Vector2));
				Wrap(obj, fontSize);
				return ((REPOElement)obj).rectTransform;
			}, topPadding, 0f);
		}

		private static void Wrap(REPOLabel l, float fontSize)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (((Object)(object)target != (Object)null) ? target.maskRectTransform : null);
			float num = (((Object)(object)val != (Object)null && val.sizeDelta.x > 100f) ? (val.sizeDelta.x - 20f) : 260f);
			((TMP_Text)l.labelTMP).fontSize = fontSize;
			((TMP_Text)l.labelTMP).textWrappingMode = (TextWrappingModes)1;
			float num2 = Mathf.Max(fontSize + 6f, ((TMP_Text)l.labelTMP).GetPreferredValues(((TMP_Text)l.labelTMP).text, num, 0f).y + 4f);
			Vector2 sizeDelta = default(Vector2);
			((Vector2)(ref sizeDelta))..ctor(num, num2);
			((REPOElement)l).rectTransform.sizeDelta = sizeDelta;
			((TMP_Text)l.labelTMP).rectTransform.sizeDelta = sizeDelta;
		}

		private static void Button(string text, Action onClick)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			target.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform p) => ((REPOElement)MenuAPI.CreateREPOButton(text, onClick, p, default(Vector2))).rectTransform), 0f, 0f);
		}

		private static RectTransform IntSlider(string label, string description, ConfigEntry<int> entry, int min, int max, string prefix = "", string postfix = "", Action<int> onChanged = null)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			RectTransform result = null;
			target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				REPOSlider val = MenuAPI.CreateREPOSlider(label, description, (Action<int>)delegate(int v)
				{
					entry.Value = v;
					onChanged?.Invoke(v);
				}, p, default(Vector2), min, max, Mathf.Clamp(entry.Value, min, max), prefix, postfix, (BarBehavior)0);
				result = ((REPOElement)val).rectTransform;
				return result;
			}, 0f, 0f);
			return result;
		}

		private static RectTransform FloatSlider(string label, string description, ConfigEntry<float> entry, float min, float max, string prefix = "x", string postfix = "")
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			RectTransform result = null;
			target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				REPOSlider val = MenuAPI.CreateREPOSlider(label, description, (Action<float>)delegate(float v)
				{
					entry.Value = v;
				}, p, default(Vector2), min, max, 1, Mathf.Clamp(entry.Value, min, max), prefix, postfix, (BarBehavior)0);
				result = ((REPOElement)val).rectTransform;
				return result;
			}, 0f, 0f);
			return result;
		}

		private static RectTransform TextInput(string label, ConfigEntry<string> entry, string placeholder)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			RectTransform result = null;
			target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				REPOInputField val = MenuAPI.CreateREPOInputField(label, (Action<string>)delegate(string v)
				{
					if (!string.IsNullOrWhiteSpace(v))
					{
						entry.Value = v.Trim();
					}
				}, p, default(Vector2), true, placeholder, entry.Value);
				result = ((REPOElement)val).rectTransform;
				return result;
			}, 0f, 0f);
			return result;
		}

		private static RectTransform PercentSlider(string label, string description, ConfigEntry<float> entry, int max = 50)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			RectTransform result = null;
			target.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform p)
			{
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				int num = Mathf.Clamp(Mathf.RoundToInt(entry.Value * 100f), 0, max);
				REPOSlider val = MenuAPI.CreateREPOSlider(label, description, (Action<int>)delegate(int v)
				{
					entry.Value = (float)v / 100f;
				}, p, default(Vector2), 0, max, num, "+", "%", (BarBehavior)0);
				result = ((REPOElement)val).rectTransform;
				return result;
			}, 0f, 0f);
			return result;
		}
	}
	internal static class Economy
	{
		internal static float ShopMult => Scaled(Plugin.ShopSize.Value, Plugin.ShopPerPlayer.Value);

		internal static float HaulMult => Scaled(Plugin.HaulMultiplier.Value, Plugin.HaulPerPlayer.Value);

		internal static float Scaled(float baseMult, float perPlayer)
		{
			int num = Mathf.Max(0, Plugin.PlayerCount - Plugin.BasePlayers.Value);
			return Mathf.Clamp(baseMult * (1f + perPlayer * (float)num), 0.1f, 10f);
		}
	}
	[HarmonyPatch(typeof(ShopManager), "UpgradeValueGet")]
	internal static class SharedUpgradeCostPatch
	{
		private static bool Prefix(float _value, Item item, ref float __result)
		{
			if (!Plugin.SharedUpgrades.Value || !Plugin.IsHost || !SemiFunc.IsMultiplayer())
			{
				return true;
			}
			if ((Object)(object)item == (Object)null || (Object)(object)StatsManager.instance == (Object)null)
			{
				return true;
			}
			int num = Mathf.Max(0, Plugin.PlayerCount - 1);
			int itemsUpgradesPurchased = StatsManager.instance.GetItemsUpgradesPurchased(((Object)item).name);
			float num2 = 1f + Mathf.Max(0f, Plugin.SharedUpgradeCostPerPlayer.Value) * (float)num;
			float num3 = 1f + Mathf.Max(0f, Plugin.SharedUpgradeCostPerLevel.Value) * (float)itemsUpgradesPurchased;
			__result = Mathf.Ceil(_value * num2 * num3);
			return false;
		}
	}
	[HarmonyPatch]
	internal static class BiggerShopPatch
	{
		private class Originals
		{
			public int Items;

			public int Upgrades;

			public int HealthPacks;
		}

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

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

		internal static bool Populating;

		internal static readonly HashSet<ItemVolume> Used = new HashSet<ItemVolume>();

		internal static readonly Dictionary<List<Item>, int> Spawned = new Dictionary<List<Item>, int>();

		private static List<ItemVolume> volumes;

		private static List<(List<Item> list, int target, string name)> targets;

		private static MethodBase TargetMethod()
		{
			Type type = AccessTools.Inner(typeof(PunManager), "ItemSpawn");
			return AccessTools.Method(typeof(PunManager), "ShopPopulateItemVolumes", new Type[1] { typeof(List<>).MakeGenericType(type) }, (Type[])null);
		}

		private static void Prefix()
		{
			Populating = false;
			if ((!Plugin.ShopEnabled.Value && !Special.AuditShop) || !Plugin.IsHost)
			{
				return;
			}
			ShopManager instance = ShopManager.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			try
			{
				int instanceID = ((Object)instance).GetInstanceID();
				if (!saved.TryGetValue(instanceID, out var value))
				{
					value = new Originals
					{
						Items = instance.itemSpawnTargetAmount,
						Upgrades = instance.itemUpgradesAmount,
						HealthPacks = instance.itemHealthPacksAmount
					};
					saved[instanceID] = value;
				}
				float num = (Plugin.ShopEnabled.Value ? Economy.ShopMult : 1f) * Special.ShopStock;
				instance.itemSpawnTargetAmount = Mathf.Max(0, Mathf.RoundToInt((float)value.Items * num));
				instance.itemUpgradesAmount = Mathf.Max(0, Mathf.RoundToInt((float)value.Upgrades * num));
				instance.itemHealthPacksAmount = Mathf.Max(0, Mathf.RoundToInt((float)value.HealthPacks * num));
				instance.itemConsumablesAmount = Mathf.Max(0, Mathf.RoundToInt((float)instance.itemConsumablesAmount * num));
				targets = new List<(List<Item>, int, string)>
				{
					(instance.potentialItemUpgrades, instance.itemUpgradesAmount, "upgrades"),
					(instance.potentialItemHealthPacks, instance.itemHealthPacksAmount, "health packs"),
					(instance.potentialItemConsumables, instance.itemConsumablesAmount, "crystals"),
					(instance.potentialItems, instance.itemSpawnTargetAmount, "items")
				};
				foreach (var target in targets)
				{
					Pad(target.list, target.target);
				}
				volumes = new List<ItemVolume>(instance.itemVolumes);
				Used.Clear();
				Spawned.Clear();
				Populating = true;
				Plugin.Log.LogInfo((object)($"[Shop] x{num:0.##}: {instance.itemSpawnTargetAmount} items, {instance.itemConsumablesAmount} crystals, " + $"{instance.itemUpgradesAmount} upgrades, {instance.itemHealthPacksAmount} health packs, {volumes.Count} slots."));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Bigger shop (prefix) failed: " + ex));
			}
		}

		private static void Pad(List<Item> list, int target)
		{
			if (list != null && list.Count != 0)
			{
				int count = list.Count;
				while (list.Count < target)
				{
					list.Add(list[Random.Range(0, count)]);
				}
				ListExtension.Shuffle<Item>((IList<Item>)list);
			}
		}

		private static void Postfix(PunManager __instance, object[] __args)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			if (!Populating)
			{
				return;
			}
			Populating = false;
			try
			{
				int num = 0;
				int num2 = 0;
				List<ItemVolume> list = volumes.Where((ItemVolume v) => (Object)(object)v != (Object)null && !Used.Contains(v)).ToList();
				foreach (var target in targets)
				{
					Spawned.TryGetValue(target.list, out var value);
					int num3 = target.target - value;
					while (num3 > 0 && target.list.Count > 0)
					{
						if (list.Count == 0)
						{
							num2 += num3;
							break;
						}
						ItemVolume val = list[list.Count - 1];
						list.RemoveAt(list.Count - 1);
						val.itemVolume = target.list[target.list.Count - 1].itemVolume;
						object[] parameters = new object[5]
						{
							val,
							target.list,
							0,
							false,
							__args[0]
						};
						if ((bool)SpawnShopItem.Invoke(__instance, parameters))
						{
							num++;
							num3--;
						}
					}
				}
				if (num > 0 || num2 > 0)
				{
					Plugin.Log.LogInfo((object)($"[Shop] Placed {num} extra item(s) in spare slots" + ((num2 > 0) ? $", {num2} didn't fit (shop is full)." : ".")));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Bigger shop (postfix) failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(PunManager), "SpawnShopItem")]
	internal static class BiggerShopSpawnTrackPatch
	{
		private static void Postfix(bool __result, ItemVolume itemVolume, List<Item> itemList, bool isSecret)
		{
			if (!(!BiggerShopPatch.Populating || !__result || isSecret))
			{
				BiggerShopPatch.Used.Add(itemVolume);
				BiggerShopPatch.Spawned.TryGetValue(itemList, out var value);
				BiggerShopPatch.Spawned[itemList] = value + 1;
			}
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "StartRoundRPC")]
	internal static class StartRoundRpcPatch
	{
		internal static bool InRpc;

		private static void Prefix()
		{
			InRpc = true;
		}

		private static void Finalizer()
		{
			InRpc = false;
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "StartRoundLogic")]
	internal static class HaulGoalPatch
	{
		private static void Prefix(ref int value)
		{
			if (!StartRoundRpcPatch.InRpc && Plugin.IsHost && SemiFunc.RunIsLevel())
			{
				float num = (Plugin.HaulEnabled.Value ? Economy.HaulMult : 1f) * Events.Haul;
				if (!Mathf.Approximately(num, 1f))
				{
					int num2 = value;
					value = Mathf.Max(1, Mathf.RoundToInt((float)value * num));
					Plugin.Log.LogInfo((object)$"[Haul] Goal {num2} -> {value} (x{num:0.##})");
				}
			}
		}
	}
	internal static class ExtractionBonus
	{
		private static int fullClearFor = int.MinValue;

		internal static void Grant(int count, string why)
		{
			if (count <= 0)
			{
				return;
			}
			List<PlayerAvatar> list = Upgrades.Players().ToList();
			if (list.Count == 0)
			{
				return;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			if (Plugin.BonusSameForAll.Value)
			{
				for (int i = 0; i < count; i++)
				{
					string key = Upgrades.PickRandom();
					dictionary.TryGetValue(key, out var value);
					dictionary[key] = value + 1;
				}
				foreach (PlayerAvatar item in list)
				{
					string steamID = SemiFunc.PlayerGetSteamID(item);
					foreach (KeyValuePair<string, int> item2 in dictionary)
					{
						Upgrades.Give(steamID, item2.Key, item2.Value);
					}
					Upgrades.Flash(item);
				}
				string text = string.Join(", ", dictionary.Select((KeyValuePair<string, int> kv) => $"+{kv.Value} {Upgrades.Pretty(kv.Key)}"));
				Announce.Truck("<color=#3dff6e><b>" + why + "</b></color>\nEveryone got " + text + ".");
				Plugin.Log.LogInfo((object)("[Bonus] " + why + ": everyone got " + text));
				return;
			}
			foreach (PlayerAvatar item3 in list)
			{
				string steamID2 = SemiFunc.PlayerGetSteamID(item3);
				for (int num = 0; num < count; num++)
				{
					Upgrades.Give(steamID2, Upgrades.PickRandom(), 1);
				}
				Upgrades.Flash(item3);
			}
			Announce.Truck($"<color=#3dff6e><b>{why}</b></color>\nEveryone got {count} random upgrade(s).");
			Plugin.Log.LogInfo((object)$"[Bonus] {why}: {count} random upgrade(s) each for {list.Count} player(s)");
		}

		internal static void FullClear(RoundDirector rd)
		{
			int instanceID = ((Object)rd).GetInstanceID();
			if (instanceID != fullClearFor)
			{
				fullClearFor = instanceID;
				Grant(Special.BonusCount(Plugin.BonusEnabled.Value ? Plugin.BonusFullClear.Value : 0), Events.Is(Events.Kind.DoubleOrNothing) ? "ALL EXTRACTIONS DONE! (DOUBLE)" : "ALL EXTRACTIONS DONE!");
			}
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "ExtractionCompleted")]
	internal static class ExtractionCompletedPatch
	{
		private static void Postfix()
		{
			if (!Plugin.IsHost || !SemiFunc.RunIsLevel())
			{
				return;
			}
			ExtractionBonus.Grant(Special.BonusCount(Plugin.BonusEnabled.Value ? Plugin.BonusPerExtraction.Value : 0), Events.Is(Events.Kind.DoubleOrNothing) ? "DOUBLE BONUS!" : "EXTRACTION BONUS!");
			try
			{
				Special.ExtractionDone();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Extraction hook failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "ExtractionCompletedAllRPC")]
	internal static class ExtractionCompletedAllPatch
	{
		private static void Postfix(RoundDirector __instance)
		{
			if (!Plugin.IsHost || !SemiFunc.RunIsLevel())
			{
				return;
			}
			ExtractionBonus.FullClear(__instance);
			try
			{
				Special.AllExtractionsDone();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("All extractions hook failed: " + ex));
			}
			try
			{
				Recap.AllExtractionsDone();
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogError((object)("Recap failed: " + ex2));
			}
		}
	}
	internal static class Events
	{
		internal enum Kind
		{
			None,
			Bounty,
			Speedrun,
			NoDeaths,
			DoubleOrNothing,
			Golden,
			LuckyDucks,
			Butterfingers,
			Payday,
			Audit,
			Mystery,
			Boss
		}

		internal class Def
		{
			public string Name;

			public string Text;

			public Kind Kind;

			public Def Hidden;

			public float Map = 1f;

			public float Enemies = 1f;

			public float Loot = 1f;

			public float EnemyHealth = 1f;

			public float Haul = 1f;

			public string[] Temp;

			public int Gifts;

			public ConfigEntry<bool> Enabled;

			public bool On
			{
				get
				{
					if (Enabled != null)
					{
						return Enabled.Value;
					}
					return true;
				}
			}
		}

		internal static readonly List<Def> All = new List<Def>
		{
			new Def
			{
				Name = "Gold Rush",
				Text = "This place is loaded.",
				Loot = 1.5f
			},
			new Def
			{
				Name = "Infestation",
				Text = "Something is breeding in here.",
				Enemies = 1.5f
			},
			new Def
			{
				Name = "Labyrinth",
				Text = "This place is bigger than it looks.",
				Map = 1.3f
			},
			new Def
			{
				Name = "Juggernauts",
				Text = "The monsters are tougher.",
				EnemyHealth = 2f
			},
			new Def
			{
				Name = "Glass Monsters",
				Text = "The monsters are fragile.",
				EnemyHealth = 0.5f
			},
			new Def
			{
				Name = "Taxman's Mercy",
				Text = "The taxman is feeling generous.",
				Haul = 0.75f
			},
			new Def
			{
				Name = "Taxman's Greed",
				Text = "The taxman wants more, but there is more.",
				Haul = 1.3f,
				Loot = 1.5f
			},
			new Def
			{
				Name = "Bloodbath",
				Text = "More monsters, more loot.",
				Enemies = 1.5f,
				Loot = 1.5f
			},
			new Def
			{
				Name = "Adrenaline",
				Text = "Everyone runs faster.",
				Temp = T("Speed")
			},
			new Def
			{
				Name = "Moon Jump",
				Text = "Everyone gets extra jumps.",
				Temp = T("ExtraJump")
			},
			new Def
			{
				Name = "Hulk Mode",
				Text = "Everyone is stronger.",
				Temp = T("Strength")
			},
			new Def
			{
				Name = "Iron Lungs",
				Text = "Everyone has more stamina.",
				Temp = T("Stamina")
			},
			new Def
			{
				Name = "Long Arms",
				Text = "Everyone can grab further.",
				Temp = T("Range")
			},
			new Def
			{
				Name = "Gift From Above",
				Text = "Everyone gets a free upgrade to keep.",
				Gifts = 1
			},
			new Def
			{
				Name = "Jackpot",
				Text = "Double the loot, but the taxman noticed.",
				Loot = 2f,
				Haul = 1.5f
			},
			new Def
			{
				Name = "Monster Mash",
				Text = "Twice the monsters, half the health.",
				Enemies = 2f,
				EnemyHealth = 0.5f
			},
			new Def
			{
				Name = "Boss Rush",
				Text = "Bigger, tougher monsters guard better loot.",
				Enemies = 1.3f,
				EnemyHealth = 1.5f,
				Loot = 1.5f
			},
			new Def
			{
				Name = "Tax Holiday",
				Text = "Half the quota, but the monsters are restless.",
				Haul = 0.5f,
				Enemies = 1.5f
			},
			new Def
			{
				Name = "Treasure Hunt",
				Text = "A huge place full of riches.",
				Map = 1.4f,
				Loot = 1.5f
			},
			new Def
			{
				Name = "Maze Runner",
				Text = "A huge place, and fresh legs to run it.",
				Map = 1.4f,
				Temp = T("Speed", "Stamina")
			},
			new Def
			{
				Name = "Superhuman",
				Text = "Faster, stronger, higher.",
				Temp = T("Speed", "Strength", "ExtraJump")
			},
			new Def
			{
				Name = "Yeet",
				Text = "Everything flies further.",
				Temp = T("Throw", "Strength")
			},
			new Def
			{
				Name = "Thick Skin",
				Text = "Everyone can take a beating.",
				Temp = T("Health")
			},
			new Def
			{
				Name = "Tumble Party",
				Text = "Everyone was born to tumble.",
				Temp = T("Launch", "TumbleWings", "TumbleClimb")
			},
			new Def
			{
				Name = "Christmas Morning",
				Text = "Two free upgrades for everyone, to keep.",
				Gifts = 2
			},
			new Def
			{
				Name = "Cursed Gift",
				Text = "A free upgrade, but the monsters are angry.",
				Gifts = 1,
				Enemies = 1.5f,
				EnemyHealth = 1.5f
			},
			new Def
			{
				Name = "Bounty Hunt",
				Text = "Every monster you kill pays out an upgrade.",
				Kind = Kind.Bounty
			},
			new Def
			{
				Name = "Speedrun",
				Text = "Beat the clock and everyone gets rewarded.",
				Kind = Kind.Speedrun
			},
			new Def
			{
				Name = "No One Left Behind",
				Text = "If nobody dies, everyone gets rewarded.",
				Kind = Kind.NoDeaths
			},
			new Def
			{
				Name = "Double or Nothing",
				Text = "The taxman wants more, but extraction bonuses pay double.",
				Kind = Kind.DoubleOrNothing,
				Haul = 1.5f
			},
			new Def
			{
				Name = "The Golden One",
				Text = "Something in here is worth a fortune.",
				Kind = Kind.Golden
			},
			new Def
			{
				Name = "Lucky Ducks",
				Text = "Rubber ducks are hidden around the level.",
				Kind = Kind.LuckyDucks
			},
			new Def
			{
				Name = "Butterfingers",
				Text = "Everything is worth more, but it breaks so easily.",
				Kind = Kind.Butterfingers
			},
			new Def
			{
				Name = "Payday",
				Text = "Bonus cash for the next shop.",
				Kind = Kind.Payday
			},
			new Def
			{
				Name = "Audit",
				Text = "The taxman takes a cut, but the next shop is a bargain.",
				Kind = Kind.Audit
			},
			new Def
			{
				Name = "Mystery Event",
				Text = "Nobody knows what this level holds.",
				Kind = Kind.Mystery
			},
			new Def
			{
				Name = "Boss Level",
				Text = "One monster is much tougher than the rest.",
				Kind = Kind.Boss
			}
		};

		internal static Def Current;

		private static Def last;

		private static int rolledFor = int.MinValue;

		internal static float Map => Current?.Map ?? 1f;

		internal static float Enemies => Current?.Enemies ?? 1f;

		internal static float Loot => Current?.Loot ?? 1f;

		internal static float EnemyHealth => Current?.EnemyHealth ?? 1f;

		internal static float Haul => Current?.Haul ?? 1f;

		private static string[] T(params string[] upgrades)
		{
			return upgrades;
		}

		internal static bool Is(Kind kind)
		{
			if (Current != null)
			{
				return Current.Kind == kind;
			}
			return false;
		}

		internal static void Roll()
		{
			if (!Plugin.IsHost || !SemiFunc.RunIsLevel())
			{
				Current = null;
				return;
			}
			LevelGenerator instance = LevelGenerator.Instance;
			int num = (((Object)(object)instance != (Object)null) ? ((Object)instance).GetInstanceID() : 0);
			if (num == rolledFor)
			{
				return;
			}
			rolledFor = num;
			Current = null;
			if (!Plugin.EventsEnabled.Value || Random.Range(0, 100) >= Plugin.EventChance.Value)
			{
				return;
			}
			List<Def> list = All.Where((Def d) => d.On && d != last && Special.Available(d)).ToList();
			if (list.Count == 0)
			{
				list = All.Where((Def d) => d.On && Special.Available(d)).ToList();
			}
			if (list.Count == 0)
			{
				Plugin.Log.LogInfo((object)"[Event] No switched-on event can happen here, skipping.");
				return;
			}
			Def def = (last = list[Random.Range(0, list.Count)]);
			Current = ((def.Kind == Kind.Mystery) ? Mystery(def) : def);
			Plugin.Log.LogInfo((object)("[Event] Rolled '" + Current.Name + "'" + ((Current.Hidden != null) ? (" (secretly '" + Current.Hidden.Name + "').") : ".")));
			Runner.Run(StartWhenReady(Current));
		}

		internal static List<Def> MysteryPool()
		{
			return All.Where((Def d) => d.On && d.Kind == Kind.None && d.Temp == null && d.Gifts == 0).ToList();
		}

		private static Def Mystery(Def template)
		{
			List<Def> list = MysteryPool();
			Def def = list[Random.Range(0, list.Count)];
			return new Def
			{
				Name = template.Name,
				Text = template.Text,
				Kind = Kind.Mystery,
				Hidden = def,
				Map = def.Map,
				Enemies = def.Enemies,
				Loot = def.Loot,
				EnemyHealth = def.EnemyHealth,
				Haul = def.Haul
			};
		}

		private static string Times(float v)
		{
			return "x" + v.ToString("0.##", CultureInfo.InvariantCulture);
		}

		private static string Percent(float v)
		{
			int num = Mathf.RoundToInt((v - 1f) * 100f);
			return ((num > 0) ? "+" : "") + num + "%";
		}

		internal static List<string> EffectLines(Def ev)
		{
			List<string> list = new List<string>();
			if (!Mathf.Approximately(ev.Loot, 1f))
			{
				list.Add("Loot " + Times(ev.Loot));
			}
			if (!Mathf.Approximately(ev.Enemies, 1f))
			{
				list.Add("Monsters " + Times(ev.Enemies));
			}
			if (!Mathf.Approximately(ev.Map, 1f))
			{
				list.Add("Map size " + Times(ev.Map));
			}
			if (!Mathf.Approximately(ev.EnemyHealth, 1f))
			{
				list.Add("Monster health " + Times(ev.EnemyHealth));
			}
			if (!Mathf.Approximately(ev.Haul, 1f))
			{
				list.Add("Haul goal " + Percent(ev.Haul));
			}
			return list;
		}

		private static IEnumerator StartWhenReady(Def ev)
		{
			float timeout = 120f;
			while (timeout > 0f && ((Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated || (Object)(object)GameDirector.instance == (Object)null || (int)GameDirector.instance.currentState != 2))
			{
				timeout -= Time.deltaTime;
				yield return null;
			}
			if (timeout <= 0f || Current != ev)
			{
				yield break;
			}
			yield return (object)new WaitForSeconds(1f);
			timeout = 30f;
			while (timeout > 0f && !Banner.MoonIdle)
			{
				timeout -= Time.deltaTime;
				yield return null;
			}
			if (Current != ev)
			{
				yield break;
			}
			yield return (object)new WaitForSeconds(0.5f);
			List<string> list = ((ev.Kind == Kind.Mystery) ? new List<string> { "Effects: ???" } : EffectLines(ev));
			if (ev.Temp != null)
			{
				int num = Mathf.Max(1, Plugin.EventBoost.Value);
				string[] temp = ev.Temp;
				foreach (string text in temp)
				{
					foreach (PlayerAvatar item in Upgrades.Players())
					{
						TempUpgrades.Add(SemiFunc.PlayerGetSteamID(item), text, num);
					}
					list.Add($"+{num} {Upgrades.Pretty(text)} this level");
				}
			}
			if (ev.Gifts > 0)
			{
				Dictionary<string, int> dictionary = new Dictionary<string, int>();
				for (int j = 0; j < ev.Gifts; j++)
				{
					string key = Upgrades.PickRandom();
					dictionary.TryGetValue(key, out var value);
					dictionary[key] = value + 1;
				}
				foreach (KeyValuePair<string, int> item2 in dictionary)
				{
					foreach (PlayerAvatar item3 in Upgrades.Players())
					{
						Upgrades.Give(SemiFunc.PlayerGetSteamID(item3), item2.Key, item2.Value);
					}
					list.Add($"+{item2.Value} {Upgrades.Pretty(item2.Key)} (yours to keep)");
				}
			}
			list.AddRange(Special.Start(ev));
			Cues.Stinger();
			foreach (PlayerAvatar item4 in Upgrades.Players())
			{
				Upgrades.Flash(item4);
			}
			Cues.Speak("Event! " + ev.Name + ". " + ev.Text);
			string text2 = ((list.Count > 0) ? ("\n" + string.Join("\n", list)) : "");
			Announce.Truck("<sprite name=!> <size=130%><color=#ff9c00><b>EVENT: " + ev.Name.ToUpperInvariant() + "</b></color></size> <sprite name=!>\n" + ev.Text + text2);
			List<string> list2 = new List<string> { ev.Text };
			list2.AddRange(list);
			Banner.Send(ev.Name, list2.ToArray());
		}
	}
	internal static class EnemyHealthScaling
	{
		internal static float Multiplier
		{
			get
			{
				float num = 1f;
				if (Plugin.HealthEnabled.Value)
				{
					int num2 = Mathf.Max(0, Plugin.PlayerCount - Plugin.BasePlayers.Value);
					num = Plugin.HealthBase.Value * (1f + Plugin.HealthPerPlayer.Value * (float)num2);
					num = Mathf.Clamp(num, 0.1f, Mathf.Max(0.1f, Plugin.HealthMax.Value));
				}
				return num * Events.EnemyHealth;
			}
		}
	}
	[HarmonyPatch(typeof(EnemyHealth), "OnSpawn")]
	internal static class EnemyHealthSpawnPatch
	{
		private static void Postfix(EnemyHealth __instance)
		{
			if (Plugin.IsHost && SemiFunc.RunIsLevel())
			{
				float num = EnemyHealthScaling.Multiplier * Special.SpawnHealth(__instance);
				if (!Mathf.Approximately(num, 1f))
				{
					Traverse obj = Traverse.Create((object)__instance).Field("healthCurrent");
					int num2 = Mathf.Max(1, Mathf.RoundToInt((float)__instance.health * num));
					obj.SetValue((object)num2);
					Plugin.Log.LogInfo((object)$"[EnemyHealth] {((Object)__instance).name}: {__instance.health} -> {num2} (x{num:0.##})");
				}
			}
		}
	}
	internal static class LateJoin
	{
		private static readonly FieldRef<RunManager, bool> restarting = AccessTools.FieldRefAccess<RunManager, bool>("restarting");

		private static readonly FieldRef<GameManager, bool> connectRandom = AccessTools.FieldRefAccess<GameManager, bool>("connectRandom");

		private static readonly FieldRef<RunManager, RunManagerPUN> runManagerPUN = AccessTools.FieldRefAccess<RunManager, RunManagerPUN>("runManagerPUN");

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

		private static readonly Func<bool> persistentObjectsSupported = AccessTools.MethodDelegate<Func<bool>>(AccessTools.Method(typeof(PhotonNetwork), "PersistentObjectsSupported", (Type[])null, (Type[])null), (object)null, true);

		private static readonly object keyByteNine = AccessTools.Field(typeof(PhotonNetwork), "keyByteNine").GetValue(null);

		private static bool openedByUs;

		private static bool cacheClean;

		private static bool vanillaCleaned;

		private static float nextTick;

		private static readonly HashSet<int> joinedThisLevel = new HashSet<int>();

		private static readonly HashSet<int> welcomed = new HashSet<int>();

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

		private static readonly string[] normalSides = new string[4] { "ConnectingTop", "ConnectingBottom", "ConnectingRight", "ConnectingLeft" };

		private static readonly string[] megaSides = new string[8] { "ConnectingTopRight", "ConnectingTopLeft", "ConnectingRightTop", "ConnectingRightBot", "ConnectingBottomRight", "ConnectingBottomLeft", "ConnectingLeftTop", "ConnectingLeftBot" };

		private static readonly List<KeyValuePair<int, int>> brokenProps = new List<KeyValuePair<int, int>>();

		private static LevelGenerator brokenLevel;

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

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

		private static readonly FieldRef<RoundDirector, int> rdHaulGoal = AccessTools.FieldRefAccess<RoundDirector, int>("haulGoal");

		private static readonly FieldRef<RoundDirector, List<GameObject>> rdPoints = AccessTools.FieldRefAccess<RoundDirector, List<GameObject>>("extractionPointList");

		private static readonly FieldRef<RoundDirector, ExtractionPoint> rdCurrent = AccessTools.FieldRefAccess<RoundDirector, ExtractionPoint>("extractionPointCurrent");

		private static readonly FieldRef<RoundDirector, bool> rdAllDone = AccessTools.FieldRefAccess<RoundDirector, bool>("allExtractionPointsCompleted");

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

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

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

		private static readonly FieldRef<ValuableObject, float> voValue = AccessTools.FieldRefAccess<ValuableObject, float>("dollarValueCurrent");

		private static readonly FieldRef<ValuableObject, bool> voValueSet = AccessTools.FieldRefAccess<ValuableObject, bool>("dollarValueSet");

		private static readonly FieldRef<ValuableObject, bool> voDiscovered = AccessTools.FieldRefAccess<ValuableObject, bool>("discovered");

		private static readonly FieldRef<PhysGrabHinge, PhotonView> hingeView = AccessTools.FieldRefAccess<PhysGrabHinge, PhotonView>("photon");

		private static readonly FieldRef<PhysGrabHinge, bool> hingeBroken = AccessTools.FieldRefAccess<PhysGrabHinge, bool>("broken");

		private static readonly FieldRef<PhysGrabHinge, bool> hingeDead = AccessTools.FieldRefAccess<PhysGrabHinge, bool>("dead");

		private static readonly FieldRef<EnemyParent, bool> enemySpawned = AccessTools.FieldRefAccess<EnemyParent, bool>("Spawned");

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

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

		internal static bool Enabled => Plugin.LateJoinEnabled.Value;

		internal static int NotCountedYet
		{
			get
			{
				if (joinedThisLevel.Count == 0 || PhotonNetwork.CurrentRoom == null)
				{
					return 0;
				}
				return joinedThisLevel.Count((int a) => PhotonNetwork.CurrentRoom.Players.ContainsKey(a));
			}
		}

		private static bool InRun
		{
			get
			{
				RunManager instance = RunManager.instance;
				if ((Object)(object)instance == (Object)null || (Object)(object)instance.levelCurrent == (Object)null)
				{
					return false;
				}
				if (!SemiFunc.RunIsLevel() && !SemiFunc.RunIsShop())
				{
					return SemiFunc.RunIsLobby();
				}
				return true;
			}
		}

		private static bool IsHostMP
		{
			get
			{
				if (SemiFunc.IsMultiplayer() && PhotonNetwork.IsMasterClient)
				{
					return PhotonNetwork.CurrentRoom != null;
				}
				return false;
			}
		}

		internal static void Tick()
		{
			if (Time.unscaledTime < nextTick)
			{
				return;
			}
			nextTick = Time.unscaledTime + 0.5f;
			if (!IsHostMP)
			{
				openedByUs = false;
				return;
			}
			bool flag = Enabled && cacheClean && InRun && (Object)(object)LevelGenerator.Instance != (Object)null && LevelGenerator.Instance.Generated && !restarting.Invoke(RunManager.instance);
			if (flag && !openedByUs)
			{
				Open();
			}
			else if (!flag && openedByUs)
			{
				Close("not joinable right now");
			}
		}

		private static void Open()
		{
			openedByUs = true;
			PhotonNetwork.SetRoomOpen(true);
			if ((Object)(object)GameManager.instance != (Object)null && connectRandom.Invoke(GameManager.instance))
			{
				PhotonNetwork.CurrentRoom.IsVisible = true;
			}
			else
			{
				SteamLobbyManager instance = SteamLobbyManager.instance;
				if (instance != null)
				{
					instance.UnlockLobby(false);
				}
			}
			ManualLogSource log = Plugin.Log;
			Level levelCurrent = RunManager.instance.levelCurrent;
			log.LogInfo((object)("[LateJoin] Room open (" + ((levelCurrent != null) ? ((Object)levelCurrent).name : null) + ")."));
		}

		private static void Close(string reason)
		{
			openedByUs = false;
			if (PhotonNetwork.CurrentRoom != null)
			{
				PhotonNetwork.SetRoomOpen(false);
				PhotonNetwork.CurrentRoom.IsVisible = false;
				SteamLobbyManager instance = SteamLobbyManager.instance;
				if (instance != null)
				{
					instance.LockLobby();
				}
				Plugin.Log.LogInfo((object)("[LateJoin] Room closed (" + reason + ")."));
			}
		}

		internal static void LevelChanging()
		{
			_ = Runner.Instance;
			cacheClean = false;
			vanillaCleaned = false;
			joinedThisLevel.Clear();
			welcomed.Clear();
			if (openedByUs && IsHostMP)
			{
				Close("level change");
			}
			openedByUs = false;
		}

		internal static void BeforeReload()
		{
			//IL_0063: 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_0079: Expected O, but got Unknown
			//IL_007b: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_0090: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			cacheClean = false;
			bool flag = vanillaCleaned;
			vanillaCleaned = false;
			if (!Enabled || !IsHostMP || !InRun)
			{
				return;
			}
			if (PhotonNetwork.CurrentRoom.IsOpen)
			{
				Plugin.Log.LogWarning((object)"[LateJoin] Room still open at level change, late joins off for this level.");
				return;
			}
			if (!persistentObjectsSupported())
			{
				Plugin.Log.LogWarning((object)"[LateJoin] Room doesn't support cache cleanup, late joins off for this level.");
				return;
			}
			if (!flag)
			{
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add(keyByteNine, (object)false);
				Hashtable val2 = val;
				RaiseEventOptions val3 = new RaiseEventOptions
				{
					CachingOption = (EventCaching)6,
					Receivers = (ReceiverGroup)2
				};
				if (!PhotonNetwork.RaiseEvent((byte)0, (object)val2, val3, SendOptions.SendReliable))
				{
					Plugin.Log.LogWarning((object)"[LateJoin] Cache cleanup failed, late joins off for this level.");
					return;
				}
			}
			RunManager instance = RunManager.instance;
			RunManagerPUN val4 = runManagerPUN.Invoke(instance);
			PhotonView val5 = (((Object)(object)val4 != (Object)null) ? punView.Invoke(val4) : null);
			if ((Object)(object)val5 == (Object)null)
			{
				Plugin.Log.LogWarning((object)"[LateJoin] Level sync not found, late joins off for this level.");
				return;
			}
			val5.RPC("UpdateLevelRPC", (RpcTarget)4, new object[3]
			{
				((Object)instance.levelCurrent).name,
				instance.levelsCompleted,
				false
			});
			cacheClean = true;
		}

		internal static void VanillaCleaned()
		{
			vanillaCleaned = true;
		}

		internal static void PlayerEntered(Player player)
		{
			if (player != null && IsHostMP && InRun)
			{
				joinedThisLevel.Add(player.ActorNumber);
				Plugin.Log.LogInfo((object)("[LateJoin] " + player.NickName + " joined mid-run."));
			}
		}

		internal static void Registered(PlayerAvatar avatar, bool known)
		{
			if (!((Object)(object)avatar == (Object)null) && !((Object)(object)avatar.photonView == (Object)null) && avatar.photonView.Owner != null)
			{
				int actorNumber = avatar.photonView.Owner.ActorNumber;
				if (joinedThisLevel.Contains(actorNumber) && welcomed.Add(actorNumber))
				{
					Runner.Run(Welcome(avatar.photonView.Owner, SemiFunc.PlayerGetSteamID(avatar), SemiFunc.PlayerGetName(avatar), known));
				}
			}
		}

		private static bool StillHere(Player player)
		{
			if (IsHostMP && player != null)
			{
				return PhotonNetwork.CurrentRoom.Players.ContainsKey(player.ActorNumber);
			}
			return false;
		}

		private static IEnumerator Welcome(Player player, string steamID, string name, bool known)
		{
			try
			{
				SyncLayout(player);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("[LateJoin] Layout sync failed: " + ex));
			}
			try
			{
				SyncIntroDone(player);
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogError((object)("[LateJoin] Intro sync failed: " + ex2));
			}
			PunManager instance = PunManager.instance;
			if (instance != null)
			{
				instance.SyncAllDictionaries();
			}
			Plugin.Log.LogInfo((object)("[LateJoin] Sent stats to " + name + " (" + (known ? "in this save" : "new to this save") + ")."));
			yield return (object)new WaitForSeconds(5f);
			if (!StillHere(player))
			{
				yield break;
			}
			try
			{
				SyncIntroDone(player);
			}
			catch (Exception ex3)
			{
				Plugin.Log.LogError((object)("[LateJoin] Intro sync failed: " + ex3));
			}
			try
			{
				Resync(player);
			}
			catch (Exception ex4)
			{
				Plugin.Log.LogError((object)("[LateJoin] Level resync failed: " + ex4));
			}
			try
			{
				SyncProps(player);
			}
			catch (Exception ex5)
			{
				Plugin.Log.LogError((object)("[LateJoin] Prop sync failed: " + ex5));
			}
			if (known || !Plugin.StarterKitEnabled.Value)
			{
				yield break;
			}
			int num = Mathf.Max(1, Plugin.StarterKitLevelsPer.Value);
			int n = Mathf.Min(Plugin.StarterKitMax.Value, RunManager.instance.levelsCompleted / num);
			if (n <= 0)
			{
				yield break;
			}
			yield return (object)new WaitForSeconds(5f);
			if (!StillHere(player))
			{
				yield break;
			}
			PlayerAvatar val = SemiFunc.PlayerAvatarGetFromSteamID(steamID);
			if ((Object)(object)val == (Object)null)
			{
				yield break;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			for (int i = 0; i < n; i++)
			{
				string key = Upgrades.PickRandom();
				dictionary.TryGetValue(key, out var value);
				dictionary[key] = value + 1;
			}
			foreach (KeyValuePair<string, int> item in dictionary)
			{
				Upgrades.Give(steamID, item.Key, item.Value);
			}
			Upgrades.Flash(val);
			string text = string.Join(", ", dictionary.Select((KeyValuePair<string, int> kv) => $"+{kv.Value} {Upgrades.Pretty(kv.Key)}"));
			Announce.Truck("<b>" + name + "</b> joined. Starter kit: " + text, banner: false);
			Plugin.Log.LogInfo((object)("[LateJoin] Starter kit for " + name + ": " + text));
		}

		private static object[] Flags(Module m, string[] names)
		{
			object[] array = new object[names.Length + 1];
			for (int i = 0; i < names.Length; i++)
			{
				array[i] = (bool)AccessTools.Field(typeof(Module), names[i]).GetValue(m);
			}
			array[names.Length] = (bool)AccessTools.Field(typeof(Module), "First").GetValue(m);
			return array;
		}

		private static void SyncLayout(Player to)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			int num = 0;
			Module[] array = Object.FindObjectsByType<Module>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (Module val in array)
			{
				PhotonView val2 = modView.Invoke(val);
				if (!((Object)(object)val2 == (Object)null))
				{
					if ((int)val.type == 5)
					{
						val2.RPC("ModuleConnectionSetMegaRPC", to, Flags(val, megaSides));
					}
					else
					{
						val2.RPC("ModuleConnectionSetRPC", to, Flags(val, normalSides));
					}
					num++;
				}
			}
			ValuableDirector instance = ValuableDirector.instance;
			PhotonView val3 = (((Object)(object)instance != (Object)null) ? ((Component)instance).GetComponent<PhotonView>() : null);
			if ((Object)(object)val3 != (Object)null)
			{
				int num2 = (int)AccessTools.Field(typeof(ValuableDirector), "valuableTargetAmount").GetValue(instance);
				int num3 = (int)AccessTools.Field(typeof(ValuableDirector), "cosmeticWorldObjectTargetAmount").GetValue(instance);
				if (num2 >= 0)
				{
					val3.RPC("ValuablesTargetSetRPC", to, new object[1] { num2 });
				}
				if (num3 >= 0)
				{
					val3.RPC("CosmeticWorldObjectTargetSetRPC", to, new object[1] { num3 });
				}
				val3.RPC("VolumesAndSwitchSetupRPC", to, Array.Empty<object>());
			}
			Plugin.Log.LogInfo((object)$"[LateJoin] Sent level layout to {to.NickName} ({num} modules).");
		}

		private static List<KeyValuePair<int, int>> BrokenProps()
		{
			if ((Object)(object)brokenLevel != (Object)(object)LevelGenerator.Instance)
			{
				brokenProps.Clear();
				brokenLevel = LevelGenerator.Instance;
			}
			return brokenProps;
		}

		internal static void PropBroken(PhysGrabObject obj)
		{
			if (IsHostMP && !((Object)(object)obj == (Object)null))
			{
				PhotonView component = ((Component)obj).GetComponent<PhotonView>();
				if (!((Object)(object)component == (Object)null) && component.ViewID != 0 && (component.ViewID != component.InstantiationId || !component.IsMine))
				{
					BrokenProps().Add(new KeyValuePair<int, int>(component.ViewID, component.Prefix));
				}
			}
		}

		private static void SendRpc(int viewID, int prefix, string method, Player to)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			Hashtable val = new Hashtable
			{
				[(byte)0] = viewID,
				[(byte)2] = PhotonNetwork.ServerTimestamp,
				[(byte)3] = method
			};
			if (prefix > 0)
			{
				val[(byte)1] = (short)prefix;
			}
			RaiseEventOptions val2 = new RaiseEventOptions();
			val2.TargetActors = new int[1] { to.ActorNumber };
			RaiseEventOptions val3 = val2;
			PhotonNetwork.NetworkingClient.OpRaiseEvent((byte)200, (object)val, val3, SendOptions.SendReliable);
		}

		private static void SyncProps(Player to)
		{
			int num = 0;
			int num2 = 0;
			foreach (KeyValuePair<int, int> item in BrokenProps())
			{
				SendRpc(item.Key, item.Value, "DestroyPhysGrabObjectRPC", to);
				num++;
			}
			ValuablePropSwitch[] array = Object.FindObjectsByType<ValuablePropSwitch>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (ValuablePropSwitch val in array)
			{
				if ((Object)(object)val == (Object)null || !(bool)AccessTools.Field(typeof(ValuablePropSwitch), "SetupComplete").GetValue(val) || (Object)(object)val.PropParent == (Object)null || val.PropParent.activeSelf)
				{
					continue;
				}
				PhysGrabObject[] componentsInChildren = val.PropParent.GetComponentsInChildren<PhysGrabObject>(true);
				for (int j = 0; j < componentsInChildren.Length; j++)
				{
					PhotonView component = ((Component)componentsInChildren[j]).GetComponent<PhotonView>();
					if (!((Object)(object)component == (Object)null) && component.ViewID != 0)
					{
						SendRpc(component.ViewID, component.Prefix, "DestroyPhysGrabObjectRPC", to);
						num2++;
					}
				}
			}
			Plugin.Log.LogInfo((object)$"[LateJoin] Sent props to {to.NickName} ({num} broken, {num2} hidden).");
		}

		private static void SyncIntroDone(Player to)
		{
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			int actorNumber = PhotonNetwork.LocalPlayer.ActorNumber;
			List<PhotonView> list = new List<PhotonView>();
			foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
			{
				PhotonView val = (((Object)(object)player != (Object)null) ? player.photonView : null);
				if (!((Object)(object)val == (Object)null) && val.Owner != null && val.Owner != to && paIntroDone.Invoke(player))
				{
					list.Add(val);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			List<int> list2 = new List<int>();
			List<int> list3 = new List<int>();
			foreach (PhotonView item in list)
			{
				if (item.OwnerActorNr != actorNumber)
				{
					list2.Add(item.ViewID);
					list2.Add(actorNumber);
					list3.Add(item.ViewID);
					list3.Add(item.OwnerActorNr);
				}
			}
			RaiseEventOptions val2 = new RaiseEventOptions();
			val2.TargetActors = new int[1] { to.ActorNumber };
			RaiseEventOptions val3 = val2;
			if (list2.Count > 0)
			{
				PhotonNetwork.NetworkingClient.OpRaiseEvent((byte)212, (object)list2.ToArray(), val3, SendOptions.SendReliable);
			}
			foreach (PhotonView item2 in list)
			{
				item2.RPC("LoadingLevelAnimationCompletedRPC", to, Array.Empty<object>());
			}
			if (list3.Count > 0)
			{
				PhotonNetwork.NetworkingClient.OpRaiseEvent((byte)212, (object)list3.ToArray(), val3, SendOptions.SendReliable);
			}
			Plugin.Log.LogInfo((object)$"[LateJoin] Sent level intro state to {to.NickName} ({list.Count} players).");
		}

		private static void Resync(Player to)
		{
			if (!SemiFunc.RunIsLevel())
			{
				return;
			}
			int num = 0;
			RoundDirector instance = RoundDirector.instance;
			PhotonView val = (((Object)(object)instance != (Object)null) ? rdView.Invoke(instance) : null);
			if ((Object)(object)val != (Object)null)
			{
				val.RPC("StartRoundRPC", to, new object[1] { rdHaulGoal.Invoke(instance) });
				num++;
				ExtractionPoint val2 = rdCurrent.Invoke(instance);
				foreach (GameObject item in rdPoints.Invoke(instance))
				{
					ExtractionPoint val3 = (((Object)(object)item != (Object)null) ? item.GetComponent<ExtractionPoint>() : null);
					PhotonView val4 = (((Object)(object)val3 != (Object)null) ? epView.Invoke(val3) : null);
					if (!((Object)(object)val4 == (Object)null) && !((Object)(object)val3 == (Object)(object)val2) && (int)epState.Invoke(val3) == 7)
					{
						val4.RPC("StateSetRPC", to, new object[1] { (object)(State)7 });
						num++;
					}
				}
				if ((Object)(object)val2 != (Object)null && (Object)(object)epView.Invoke(val2) != (Object)null)
				{
					PhotonView val5 = epView.Invoke(val2);
					if ((int)epState.Invoke(val2) == 7)
					{
						val5.RPC("StateSetRPC", to, new object[1] { (object)(State)7 });
						num++;
					}
					else
					{
						val.RPC("ExtractionPointActivateRPC", to, new object[1] { val5.ViewID });
						val5.RPC("StateSetRPC", to, new object[1] { (object)(State)2 });
						val5.RPC("HaulGoalSetRPC", to, new object[1] { val2.haulGoal });
						num += 3;
					}
				}
				if (rdAllDone.Invoke(instance))
				{
					val.RPC("ExtractionCompletedAllRPC", to, Array.Empty<object>());
					num++;
				}
			}
			if ((Object)(object)ValuableDirector.instance != (Object)null)
			{
				foreach (ValuableObject valuable in ValuableDirector.instance.valuableList)
				{
					PhotonView val6 = (((Object)(object)valuable != (Object)null) ? voView.Invoke(valuable) : null);
					if (!((Object)(object)val6 == (Object)null) && val6.ViewID != 0)
					{
						if (voValueSet.Invoke(valuable))
						{
							val6.RPC("DollarValueSetRPC", to, new object[1] { voValue.Invoke(valuable) });
							num++;
						}
						if (voDiscovered.Invoke(valuable))
						{
							val6.RPC("DiscoverRPC", to, Array.Empty<object>());
							num++;
						}
					}
				}
			}
			if ((Object)(object)instance != (Object)null)
			{
				foreach (GameObject dollarHaul in instance.dollarHaulList)
				{
					ValuableObject val7 = (((Object)(object)dollarHaul != (Object)null) ? dollarHaul.GetComponent<ValuableObject>() : null);
					PhotonView val8 = (((Object)(object)val7 != (Object)null) ? voView.Invoke(val7) : null);
					if (!((Object)(object)val8 == (Object)null) && val8.ViewID != 0)
					{
						val8.RPC("AddToDollarHaulListRPC", to, Array.Empty<object>());
						num++;
					}
				}
			}
			PhysGrabHinge[] array = Object.FindObjectsOfType<PhysGrabHinge>();
			foreach (PhysGrabHinge val9 in array)
			{
				PhotonView val10 = hingeView.Invoke(val9);
				if (!((Object)(object)val10 == (Object)null) && val10.ViewID != 0 && hingeBroken.Invoke(val9) && !hingeDead.Invoke(val9))
				{
					val10.RPC("HingeBreakRPC", to, Array.Empty<object>());
					num++;
				}
			}
			if ((Object)(object)EnemyDirector.instance != (Object)null && EnemyDirector.instance.enemiesSpawned != null)
			{
				foreach (EnemyParent item2 in EnemyDirector.instance.enemiesSpawned)
				{
					if (!((Object)(object)item2 == (Object)null) && !((Object)(object)((MonoBehaviourPun)item2).photonView == (Object)null) && !enemySpawned.Invoke(item2))
					{
						((MonoBehaviourPun)item2).photonView.RPC("DespawnRPC", to, Array.Empty<object>());
						num++;
					}
				}
			}
			if ((Object)(object)GameDirector.instance != (Object)null)
			{
				foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
				{
					if (!((Object)(object)player == (Object)null) && !((Object)(object)player.photonView == (Object)null) && player.photonView.Owner != to && (playerDisabled.Invoke(player) || playerDeadSet.Invoke(player)))
					{
						player.photonView.RPC("PlayerDeathRPC", to, new object[1] { -1 });
						num++;
					}
				}
			}
			Plugin.Log.LogInfo((object)$"[LateJoin] Resynced level for {to.NickName} ({num} updates).");
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "LoadLevel", new Type[] { typeof(string) })]
	internal static class LateJoinReloadPatch
	{
		private static void Prefix(string levelName)
		{
			if (levelName != "Reload" || !PhotonNetwork.IsMasterClient)
			{
				return;
			}
			try
			{
				LateJoin.BeforeReload();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Late join cleanup failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabObject), "DestroyPhysGrabObject")]
	internal static class LateJoinPropBrokenPatch
	{
		private static void Prefix(PhysGrabObject __instance)
		{
			try
			{
				LateJoin.PropBroken(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Late join prop tracking failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(NetworkManager), "DestroyRunObjects")]
	internal static class LateJoinVanillaCleanPatch
	{
		private static void Postfix()
		{
			LateJoin.VanillaCleaned();
		}
	}
	[HarmonyPatch(typeof(NetworkManager), "OnPlayerEnteredRoom")]
	internal static class LateJoinEnteredPatch
	{
		private static void Postfix(Player newPlayer)
		{
			try
			{
				LateJoin.PlayerEntered(newPlayer);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Late join tracking failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "AddToStatsManagerForced")]
	internal static class LateJoinRegisterPatch
	{
		private static void Prefix(string _steamID, out bool __state)
		{
			__state = !string.IsNullOrEmpty(_steamID) && (Object)(object)StatsManager.instance != (Object)null && StatsManager.instance.playerNames.ContainsKey(_steamID);
		}

		private static void Postfix(PlayerAvatar __instance, bool __state)
		{
			if (!PhotonNetwork.IsMasterClient || !SemiFunc.IsMultiplayer() || __instance.photonView.IsMine)
			{
				return;
			}
			try
			{
				LateJoin.Registered(__instance, __state);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Late join welcome failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "Start")]
	internal static class LateJoinSpawnPatch
	{
		internal static PlayerAvatar Only;

		private static void Prefix(PlayerAvatar __instance)
		{
			Only = null;
			if (SemiFunc.IsMasterClient() && !((Object)(object)LevelGenerator.Instance == (Object)null) && LevelGenerator.Instance.Generated && !SemiFunc.MenuLevel())
			{
				Only = __instance;
			}
		}

		private static Exception Finalizer(Exception __exception)
		{
			Only = null;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "PlayerSpawn")]
	internal static class LateJoinPlayerSpawnPatch
	{
		private static void Prefix(out List<PlayerAvatar> __state)
		{
			__state = null;
			PlayerAvatar only = LateJoinSpawnPatch.Only;
			if (!((Object)(object)only == (Object)null) && !((Object)(object)GameDirector.instance == (Object)null))
			{
				__state = GameDirector.instance.PlayerList;
				GameDirector.instance.PlayerList = new List<PlayerAvatar> { only };
			}
		}

		private static Exception Finalizer(Exception __exception, List<PlayerAvatar> __state)
		{
			if (__state != null && (Object)(object)GameDirector.instance != (Object)null)
			{
				GameDirector.instance.PlayerList = __state;
			}
			return __exception;
		}
	}
	internal static class Players
	{
		public const int SteamLobbyHardMax = 250;

		private static bool retryInProgress;

		private static bool vanillaCaptured;

		private static int vanillaMaxPlayers = 6;

		private static int vanillaPhotonCap = 20;

		private static readonly Regex CapRegex = new Regex("(\\d+)\\D*$", RegexOptions.Compiled);

		internal static bool Enabled => Plugin.PlayersEnabled.Value;

		internal static int SliderMax
		{
			get
			{
				int value = Plugin.DetectedPhotonCap.Value;
				if (value <= 1 || value >= 250)
				{
					return 250;
				}
				return value;
			}
		}

		internal static int Target
		{
			get
			{
				int num = Mathf.Clamp(Plugin.MaxPlayers.Value, 2, 250);
				int value = Plugin.DetectedPhotonCap.Value;
				if (value > 0 && value < num)
				{
					num = value;
				}
				return num;
			}
		}

		internal static void CaptureVanilla(GameManager gm)
		{
			if (!vanillaCaptured && !((Object)(object)gm == (Object)null))
			{
				vanillaCaptured = true;
				vanillaMaxPlayers = gm.maxPlayers;
				vanillaPhotonCap = gm.maxPlayersPhoton;
			}
		}

		internal static void Apply(string source)
		{
			if (!Enabled)
			{
				return;
			}
			GameManager instance = GameManager.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				int target = Target;
				if (instance.maxPlayersPhoton < target)
				{
					instance.maxPlayersPhoton = target;
				}
				if (instance.maxPlayers != target)
				{
					instance.maxPlayers = target;
					Plugin.Log.LogInfo((object)$"[Players/{source}] maxPlayers -> {target}");
				}
			}
		}

		internal static void SyncLiveRoom(string source)
		{
			GameManager instance = GameManager.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (Enabled)
			{
				Apply(source);
				if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient)
				{
					instance.SetMaxPlayers(Target);
				}
			}
			else
			{
				instance.maxPlayersPhoton = vanillaPhotonCap;
				if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient)
				{
					instance.SetMaxPlayers(vanillaMaxPlayers);
				}
				else
				{
					instance.maxPlayers = vanillaMaxPlayers;
				}
			}
			if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && PhotonNetwork.CurrentRoom != null)
			{
				Plugin.Log.LogInfo((object)$"[Players/{source}] Room MaxPlayers = {PhotonNetwork.CurrentRoom.MaxPlayers}");
			}
		}

		internal static bool HandleTooBig(NetworkConnect nc, string cause)
		{
			if (!Enabled)
			{
				return false;
			}
			if (string.IsNullOrEmpty(cause) || !cause.ToLowerInvariant().Contains("max players peer room value is too big"))
			{
				return false;
			}
			Match match = CapRegex.Match(cause);
			if (!match.Success || !int.TryParse(match.Groups[1].Value, out var result) || result < 2)
			{
				Plugin.Log.LogWarning((object)("Photon rejected the room size but the cap could not be parsed: " + cause));
				return false;
			}
			Plugin.DetectedPhotonCap.Value = result;
			Plugin.Log.LogWarning((object)$"Photon server caps rooms at {result} players. Using {result} from now on.");
			if ((Object)(object)GameManager.instance != (Object)null)
			{
				GameManager.instance.maxPlayersPhoton = result;
				GameManager.instance.maxPlayers = Mathf.Min(Target, result);
			}
			if (retryInProgress || (Object)(object)nc == (Object)null)
			{
				return false;
			}
			retryInProgress = true;
			((MonoBehaviour)nc).StartCoroutine(RetryWhenOnMaster(nc));
			return true;
		}

		private static IEnumerator RetryWhenOnMaster(NetworkConnect nc)
		{
			float timeout = 15f;
			while (timeout > 0f && (int)PhotonNetwork.NetworkClientState != 15 && (int)PhotonNetwork.NetworkClientState != 4)
			{
				timeout -= Time.unscaledDeltaTime;
				yield return null;
			}
			try
			{
				if (timeout <= 0f || (Object)(object)nc == (Object)null)
				{
					Plugin.Log.LogError((obj