Decompiled source of AI LIMIT Coop v0.4.3

BepInEx/plugins/AILimitCoop/AILimitCoop.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using AILimitCoop.Dev;
using AILimitCoop.Game;
using AILimitCoop.Net;
using AILimitCoop.UI;
using AILimitCoop.Util;
using AILimitPhotoMode;
using ArchiveDef;
using AtmosphericHeightFog;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
using BehaviorDesigner.Runtime.Tasks.Unity.Math;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.UnityEngine;
using Bullets;
using GameDef;
using HarmonyLib;
using Il2CppInterop.Common.XrefScans;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using LevelEdit;
using LiteNetLib;
using LiteNetLib.Layers;
using LiteNetLib.Utils;
using Logic.BossRush;
using Logic.RoguelikeAbility;
using MagicaCloth2;
using Microsoft.CodeAnalysis;
using MonsterGroupManager;
using PlayerShowSateDefine;
using ProtoUtility;
using RootMotion.Dynamics;
using SceneSettingDef;
using SenseGame;
using SenseGame.Tasks;
using Steamworks;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.AddressableAssets;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Samples;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Playables;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("AILimitCoop contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.3.0")]
[assembly: AssemblyInformationalVersion("0.3.8+844729c83d448e6315b248b396253c4bbd88ad75")]
[assembly: AssemblyProduct("AI LIMIT Co-op")]
[assembly: AssemblyTitle("AILimitCoop")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.4.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 AILimitCoop
{
	public enum PartyHudCorner
	{
		TopRight,
		TopLeft,
		BottomRight,
		BottomLeft
	}
	public enum MenuSize
	{
		Auto,
		Normal,
		Large
	}
	public enum PadButtons
	{
		Auto,
		Xbox,
		PlayStation
	}
	public enum TransportKind
	{
		UDP,
		Steam
	}
	public enum HitDetectionMode
	{
		Auto,
		ClientSide,
		HostForward
	}
	public static class CoopConfig
	{
		public static ConfigEntry<string> PlayerName;

		public static ConfigEntry<bool> PublicGame;

		public static ConfigEntry<bool> AskBeforeJoin;

		public static ConfigEntry<bool> ShowJoinCode;

		public static ConfigEntry<bool> ShowPrivateGames;

		public static ConfigEntry<string> PlayerEmblem;

		public static ConfigEntry<TransportKind> Transport;

		public static ConfigEntry<int> Port;

		public static ConfigEntry<string> JoinAddress;

		public static ConfigEntry<int> MaxPlayers;

		public static ConfigEntry<KeyCode> ToggleMenuKey;

		public static ConfigEntry<KeyCode> HostKey;

		public static ConfigEntry<KeyCode> JoinKey;

		public static ConfigEntry<KeyCode> LeaveKey;

		public static ConfigEntry<float> PlayerSendRate;

		public static ConfigEntry<float> MonsterSendRate;

		public static ConfigEntry<float> NetworkDiagnosticsInterval;

		public static ConfigEntry<float> InterpolationDelay;

		public static ConfigEntry<float> GhostAnimSmoothing;

		public static ConfigEntry<float> GhostAnimCrossFade;

		public static ConfigEntry<bool> SyncMonsters;

		public static ConfigEntry<bool> SyncEnemyBreakState;

		public static ConfigEntry<bool> SyncEnemyEffects;

		public static ConfigEntry<bool> SyncPlayerEffects;

		public static ConfigEntry<bool> SyncPlayerProjectiles;

		public static ConfigEntry<bool> SyncPlayerWorldEffects;

		public static ConfigEntry<bool> SyncRogueLayout;

		public static ConfigEntry<bool> AssistBossWake;

		public static ConfigEntry<bool> SyncRogueTrials;

		public static ConfigEntry<bool> SyncRogueStageExits;

		public static ConfigEntry<bool> SyncExecutions;

		public static ConfigEntry<bool> SyncRoomClears;

		public static ConfigEntry<float> EnemyHpPerExtraPlayer;

		public static ConfigEntry<DifficultyPreset> Difficulty;

		public static ConfigEntry<float> BossHpPerExtraPlayer;

		public static ConfigEntry<float> BreakResistPerExtraPlayer;

		public static ConfigEntry<bool> AllowPvp;

		public static ConfigEntry<PvpDamagePreset> PvpDamage;

		public static ConfigEntry<bool> PvpArena;

		public static ConfigEntry<bool> GhostTargeting;

		public static ConfigEntry<HitDetectionMode> HitDetection;

		public static ConfigEntry<bool> GhostEquipment;

		public static ConfigEntry<bool> GhostCollision;

		public static ConfigEntry<bool> ShowFallenPlayers;

		public static ConfigEntry<bool> SyncWeakPoints;

		public static ConfigEntry<bool> CutsceneSpacing;

		public static ConfigEntry<bool> ShowAllySync;

		public static ConfigEntry<bool> ForceRunInBackground;

		public static ConfigEntry<bool> EnableOverlay;

		public static ConfigEntry<bool> ShowHud;

		public static ConfigEntry<float> HudScale;

		public static ConfigEntry<float> HudOpacity;

		public static ConfigEntry<PartyHudCorner> HudCorner;

		public static ConfigEntry<MenuSize> MenuSize;

		public static ConfigEntry<PadButtons> PadButtons;

		public static ConfigEntry<bool> AllyHealthBars;

		public static ConfigEntry<float> AllyHealthBarDistance;

		public static ConfigEntry<bool> AllyHealthBarNames;

		public static ConfigEntry<bool> ShowChat;

		public static ConfigEntry<KeyCode> ChatKey;

		public static ConfigEntry<KeyCode> PingKey;

		public static ConfigEntry<bool> ShowPings;

		public static ConfigEntry<string> PlayerColor;

		public static ConfigEntry<bool> PadPing;

		public static ConfigEntry<string> PadPingModifier;

		public static ConfigEntry<bool> ShowMenuOnStart;

		public const string DefaultPlayerName = "Player";

		public static ConfigEntry<bool> Verbose;

		public static ConfigEntry<bool> DevCommands;

		public static ConfigEntry<string> PatchGroups;

		public static ConfigEntry<int> SimulatedLatencyMs;

		public static ConfigEntry<int> SimulatedJitterMs;

		public static ConfigEntry<int> SimulatedPacketLossPercent;

		public const string DevFileName = "com.ailimit.coop.dev.cfg";

		public static DifficultySettings EffectiveDifficulty => CoopDifficulty.For(Difficulty.Value, EnemyHpPerExtraPlayer.Value, BossHpPerExtraPlayer.Value, BreakResistPerExtraPlayer.Value);

		public static int EffectivePort
		{
			get
			{
				if (InstanceProfile.Port <= 0)
				{
					return Port.Value;
				}
				return InstanceProfile.Port;
			}
		}

		public static string EffectivePlayerName
		{
			get
			{
				if (!string.IsNullOrEmpty(InstanceProfile.PlayerName))
				{
					return InstanceProfile.PlayerName;
				}
				string text = PlayerName?.Value;
				if (!string.IsNullOrWhiteSpace(text) && text != "Player")
				{
					return text;
				}
				string localName = SteamPresence.LocalName;
				if (!string.IsNullOrWhiteSpace(localName))
				{
					return localName;
				}
				return "Player";
			}
		}

		public static bool DevFile { get; private set; }

		public static int RetiredDropped { get; private set; }

		public static void Bind(ConfigFile cfg)
		{
			//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_0037: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Expected O, but got Unknown
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Expected O, but got Unknown
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Expected O, but got Unknown
			//IL_0396: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Expected O, but got Unknown
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c6: Expected O, but got Unknown
			//IL_04b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f3: Expected O, but got Unknown
			//IL_0521: Unknown result type (might be due to invalid IL or missing references)
			//IL_052b: Expected O, but got Unknown
			//IL_0705: Unknown result type (might be due to invalid IL or missing references)
			//IL_070f: Expected O, but got Unknown
			//IL_073d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0747: Expected O, but got Unknown
			//IL_07fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0806: Expected O, but got Unknown
			//IL_08b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c2: Expected O, but got Unknown
			//IL_08eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f5: Expected O, but got Unknown
			//IL_0939: Unknown result type (might be due to invalid IL or missing references)
			//IL_0943: Expected O, but got Unknown
			//IL_09d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_09e3: Expected O, but got Unknown
			//IL_0a09: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a13: Expected O, but got Unknown
			//IL_0a36: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a40: Expected O, but got Unknown
			string text = Path.Combine(Path.GetDirectoryName(cfg.ConfigFilePath) ?? "", "com.ailimit.coop.dev.cfg");
			DevFile = File.Exists(text);
			ConfigFile val = new ConfigFile(text, false)
			{
				SaveOnConfigSet = false
			};
			bool flag = false;
			try
			{
				flag = File.Exists(cfg.ConfigFilePath) && !Regex.IsMatch(File.ReadAllText(cfg.ConfigFilePath), "^\\s*Difficulty\\s*=", RegexOptions.Multiline);
			}
			catch (IOException)
			{
			}
			PlayerName = cfg.Bind<string>("General", "PlayerName", DefaultName(), "Name shown to other players.");
			Transport = cfg.Bind<TransportKind>("General", "Transport", TransportKind.UDP, "UDP: connect by IP address (LAN, VPN such as ZeroTier/Radmin/Hamachi, or a forwarded port).\nSteam: host and join through your Steam friends list - no address or port forwarding needed.");
			Port = cfg.Bind<int>("General", "Port", 7777, "UDP port to host on (and default port when joining).");
			JoinAddress = cfg.Bind<string>("General", "JoinAddress", "127.0.0.1:7777", "Address used by the Join key / menu. UDP: ip:port. Steam: the host's 64-bit Steam id.");
			MaxPlayers = cfg.Bind<int>("General", "MaxPlayers", 8, new ConfigDescription("Maximum players in a hosted session, including the host. More than two is experimental; up to 16 allowed for stress testing.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 16), Array.Empty<object>()));
			PublicGame = cfg.Bind<bool>("General", "PublicGame", false, "Steam: list your game in FIND GAMES so anyone with the mod can join. Off: only friends and players with your join code.");
			AskBeforeJoin = cfg.Bind<bool>("General", "AskBeforeJoin", true, "Steam: players who aren't your Steam friends wait until you accept them in the party menu. Off: they join straight away.");
			ShowJoinCode = cfg.Bind<bool>("General", "ShowJoinCode", false, "Show your join code in the party menu. Off: it shows as ***** (for streaming) but can still be copied.");
			ShowPrivateGames = cfg.Bind<bool>("General", "ShowPrivateGames", true, "List private games in FIND GAMES (no host name; they need the host's code). Off: public games only.");
			ToggleMenuKey = cfg.Bind<KeyCode>("Keys", "ToggleMenu", (KeyCode)286, "Show/hide the co-op menu.");
			HostKey = cfg.Bind<KeyCode>("Keys", "Host", (KeyCode)287, "Start hosting a session.");
			JoinKey = cfg.Bind<KeyCode>("Keys", "Join", (KeyCode)288, "Join the session at JoinAddress.");
			LeaveKey = cfg.Bind<KeyCode>("Keys", "Leave", (KeyCode)289, "Leave / stop the current session.");
			PlayerSendRate = val.Bind<float>("Network", "PlayerSendRate", 30f, new ConfigDescription("How many times per second your character state is sent.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 60f), Array.Empty<object>()));
			MonsterSendRate = val.Bind<float>("Network", "MonsterSendRate", 15f, new ConfigDescription("Host only: how many times per second monster states are sent.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 30f), Array.Empty<object>()));
			NetworkDiagnosticsInterval = val.Bind<float>("Network", "DiagnosticsInterval", 30f, new ConfigDescription("Seconds between networking summaries in LogOutput.log. 0 disables periodic summaries; counters and rate-limited send failures remain active.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>()));
			InterpolationDelay = val.Bind<float>("Network", "InterpolationDelay", 0.1f, new ConfigDescription("Seconds of buffering applied to remote characters. Higher is smoother but adds visual latency.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.5f), Array.Empty<object>()));
			GhostAnimSmoothing = val.Bind<float>("Network", "GhostAnimSmoothing", 0.08f, "Seconds of easing applied to another player's animation blending. Updates arrive at the send rate, so writing them straight through makes movement look stepped. 0 disables.");
			GhostAnimCrossFade = val.Bind<float>("Network", "GhostAnimCrossFade", 0.06f, "Seconds to fade when another player's animation state changes, instead of cutting. 0 disables.");
			SyncMonsters = val.Bind<bool>("Gameplay", "SyncMonsters", true, "Share enemies, so everyone fights the same ones. Off: each player fights their own copy of every enemy and only the players themselves are shared.");
			SyncEnemyBreakState = val.Bind<bool>("Gameplay", "SyncEnemyBreakState", true, "Show the stagger gauge of enemies another player's game runs, and break them when it breaks there, so an execution can be offered. Disable if a broken enemy misbehaves on your machine.");
			SyncEnemyEffects = val.Bind<bool>("Gameplay", "SyncEnemyEffects", true, "Show the attack effects, attack sounds and weapon trails of enemies that another player's game runs. Cosmetic only; disable if it causes problems.");
			SyncPlayerEffects = val.Bind<bool>("Gameplay", "SyncPlayerEffects", true, "Show the spell, skill and weapon-art effects of the other players. Cosmetic only.");
			SyncPlayerProjectiles = val.Bind<bool>("Gameplay", "SyncPlayerProjectiles", true, new ConfigDescription("Show the flying projectiles of other players' spells and skills. The copy is visual only: it cannot hit anyone, and damage is unaffected.", (AcceptableValueBase)null, Array.Empty<object>()));
			SyncPlayerWorldEffects = val.Bind<bool>("Gameplay", "SyncPlayerWorldEffects", true, new ConfigDescription("Show the effects other players' abilities put into the world: a lightning strike where it was aimed, its impact, a buff flash, a weapon art's slash, a spell's flames on their blade. Visual only.", (AcceptableValueBase)null, Array.Empty<object>()));
			SyncRogueLayout = val.Bind<bool>("Gameplay", "SyncRogueLayout", true, "Furnace of War: every player fights the same rooms in a run, and the second stage is made of the same maps for everyone. Off makes each game roll its own, and each player then plays every stage alone.");
			AssistBossWake = val.Bind<bool>("Gameplay", "AssistBossWake", true, "While the host is dead and spectating, a boss starts for the living player standing in front of it. Off leaves a run unfinishable once the host is down.");
			SyncRoomClears = val.Bind<bool>("Gameplay", "SyncRoomClears", true, "When a DLC room is cleared on another player's game and not on yours - a Furnace room whose doors stay shut, a Boss Rush room with no exit rift - open it on yours too.");
			SyncRogueTrials = val.Bind<bool>("Gameplay", "SyncRogueTrials", true, "Furnace of War: a spectating player's game enters a trial when a teammate does, so the arena and its boss exist for the game that simulates them. Living players always enter their own.");
			SyncRogueStageExits = val.Bind<bool>("Gameplay", "SyncRogueStageExits", true, "Furnace of War: when a teammate takes the portal to the next stage while you are down, you get up and follow them instead of being left behind, which ended your run. Living players are told and take the portal themselves.");
			SyncExecutions = val.Bind<bool>("Gameplay", "SyncExecutions", true, "An execution (finisher) of a broken enemy, or a backstab, on an enemy that another player's game runs deals your damage there. Without it they do no damage. Executions are new in 0.3.0 and backstabs in 0.3.1; turn it off if either misbehaves in co-op.");
			Difficulty = cfg.Bind<DifficultyPreset>("Gameplay", "Difficulty", DifficultyPreset.Balanced, "Host setting, shared when players join. How much tougher enemies get for each extra player in the same area. Balanced: enemies +75% and bosses +100% HP per extra player, stagger/sync-rate breaks +50% harder per extra player. Hard: enemies +100%, bosses +150%, breaks +100% harder. Challenge: enemies +150%, bosses +200%, breaks +150% harder. Custom: the three values below. Change before hosting a new session.");
			EnemyHpPerExtraPlayer = cfg.Bind<float>("Gameplay", "EnemyHpPerExtraPlayer", 0.5f, new ConfigDescription("Difficulty = Custom only. Extra HP for ordinary enemies per extra player in the area: 0.5 = +50%, 0 disables. Combat locks the maximum until rest/reset.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			BossHpPerExtraPlayer = cfg.Bind<float>("Gameplay", "BossHpPerExtraPlayer", 1f, new ConfigDescription("Difficulty = Custom only. Extra HP for bosses and mini-bosses per extra player in the area: 1 = +100%.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			BreakResistPerExtraPlayer = cfg.Bind<float>("Gameplay", "BreakResistPerExtraPlayer", 0.5f, new ConfigDescription("Difficulty = Custom only. How much slower enemies stagger and lose sync rate per extra player: damage to those gauges is divided by 1 + this x (players - 1). 0 = the game's own rate.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			if (flag && Math.Abs(EnemyHpPerExtraPlayer.Value - 0.5f) > 0.001f)
			{
				Difficulty.Value = DifficultyPreset.Custom;
				BossHpPerExtraPlayer.Value = EnemyHpPerExtraPlayer.Value;
				BreakResistPerExtraPlayer.Value = 0f;
			}
			AllowPvp = cfg.Bind<bool>("Gameplay", "AllowPvp", true, "Host setting, shared when players join. Lets players turn PvP on for themselves (party menu, Rules). PvP only ever applies between two players who have both turned it on, and it starts off in every session. Off: no one in your sessions can turn it on.");
			PvpDamage = cfg.Bind<PvpDamagePreset>("Gameplay", "PvpDamage", PvpDamagePreset.Standard, "Host setting, shared when players join. How hard players hit each other in PvP, as a share of an attack's usual damage (player attacks are tuned for fighting enemies, so at full strength a few hits end a duel). Low: weapons 35%, spells and items 20%. Standard: weapons 50%, spells and items 30%. High: weapons 75%, spells and items 50%. Full: 100% (enemy-strength damage).");
			PvpArena = cfg.Bind<bool>("Gameplay", "PvpArena", true, "Add the PvP Arena to the teleport menu, under PvP.");
			GhostTargeting = val.Bind<bool>("Gameplay", "GhostTargeting", true, "Enemies pick which player to attack by who hurts them and who is close, as they would among allies in the base game. Off: an enemy only attacks the player whose game runs it.");
			HitDetection = val.Bind<HitDetectionMode>("Gameplay", "HitDetection", HitDetectionMode.Auto, "How monster attacks against remote players are resolved. Leave on Auto unless you know what you are doing.");
			GhostEquipment = val.Bind<bool>("Gameplay", "GhostEquipment", true, "Show other players' armour and weapons. Turn off if other players' characters fail to appear.");
			ShowFallenPlayers = val.Bind<bool>("Gameplay", "ShowFallenPlayers", true, "When another player dies, their character stays where they fell and turns to mud like a death in the game, then disappears until they are revived. Turn off to keep the old behaviour.");
			SyncWeakPoints = val.Bind<bool>("Gameplay", "SyncWeakPoints", true, "Host only: share boss weak points (shields and crystals on some bosses) so breaking one breaks it for everyone, let every player take Charon's execution, and let Charon's floor squares and fatal attack reach the player she is after. Every player follows the host's setting. On since 0.3.11.");
			CutsceneSpacing = val.Bind<bool>("Gameplay", "CutsceneSpacing", true, "When a cutscene or a scripted placement puts players on the same spot, everyone but the host steps aside to a spot of their own afterwards, and a teammate standing inside this player is hidden while the cutscene plays.");
			GhostCollision = val.Bind<bool>("Gameplay", "GhostCollision", false, "Players physically block each other instead of passing through one another.");
			ForceRunInBackground = val.Bind<bool>("General", "ForceRunInBackground", true, "Keep simulating while the game window is not focused. Needed so your character keeps syncing when you\nalt-tab, and required to run two instances on one PC.");
			EnableOverlay = val.Bind<bool>("UI", "EnableOverlay", true, "Draw the in-game menu and HUD. Turn off if the overlay causes problems; hotkeys and the config file still work.");
			ShowHud = cfg.Bind<bool>("UI", "ShowHud", true, "Show the party cards while the co-op menu is closed.");
			HudScale = cfg.Bind<float>("UI", "HudScale", 1f, new ConfigDescription("Party HUD size, relative to automatic resolution scaling.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.75f, 1.5f), Array.Empty<object>()));
			HudOpacity = cfg.Bind<float>("UI", "HudOpacity", 0.9f, new ConfigDescription("Party HUD panel opacity. Text and health remain readable.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.35f, 1f), Array.Empty<object>()));
			HudCorner = cfg.Bind<PartyHudCorner>("UI", "HudCorner", PartyHudCorner.TopRight, "Screen corner used by the party HUD.");
			MenuSize = cfg.Bind<MenuSize>("UI", "MenuSize", AILimitCoop.MenuSize.Auto, "Size of the co-op menu. Large fills the screen, for handhelds; Auto picks Large on a screen 900 pixels tall or less and on a Steam Deck.");
			PadButtons = cfg.Bind<PadButtons>("UI", "ControllerButtons", AILimitCoop.PadButtons.Auto, "Controller button names and shapes in the co-op menu: Xbox (A, B, LB, RB, View), PlayStation (Cross, Circle, L1, R1, Create), or Auto to follow the controller.");
			ShowAllySync = cfg.Bind<bool>("UI", "ShowAllySync", true, "Show each teammate's sync rate as a thin blue bar under their health, on the party cards and above their head.");
			AllyHealthBars = cfg.Bind<bool>("UI", "AllyHealthBars", true, "Show a small health bar above allies in your area. Hidden while the co-op menu is open and whenever the game hides its own enemy health bars.");
			AllyHealthBarDistance = cfg.Bind<float>("UI", "AllyHealthBarDistance", 40f, new ConfigDescription("Metres from the camera beyond which allies show no bar. Bars shrink with distance and fade out near this limit.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f), Array.Empty<object>()));
			AllyHealthBarNames = cfg.Bind<bool>("UI", "AllyHealthBarNames", true, "Show each ally's name above their health bar. Names fade out at a shorter distance than the bar.");
			ShowChat = cfg.Bind<bool>("UI", "ShowChat", true, "Show party chat and allow typing messages. Messages fade after a few seconds while chat is closed.");
			ChatKey = cfg.Bind<KeyCode>("Keys", "Chat", (KeyCode)13, "Open party chat while in a session. Enter sends and Escape closes; other co-op hotkeys pause while you type.");
			PingKey = cfg.Bind<KeyCode>("Keys", "Ping", (KeyCode)116, "Mark what you are looking at for your party: an enemy near the middle of the screen, or the spot you aim at. Mouse3 and Mouse4 (the side buttons) work too.");
			ShowPings = cfg.Bind<bool>("UI", "ShowPings", true, "Show the party's pings (and your own) on screen.");
			PlayerEmblem = cfg.Bind<string>("UI", "PlayerEmblem", "Letter", new ConfigDescription("The emblem on your party card, in your colour, as everyone in the party sees it (party menu: click your card). Letter: your initial.", (AcceptableValueBase)(object)new AcceptableValueList<string>(PlayerEmblems.Names), Array.Empty<object>()));
			PlayerColor = cfg.Bind<string>("UI", "PlayerColor", "Auto", new ConfigDescription("Your colour for the party: your name, party card, chat name and pings, as everyone sees them. Auto picks one by join order. Can also be changed in the co-op menu.", (AcceptableValueBase)(object)new AcceptableValueList<string>(PlayerColors.Names), Array.Empty<object>()));
			PadPing = cfg.Bind<bool>("Keys", "ControllerPing", true, "On a controller, hold the ping button (ControllerPingButton) and press R3 to ping (R3 does not lock on while it is held). Turn off to keep R3 as lock-on always. Can also be changed in the co-op menu (CONTROLS).");
			PadPingModifier = cfg.Bind<string>("Keys", "ControllerPingButton", "GameModifier", new ConfigDescription("The button held with R3 to ping on a controller. GameModifier = the button bound to the game's status/skill modifier (LT unless you rebound it), which does nothing on its own. LB, RB and L3 also do their own game action when pressed.", (AcceptableValueBase)(object)new AcceptableValueList<string>(PingMarkers.PadModifiers), Array.Empty<object>()));
			ShowMenuOnStart = cfg.Bind<bool>("UI", "ShowMenuOnStart", true, "Show the co-op menu when the game starts.");
			Verbose = val.Bind<bool>("Debug", "Verbose", false, "Log per-hit and per-spawn diagnostics to BepInEx/LogOutput.log.");
			DevCommands = val.Bind<bool>("Debug", "DevCommands", false, "Poll <GameDir>/BepInEx/coop_cmd.txt for developer commands (host, join, leave, dump, ...). Development aid only.");
			PatchGroups = val.Bind<string>("Debug", "PatchGroups", "Lifecycle,Ghost,Monster,Hit,Overlay", "Which groups of game hooks to install (comma separated). Troubleshooting aid: remove a group to disable that feature.\nLifecycle = level/game start tracking, Ghost = remote player bodies, Monster = shared monster simulation,\nHit = damage relay and targeting, Overlay = in-game menu/HUD drawing.");
			SimulatedLatencyMs = val.Bind<int>("Debug", "SimulatedLatencyMs", 0, new ConfigDescription("Testing aid: delay every packet this many milliseconds each way. 0 is off.\nA typical distant player sits around 30-80. Leave at 0 for real play.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), Array.Empty<object>()));
			SimulatedJitterMs = val.Bind<int>("Debug", "SimulatedJitterMs", 0, new ConfigDescription("Testing aid: vary the simulated delay by up to this much, so packets arrive unevenly.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			SimulatedPacketLossPercent = val.Bind<int>("Debug", "SimulatedPacketLossPercent", 0, new ConfigDescription("Testing aid: drop this percentage of outgoing packets. 0 is off.\n1-3 resembles a poor connection and is the case worth testing.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			DropRetired(cfg);
			Log.Info("[Config] advanced settings " + (DevFile ? "read from com.ailimit.coop.dev.cfg" : "at their defaults") + ((RetiredDropped > 0) ? $"; {RetiredDropped} unused entries removed from the config file" : ""));
		}

		private static void DropRetired(ConfigFile cfg)
		{
			try
			{
				if (AccessTools.Property(typeof(ConfigFile), "OrphanedEntries")?.GetValue(cfg) is IDictionary { Count: >0 } dictionary)
				{
					RetiredDropped = dictionary.Count;
					dictionary.Clear();
				}
			}
			catch (Exception ex)
			{
				Log.Warn("[Config] could not tidy the config file: " + ex.Message);
			}
		}

		private static string DefaultName()
		{
			return "Player";
		}
	}
	public sealed class KeyEdge
	{
		private readonly Dictionary<KeyCode, bool> _held = new Dictionary<KeyCode, bool>();

		private static readonly int _pid = Process.GetCurrentProcess().Id;

		[DllImport("user32.dll")]
		private static extern short GetAsyncKeyState(int vKey);

		public static bool MouseButtonHeld()
		{
			if ((GetAsyncKeyState(1) & 0x8000) == 0 && (GetAsyncKeyState(2) & 0x8000) == 0)
			{
				return (GetAsyncKeyState(4) & 0x8000) != 0;
			}
			return true;
		}

		[DllImport("user32.dll")]
		private static extern IntPtr GetForegroundWindow();

		[DllImport("user32.dll")]
		private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

		public static bool GameHasFocus()
		{
			try
			{
				IntPtr foregroundWindow = GetForegroundWindow();
				if (foregroundWindow == IntPtr.Zero)
				{
					return false;
				}
				GetWindowThreadProcessId(foregroundWindow, out var processId);
				return processId == (uint)_pid;
			}
			catch
			{
				return true;
			}
		}

		public static int ToVirtualKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Expected I4, but got Unknown
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Invalid comparison between Unknown and I4
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Invalid comparison between Unknown and I4
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Invalid comparison between Unknown and I4
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Invalid comparison between Unknown and I4
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Invalid comparison between Unknown and I4
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Invalid comparison between Unknown and I4
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected I4, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Invalid comparison between Unknown and I4
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Invalid comparison between Unknown and I4
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Invalid comparison between Unknown and I4
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Invalid comparison between Unknown and I4
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Invalid comparison between Unknown and I4
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected I4, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Expected I4, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected I4, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected I4, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Invalid comparison between Unknown and I4
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Invalid comparison between Unknown and I4
			int num = (int)key;
			if ((int)key >= 282 && (int)key <= 296)
			{
				return 112 + (num - 282);
			}
			if ((int)key >= 97 && (int)key <= 122)
			{
				return 65 + (num - 97);
			}
			if ((int)key >= 48 && (int)key <= 57)
			{
				return 48 + (num - 48);
			}
			if ((int)key >= 256 && (int)key <= 265)
			{
				return 96 + (num - 256);
			}
			if ((int)key <= 47)
			{
				if ((int)key <= 13)
				{
					if ((int)key == 8)
					{
						return 8;
					}
					if ((int)key == 9)
					{
						return 9;
					}
					if ((int)key == 13)
					{
						return 13;
					}
				}
				else if ((int)key <= 27)
				{
					if ((int)key == 19)
					{
						return 19;
					}
					if ((int)key == 27)
					{
						return 27;
					}
				}
				else
				{
					if ((int)key == 32)
					{
						return 32;
					}
					switch (key - 39)
					{
					case 6:
						return 189;
					case 0:
						return 222;
					case 5:
						return 188;
					case 7:
						return 190;
					case 8:
						return 191;
					}
				}
			}
			else if ((int)key <= 96)
			{
				if ((int)key == 59)
				{
					return 186;
				}
				if ((int)key == 61)
				{
					return 187;
				}
				switch (key - 91)
				{
				case 5:
					return 192;
				case 0:
					return 219;
				case 2:
					return 221;
				case 1:
					return 220;
				}
			}
			else if ((int)key <= 281)
			{
				if ((int)key == 127)
				{
					return 46;
				}
				switch (key - 273)
				{
				case 7:
					return 33;
				case 8:
					return 34;
				case 6:
					return 35;
				case 5:
					return 36;
				case 3:
					return 37;
				case 0:
					return 38;
				case 2:
					return 39;
				case 1:
					return 40;
				case 4:
					return 45;
				}
			}
			else
			{
				switch (key - 300)
				{
				case 1:
					return 20;
				case 0:
					return 144;
				case 2:
					return 145;
				case 4:
					return 160;
				case 3:
					return 161;
				case 6:
					return 162;
				case 5:
					return 163;
				case 8:
					return 164;
				case 7:
					return 165;
				}
				switch (key - 325)
				{
				case 0:
					return 4;
				case 1:
					return 5;
				case 2:
					return 6;
				}
			}
			return 0;
		}

		public bool Pressed(KeyCode key)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			try
			{
				int num = ToVirtualKey(key);
				if (num != 0)
				{
					flag = (GetAsyncKeyState(num) & 0x8000) != 0;
				}
			}
			catch
			{
			}
			bool value;
			bool flag2 = _held.TryGetValue(key, out value) && value;
			_held[key] = flag;
			if (flag)
			{
				return !flag2;
			}
			return false;
		}

		public bool Held(KeyCode key)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			bool value;
			return _held.TryGetValue(key, out value) && value;
		}
	}
	public sealed class CoopRuntime
	{
		public readonly Session Session;

		public readonly RemotePlayerManager Ghosts;

		public readonly MonsterSyncHost MonsterHost;

		public readonly MonsterSyncClient MonsterClient;

		public readonly MonsterFxSync EnemyFx;

		public readonly PlayerFxSync PlayerFx;

		public readonly PlayerProjectileSync PlayerShots;

		public readonly PlayerWorldFxSync PlayerWorldFx;

		public readonly RogueLayoutSync RogueLayout;

		public readonly BossWakeAssist BossWake;

		public readonly RogueTrialSync RogueTrial;

		public readonly RogueStageSync RogueStage;

		public readonly RoomClearSync RoomClear;

		public readonly SummonSync Summons;

		public readonly GuardianFightSync Guardians;

		public readonly WeakPointSync WeakPoints;

		public readonly MonsterAuthority Authority;

		public readonly EnemyHealthScaling HealthScaling;

		public readonly LocalPlayerSampler Sampler = new LocalPlayerSampler();

		public readonly MonsterIndex MonsterIndex = new MonsterIndex();

		public readonly CoopUI UI;

		public readonly MenuInputFocus MenuFocus;

		public readonly ControllerMenu Pad;

		public readonly BossRewardSync Rewards;

		public readonly BossProgressMirror Progress;

		public readonly PartyLife Life;

		public readonly DefenseWatch Defense = new DefenseWatch();

		public BossMusicTracker Music;

		public readonly MonsterThreat Threat;

		public readonly TeammateTriggers Triggers;

		public readonly SharedWorld World;

		public readonly BossEncounterSync Encounters;

		public readonly BossPresentationSync Presentation;

		public readonly CutsceneSpacing Spacing;

		public readonly BossShowRelay BossShows;

		public readonly PingMarkers Pings;

		public readonly RogueAbilitySync Abilities;

		public readonly PhotoPoseSync PhotoPoses;

		public readonly DevCommands Dev;

		private readonly KeyEdge _keys = new KeyEdge();

		private int _levelId = -1;

		private bool _loading;

		private float _nextStateSend;

		private float _nextEquipCheck;

		private PlayerEquipMsg _lastEquip;

		private bool _equipSent;

		private float _lastErrorAt;

		private int _errorBurst;

		private RemotePlayer _fakeGhost;

		private Peer _fakePeer;

		private float _nextFakeSend;

		private readonly PlayerStateMsg _fakeState = new PlayerStateMsg();

		public bool MenuVisible;

		private bool _hostedLast;

		private int _frames;

		private readonly SessionPerformance _performance = new SessionPerformance();

		private int _hostAttempts;

		private float _nextHostAttempt;

		private bool _firstGui = true;

		private int _guiCalls;

		private const float IdleStateInterval = 0.1f;

		private float _lastStateSentAt = -10f;

		private float _sentX;

		private float _sentY;

		private float _sentZ;

		private float _sentYaw;

		private float _sentHp;

		private float _sentSync;

		private PlayerFlags _sentFlags;

		private int _sentLevel;

		private int _sentLayers;

		private readonly int[] _sentLayerHashes = new int[6];

		private byte _sentShield;

		private byte _sentEnchant;

		private readonly HashSet<byte> _apartPeers = new HashSet<byte>();

		private float _nextAutoContinue;

		private int _autoContinueAttempts;

		private bool _autoStarted;

		private float _autoStartAt = -1f;

		private float _autoRetryAt;

		private int _autoRetries;

		private bool _steamLaunchJoinChecked;

		private LobbyDetails _lobbyDetails;

		private float _nextLobbyDetails;

		private Action _frameAction;

		private float _frameActionUntil;

		private Action _delayedAction;

		private float _delayedAt;

		public static CoopRuntime Instance { get; private set; }

		public int LevelId => _levelId;

		public bool Loading => _loading;

		public string LastError { get; private set; } = "";

		public bool GameActive { get; private set; }

		public bool OverlayAvailable => OverlayHost.IsAlive;

		public bool FakeGhostActive => _fakeGhost != null;

		public static void Create()
		{
			Instance = new CoopRuntime();
			HitRelay.Runtime = Instance;
			PvpCombat.Attach(Instance);
		}

		private CoopRuntime()
		{
			Log.Trace("runtime ctor: begin");
			Session = new Session(new SteamBanList(Path.Combine(Paths.ConfigPath, "com.ailimit.coop.bans" + InstanceProfile.FileSuffix + ".json")));
			Session.Diagnostics.SummaryInterval = CoopConfig.NetworkDiagnosticsInterval.Value;
			Ghosts = new RemotePlayerManager(Session);
			Authority = new MonsterAuthority(Session);
			HealthScaling = new EnemyHealthScaling(Session, Authority);
			MonsterHost = new MonsterSyncHost(Session, Authority, HealthScaling);
			MonsterClient = new MonsterSyncClient(Session, Authority, HealthScaling, MonsterIndex);
			EnemyFx = new MonsterFxSync(this);
			PlayerFx = new PlayerFxSync(this);
			PlayerShots = new PlayerProjectileSync(this);
			PlayerWorldFx = new PlayerWorldFxSync(this);
			RogueLayout = new RogueLayoutSync(this);
			Session.SeparateBuild = delegate(int level, int build)
			{
				int currentLevelId = GameState.CurrentLevelId;
				return RogueLayoutSync.Separate(level, build, currentLevelId, RogueLayout.BuildOf(currentLevelId));
			};
			BossWake = new BossWakeAssist(this);
			RogueTrial = new RogueTrialSync(this);
			RogueStage = new RogueStageSync(this);
			RoomClear = new RoomClearSync(this);
			Summons = new SummonSync(this);
			Authority.PinToOwner = Summons.HelperOwnerOf;
			Guardians = new GuardianFightSync(this);
			WeakPoints = new WeakPointSync(this);
			Log.Trace("runtime ctor: sync objects");
			UI = new CoopUI(this);
			MenuFocus = new MenuInputFocus(this);
			Pad = new ControllerMenu(this);
			Rewards = new BossRewardSync(this);
			Progress = new BossProgressMirror(this);
			Life = new PartyLife(this);
			Threat = new MonsterThreat(this);
			Triggers = new TeammateTriggers(this);
			World = new SharedWorld(this);
			Encounters = new BossEncounterSync(this);
			Presentation = new BossPresentationSync(this);
			Spacing = new CutsceneSpacing(this);
			BossShows = new BossShowRelay(this);
			Pings = new PingMarkers(this);
			Abilities = new RogueAbilitySync(this);
			PhotoPoses = new PhotoPoseSync(this);
			Music = new BossMusicTracker(this);
			MonsterClient.ActivationTarget = Threat.RecoveryTarget;
			MonsterClient.JoinerOnlyActor = Encounters.JoinerOnlyActor;
			MonsterClient.JoinerOnlyGone = Encounters.JoinerStandInGone;
			Dev = new DevCommands(this);
			Log.Trace("runtime ctor: ui/dev");
			MenuVisible = CoopConfig.ShowMenuOnStart.Value;
			ConfigureNetworkConditions();
			Session.OnMonsterHit += HitRelay.ApplyMonsterHit;
			Session.OnGhostHit += HitRelay.ReceiveGhostHit;
			Session.OnGhostHitResult += HitRelay.ApplyGhostHitResult;
			Session.OnPeerJoined += delegate(Peer p)
			{
				_equipSent = false;
				UI.Notify(p.Name + " joined the party", $"{p} joined");
			};
			Session.OnPeerLeft += delegate(Peer p)
			{
				if (!Session.Ending)
				{
					UI.Notify(p.Name + " left the party", $"{p} left");
				}
			};
			Session.OnPeerLeft += delegate(Peer p)
			{
				HitRelay.ForgetPeer(p.Id);
			};
			Session.OnPeerLeft += delegate(Peer p)
			{
				_apartPeers.Remove(p.Id);
			};
			Session.OnChat += delegate(Peer p, string text)
			{
				UI.ReceiveChat(p, text);
			};
			Session.OnSessionStarted += delegate
			{
				_equipSent = false;
				HitRelay.ClientSideHitsObserved = false;
				_hostedLast = Session.IsHost;
				UI.Notify(Session.IsHost ? "You're hosting. Friends can join now." : "Joining the host...");
			};
			Session.LocalGameBuild = GameBuildId.Describe();
			Log.Info("[Coop] game build " + Session.LocalGameBuild);
			Session.OnGameBuildMismatch += delegate(string theirs, string ours)
			{
				UI.Notify("Players have different game versions; some effects may not show.", "[Coop] game build mismatch: theirs " + theirs + ", ours " + ours);
			};
			Session.OnSessionEnded += delegate(string reason)
			{
				HitRelay.ClearCaches();
				PvpArena.OnSessionEnded();
				_apartPeers.Clear();
				UI.ClearChat();
				string text = SessionText.EndedNotice(reason, _hostedLast);
				if (text != null)
				{
					UI.Notify(text, "[Session] ended: " + reason);
				}
			};
		}

		private void ConfigureNetworkConditions()
		{
			string environmentVariable = Environment.GetEnvironmentVariable("AILIMITCOOP_NETSIM");
			string[] parts;
			if (!string.IsNullOrWhiteSpace(environmentVariable) && CoopConfig.DevCommands.Value)
			{
				parts = environmentVariable.Split(',');
				Session.Conditioner.Configure(Part(0), Part(1), Part(2));
				Log.Warn("[Coop] developer network conditions active: " + Session.Conditioner.Diagnostics);
			}
			float Part(int i)
			{
				if (i >= parts.Length || !float.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					return 0f;
				}
				return result;
			}
		}

		private void EnsureHost(float now)
		{
			if (!OverlayHost.IsAlive && CoopConfig.EnableOverlay.Value && !(now < _nextHostAttempt) && _hostAttempts < 3)
			{
				_hostAttempts++;
				_nextHostAttempt = now + 5f;
				Log.Trace("host: creating");
				if (OverlayHost.TryCreate())
				{
					Log.Trace("host: ready");
				}
				else
				{
					Log.Trace("host: failed");
				}
			}
		}

		public void Update()
		{
			bool flag = _frames < 3;
			if (flag)
			{
				Log.Trace($"Update {_frames} begin");
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			_frames++;
			_performance.Begin(this, realtimeSinceStartup);
			try
			{
				if (_frames == 1)
				{
					Log.Info("[Coop] first Update");
				}
				AttackDefenseCapture.ResetScopes();
				if (_frames > 1)
				{
					EnsureHost(realtimeSinceStartup);
				}
				GhostRegistry.Prune(Time.frameCount, realtimeSinceStartup);
				if (flag)
				{
					Log.Trace("Update: keys");
				}
				if (KeyEdge.GameHasFocus())
				{
					HandleKeys();
				}
				if (KeyEdge.GameHasFocus() || ControllerMenu.Simulated.HasValue)
				{
					Pad.Tick(realtimeSinceStartup);
				}
				PhotoBridge.Tick();
				try
				{
					PhotoPoses.Tick(realtimeSinceStartup);
				}
				catch (Exception ex)
				{
					Log.Debug("[Photo] pose sync: " + ex.Message);
				}
				MenuFocus.Tick();
				SteamPresence.Tick(realtimeSinceStartup, MenuVisible);
				if (SteamLobby.IsBlocked == null)
				{
					SteamLobby.IsBlocked = Session.SteamBans.Contains;
				}
				if (Session.NeedsApproval == null)
				{
					Session.NeedsApproval = (ulong id) => CoopConfig.AskBeforeJoin.Value && ((id == 0L) ? SteamLobby.AskDirect : (!SteamPresence.IsFriend(id)));
					Session.OnJoinRequest += delegate
					{
						UI.Notify("Someone wants to join. Open the party menu (" + CoopUI.MenuOpenHint() + ") to answer.");
					};
				}
				SteamLobby.Tick(realtimeSinceStartup, Session, CoopConfig.PublicGame.Value, CoopConfig.Difficulty.Value.ToString(), LobbyDetailsNow(realtimeSinceStartup), JoinSteamFriend);
				if (flag)
				{
					Log.Trace("Update: dev poll");
				}
				Dev.Poll(realtimeSinceStartup);
				if (flag)
				{
					Log.Trace("Update: session poll");
				}
				if (GameActive)
				{
					TrackLevel();
				}
				_performance.Mark(CoopWork.Input);
				Session.Poll();
				Session.RefreshBuilds();
				WatchBuilds();
				_performance.Mark(CoopWork.Network);
				CoopMenuPause.Tick(this);
				Life.Tick(realtimeSinceStartup);
				ChestInteractionSafety.Tick(GameActive && !Loading && Session.IsConnected);
				HolidayItems.Tick(realtimeSinceStartup, this);
				AllySpells.Tick(realtimeSinceStartup, this);
				PvpArena.Tick(realtimeSinceStartup);
				_performance.Mark(CoopWork.Life);
				if (!GameActive)
				{
					_levelId = -1;
					_loading = true;
					AutoContinueTick(realtimeSinceStartup);
					SendState(realtimeSinceStartup);
					if (flag)
					{
						Log.Trace("Update end (inactive)");
					}
					return;
				}
				TrackLevel();
				AutoStart(realtimeSinceStartup);
				PumpFrameAction(realtimeSinceStartup);
				UpdateFakeGhost(realtimeSinceStartup);
				if (Session.IsActive || _fakeGhost != null)
				{
					Sampler.Bind(GameState.LocalPlayer);
					SendState(realtimeSinceStartup);
					_performance.Mark(CoopWork.LocalState);
					World.Tick(realtimeSinceStartup);
					Encounters.Tick(realtimeSinceStartup);
					BossWake.Tick(realtimeSinceStartup);
					Presentation.Tick(realtimeSinceStartup);
					Music?.Tick(realtimeSinceStartup);
					Spacing.Tick(realtimeSinceStartup);
					LiftCars.Tick(realtimeSinceStartup, _loading ? (-1) : _levelId);
					Ghosts.Update(realtimeSinceStartup, _levelId, _loading);
					_performance.Mark(CoopWork.Ghosts);
					MonsterHost.Tick(realtimeSinceStartup, _levelId, _loading);
					_performance.Mark(CoopWork.MonsterSend);
					MonsterClient.Update(realtimeSinceStartup, _levelId);
					Summons.Tick(realtimeSinceStartup);
					HelperRules.Refresh(realtimeSinceStartup);
					Guardians.Tick(realtimeSinceStartup);
					WeakPoints.Tick(realtimeSinceStartup);
					BossShows.Tick(realtimeSinceStartup);
					EnemyFx.Tick(realtimeSinceStartup);
					int frameCount = Time.frameCount;
					Defense.Record(frameCount, realtimeSinceStartup, MonsterClient, HitRelay.PendingAttackers, PvpCombat.Duelists(Ghosts));
					HitRelay.TickTimeline(frameCount, realtimeSinceStartup);
					PvpCombat.Tick(realtimeSinceStartup);
					_performance.Mark(CoopWork.MonsterReceive);
					Threat.Tick(realtimeSinceStartup);
					Triggers.Tick(realtimeSinceStartup);
					_performance.Mark(CoopWork.Threat);
					Rewards.Tick();
					Progress.Tick();
					_performance.Mark(CoopWork.Rewards);
					PlayerFx.Tick();
					PlayerShots.Tick(realtimeSinceStartup);
					PlayerWorldFx.Tick(realtimeSinceStartup);
					_performance.Mark(CoopWork.PlayerFx);
					RoomClear.Tick(Time.realtimeSinceStartup);
					RogueLayout.Tick(Time.realtimeSinceStartup);
					RogueStage.Tick(Time.realtimeSinceStartup);
					_performance.Mark(CoopWork.Rogue);
				}
			}
			catch (Exception ex2)
			{
				ReleaseMenuOnError();
				ReportError("Update", ex2);
			}
			finally
			{
				_performance.End(this, realtimeSinceStartup);
			}
		}

		public void OnGUI()
		{
			if (!CoopConfig.EnableOverlay.Value)
			{
				return;
			}
			bool flag = _guiCalls < 3;
			_guiCalls++;
			if (flag)
			{
				Log.Trace($"OnGUI {_guiCalls} begin");
			}
			long stamp = _performance.BeginMenu();
			try
			{
				if (_firstGui)
				{
					_firstGui = false;
					Log.Info("[Coop] first OnGUI");
				}
				bool menuWasVisible = MenuVisible || UI.ChatOpen;
				UI.Draw(flag);
				MenuFocus.AfterGui(menuWasVisible);
			}
			catch (Exception ex)
			{
				ReleaseMenuOnError();
				ReportError("OnGUI", ex);
			}
			finally
			{
				_performance.EndMenu(stamp);
			}
			if (flag)
			{
				Log.Trace($"OnGUI {_guiCalls} end");
			}
		}

		private void ReportError(string where, Exception ex)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			LastError = $"{where}: {ex.GetType().Name}: {ex.Message}";
			if (realtimeSinceStartup - _lastErrorAt > 5f)
			{
				_errorBurst = 0;
			}
			_lastErrorAt = realtimeSinceStartup;
			if (++_errorBurst <= 3)
			{
				Log.Error("[Coop] " + where, ex);
			}
		}

		private void HandleKeys()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			HandleMenuKey();
			HandleChatKey();
			if (!UI.ChatOpen)
			{
				TrySteamLaunchJoin();
				if (_keys.Pressed(CoopConfig.HostKey.Value))
				{
					HostSession();
				}
				if (_keys.Pressed(CoopConfig.JoinKey.Value))
				{
					JoinSession(CoopConfig.JoinAddress.Value);
				}
				if (_keys.Pressed(CoopConfig.LeaveKey.Value))
				{
					LeaveSession();
				}
				if (_keys.Pressed(CoopConfig.PingKey.Value) && !MenuVisible && !PhotoBridge.Active)
				{
					Pings.Pressed();
				}
				if (Life.IsSpectating && _keys.Pressed((KeyCode)290))
				{
					Life.CycleTarget();
				}
			}
		}

		private void HandleMenuKey()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (_keys.Pressed(CoopConfig.ToggleMenuKey.Value) && !UI.ChatOpen)
			{
				if (PhotoBridge.Active)
				{
					PhotoBridge.Exit("menu key");
				}
				else
				{
					MenuVisible = !MenuVisible;
				}
			}
		}

		private void HandleChatKey()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			KeyCode value = CoopConfig.ChatKey.Value;
			bool num = _keys.Pressed(value);
			UI.TickChat(_keys.Held(value));
			if (num && !UI.ChatOpen && !MenuVisible && !PhotoBridge.Active)
			{
				UI.OpenChat();
			}
		}

		public void BeforeInputUpdate()
		{
			try
			{
				if (KeyEdge.GameHasFocus())
				{
					HandleMenuKey();
					HandleChatKey();
				}
				MenuFocus.Tick();
			}
			catch (Exception ex)
			{
				ReleaseMenuOnError();
				ReportError("Menu input", ex);
			}
		}

		private void ReleaseMenuOnError()
		{
			MenuVisible = false;
			try
			{
				UI.CloseChat(clearDraft: false);
			}
			catch
			{
			}
			try
			{
				MenuFocus.Release();
			}
			catch (Exception ex)
			{
				Log.Warn("[Menu input] restore: " + ex.Message);
			}
		}

		private void TrackLevel()
		{
			int currentLevelId = GameState.CurrentLevelId;
			bool isLoadingLevel = GameState.IsLoadingLevel;
			if (currentLevelId != _levelId)
			{
				Log.Info($"[Game] level changed {_levelId} -> {currentLevelId} ({GameState.CurrentSceneName})");
				HealthScaling.RestoreAll();
				_levelId = currentLevelId;
				MonsterClient.OnLevelChanged(currentLevelId);
				RogueLayout.LevelChanged(currentLevelId);
				RogueTrial.LevelChanged(currentLevelId);
				RogueStage.LevelChanged(currentLevelId);
				RoomClear.LevelChanged(currentLevelId);
				Summons.LevelChanged(currentLevelId);
				Guardians.LevelChanged(currentLevelId);
				WeakPoints.LevelChanged(currentLevelId);
				Pings.Clear();
				Authority.OnLevelChanged();
				MonsterHost.OnLevelChanged();
				MonsterIndex.Invalidate();
				HitRelay.ClearCaches();
			}
			if (isLoadingLevel != _loading)
			{
				_loading = isLoadingLevel;
				Log.Debug($"[Game] loading = {isLoadingLevel}");
			}
		}

		private bool StateIdle(PlayerStateMsg m)
		{
			if (m.LevelId != _sentLevel || m.Flags != _sentFlags || m.ShieldStage != _sentShield || m.Enchant != _sentEnchant)
			{
				return false;
			}
			if (Math.Abs(m.X - _sentX) > 0.01f || Math.Abs(m.Y - _sentY) > 0.01f || Math.Abs(m.Z - _sentZ) > 0.01f)
			{
				return false;
			}
			if (Math.Abs(Mathf.DeltaAngle(m.Yaw, _sentYaw)) > 0.5f || m.Hp != _sentHp || Math.Abs(m.Sync - _sentSync) > 0.05f)
			{
				return false;
			}
			if (m.LayerCount != _sentLayers)
			{
				return false;
			}
			for (int i = 0; i < m.LayerCount && i < _sentLayerHashes.Length; i++)
			{
				if (m.Layers[i].Hash != _sentLayerHashes[i])
				{
					return false;
				}
			}
			for (int j = 0; j < m.ParamCount; j++)
			{
				if (Math.Abs(m.Params[j].Value) > 0.01f && IsMovementParam(j))
				{
					return false;
				}
			}
			return true;
		}

		private static bool IsMovementParam(int index)
		{
			return index < 3;
		}

		private void RememberSent(PlayerStateMsg m)
		{
			_sentLevel = m.LevelId;
			_sentFlags = m.Flags;
			_sentShield = m.ShieldStage;
			_sentEnchant = m.Enchant;
			_sentX = m.X;
			_sentY = m.Y;
			_sentZ = m.Z;
			_sentYaw = m.Yaw;
			_sentHp = m.Hp;
			_sentSync = m.Sync;
			_sentLayers = m.LayerCount;
			for (int i = 0; i < m.LayerCount && i < _sentLayerHashes.Length; i++)
			{
				_sentLayerHashes[i] = m.Layers[i].Hash;
			}
		}

		private void SendState(float now)
		{
			if (!Session.IsConnected)
			{
				return;
			}
			if (now >= _nextStateSend)
			{
				_nextStateSend = now + 1f / UnityMath.Max(1f, CoopConfig.PlayerSendRate.Value);
				PlayerFlags playerFlags = PlayerFlags.None;
				if (_loading || (Object)(object)Sampler.Player == (Object)null)
				{
					playerFlags |= PlayerFlags.Loading;
				}
				if (HitRelay.ClientSideHitsObserved)
				{
					playerFlags |= PlayerFlags.ClientSideHits;
				}
				if (Life.IsSpectating)
				{
					playerFlags |= PlayerFlags.Dead | PlayerFlags.Spectating;
				}
				if (Session.LocalPvp && Session.PvpAllowed)
				{
					playerFlags |= PlayerFlags.PvpOptIn;
				}
				PlayerStateMsg playerStateMsg = Sampler.Sample(_levelId, playerFlags);
				playerStateMsg.Layout = RogueLayout.BuildOf(_levelId);
				if (StateIdle(playerStateMsg) && now - _lastStateSentAt < 0.1f)
				{
					return;
				}
				_lastStateSentAt = now;
				RememberSent(playerStateMsg);
				Session.SendPlayerState(playerStateMsg);
			}
			if (now >= _nextEquipCheck && (Object)(object)Sampler.Player != (Object)null)
			{
				_nextEquipCheck = now + 1f;
				PlayerEquipMsg playerEquipMsg = Sampler.SampleEquip(CoopConfig.EffectivePlayerName);
				playerEquipMsg.Color = PlayerColors.LocalChoice;
				playerEquipMsg.Emblem = PlayerEmblems.LocalChoice;
				if (!_equipSent || !playerEquipMsg.SameAs(in _lastEquip))
				{
					Session.SendPlayerEquip(playerEquipMsg);
					_lastEquip = playerEquipMsg;
					_equipSent = true;
					Log.Debug($"[Coop] sent equipment: weapon {playerEquipMsg.WeaponDefineId} reserve {playerEquipMsg.ReserveWeaponDefineId} head {playerEquipMsg.HeadId} body {playerEquipMsg.BodyId} acc {playerEquipMsg.AccessoriesId}");
				}
			}
		}

		private void WatchBuilds()
		{
			if (_apartPeers.Count == 0 && GameState.CurrentLevelId <= 0)
			{
				return;
			}
			IReadOnlyList<Peer> peers = Session.Peers;
			for (int i = 0; i < peers.Count; i++)
			{
				Peer peer = peers[i];
				bool flag = Session.IsApart(peer);
				if (flag == _apartPeers.Contains(peer.Id))
				{
					continue;
				}
				if (!flag)
				{
					_apartPeers.Remove(peer.Id);
					Log.Info($"[Rogue] {peer} is no longer in a different build of this game's stage");
					continue;
				}
				_apartPeers.Add(peer.Id);
				int reportedLevelId = peer.LastState.ReportedLevelId;
				Log.Warn($"[Rogue] {peer} is in level {reportedLevelId} too, but their game built it differently (build {peer.LastState.Layout}, this game's {RogueLayout.BuildOf(reportedLevelId)}): enemies, rooms and revives are not shared with them in this stage");
				if (peer.Id == 0)
				{
					UI.Notify("Rooms differ from the host's: you each play this stage alone.");
					continue;
				}
				UI.Notify(peer.Name + "'s rooms here differ from yours, so you each play this stage alone.", $"{peer}'s rooms differ from this game's; each plays this stage alone");
			}
		}

		private void AutoContinueTick(float now)
		{
			if (InstanceProfile.AutoContinue && !GameActive && !(now < _nextAutoContinue))
			{
				_nextAutoContinue = now + 2f;
				if (_autoContinueAttempts < 300)
				{
					_autoContinueAttempts++;
					PressThroughTitle(_autoContinueAttempts <= 3 || _autoContinueAttempts % 15 == 0);
				}
			}
		}

		public bool PressThroughTitle(bool log)
		{
			try
			{
				TitleView val = Il2CppUtil.FindObjectOfType<TitleView>();
				if ((Object)(object)val == (Object)null)
				{
					if (log)
					{
						Log.Debug("[Auto] title screen not ready yet");
					}
					return false;
				}
				try
				{
					InputManager instance = InputManager.Instance;
					if (instance != null)
					{
						instance.UISubmitInput((CallbackContext)null);
					}
				}
				catch (Exception ex)
				{
					if (log)
					{
						Log.Debug("[Auto] UISubmitInput: " + ex.Message);
					}
				}
				try
				{
					val.InvokeButton();
				}
				catch (Exception ex2)
				{
					if (log)
					{
						Log.Debug("[Auto] InvokeButton: " + ex2.Message);
					}
				}
				try
				{
					val.Continue();
				}
				catch (Exception ex3)
				{
					if (log)
					{
						Log.Debug("[Auto] Continue: " + ex3.Message);
					}
				}
				if (log)
				{
					Log.Info($"[Auto] title press + Continue() (attempt {_autoContinueAttempts})");
				}
				return true;
			}
			catch (Exception ex4)
			{
				if (log)
				{
					Log.Debug("[Auto] continue failed: " + ex4.Message);
				}
				return false;
			}
		}

		private void AutoStart(float now)
		{
			bool autoHost = InstanceProfile.AutoHost;
			bool flag = !string.IsNullOrEmpty(InstanceProfile.AutoJoin);
			if (_autoStarted)
			{
				if (flag && !Session.IsActive && Session.AllowAutoJoinRetry && _autoRetries < 30 && now >= _autoRetryAt)
				{
					_autoRetryAt = now + 5f;
					_autoRetries++;
					Log.Msg($"[Auto] retrying join {InstanceProfile.AutoJoin} ({_autoRetries})");
					JoinSession(InstanceProfile.AutoJoin);
				}
			}
			else if (!autoHost && !flag)
			{
				_autoStarted = true;
			}
			else if (_loading || _levelId < 0 || (Object)(object)GameState.LocalPlayer == (Object)null)
			{
				_autoStartAt = -1f;
			}
			else if (_autoStartAt < 0f)
			{
				_autoStartAt = now + 3f;
			}
			else if (!(now < _autoStartAt))
			{
				_autoStarted = true;
				if (autoHost)
				{
					Log.Msg("[Auto] hosting");
					HostSession();
				}
				else
				{
					Log.Msg("[Auto] joining " + InstanceProfile.AutoJoin);
					JoinSession(InstanceProfile.AutoJoin);
				}
			}
		}

		private void TrySteamLaunchJoin()
		{
			if (!_steamLaunchJoinChecked && !Session.IsActive && _levelId >= 0 && !_loading && !((Object)(object)GameState.LocalPlayer == (Object)null))
			{
				_steamLaunchJoinChecked = true;
				ulong num = SteamPresence.PendingLaunchJoin();
				if (num != 0L && num != SteamPresence.LocalSteamId)
				{
					Log.Msg($"[Steam] joining {num}, who invited us before the game started");
					UI.Notify("Joining your friend's session...");
					JoinFriend(num);
				}
			}
		}

		private INetTransport CreateTransport()
		{
			if (CoopConfig.Transport.Value == TransportKind.Steam)
			{
				if (SteamP2PTransport.IsAvailable)
				{
					return new SteamP2PTransport();
				}
				Log.Warn("[Coop] Steam is not initialised; falling back to UDP.");
				UI.Notify("Steam isn't running, so this uses a direct connection.");
			}
			return new UdpTransport();
		}

		public void HostSession()
		{
			LogPrivacy.RegisterName(SteamPresence.LocalName);
			Session.LocalName = CoopConfig.EffectivePlayerName;
			Session.LocalSteamId = SteamP2PTransport.LocalSteamIdOrZero;
			Session.MaxPlayers = CoopConfig.MaxPlayers.Value;
			DifficultySettings effectiveDifficulty = CoopConfig.EffectiveDifficulty;
			Session.ConfiguredEnemyHpPerExtraPlayer = effectiveDifficulty.EnemyHp;
			Session.ConfiguredBossHpPerExtraPlayer = effectiveDifficulty.BossHp;
			Session.ConfiguredBreakResistPerExtraPlayer = effectiveDifficulty.BreakResist;
			Session.ConfiguredAllowPvp = CoopConfig.AllowPvp.Value;
			Session.ConfiguredSyncWeakPoints = CoopConfig.SyncWeakPoints.Value;
			Session.ConfiguredPvpDamage = PvpRules.DamageFor(CoopConfig.PvpDamage.Value);
			Log.Info($"[Difficulty] hosting on {CoopConfig.Difficulty.Value}: {effectiveDifficulty}; PvP " + (CoopConfig.AllowPvp.Value ? $"allowed (opt-in), damage {CoopConfig.PvpDamage.Value}: {Session.ConfiguredPvpDamage}" : "disabled"));
			INetTransport netTransport = CreateTransport();
			if (!Session.Host(netTransport, CoopConfig.EffectivePort))
			{
				UI.Notify(Session.StatusText);
				netTransport.Dispose();
			}
			else if (CoopConfig.Transport.Value == TransportKind.Steam)
			{
				SteamPresence.Advertise();
			}
		}

		public void JoinFriend(ulong hostSteamId)
		{
			if (hostSteamId != 0L && !SteamLobby.JoinFriend(hostSteamId, Time.realtimeSinceStartup))
			{
				JoinSteamFriend(hostSteamId);
			}
		}

		public void JoinSteamFriend(ulong hostSteamId)
		{
			if (hostSteamId != 0L)
			{
				if (CoopConfig.Transport.Value != TransportKind.Steam)
				{
					CoopConfig.Transport.Value = TransportKind.Steam;
					Log.Info("[Coop] switched to the Steam transport to join a friend");
				}
				JoinSession(hostSteamId.ToString());
			}
		}

		public void InviteOverSteam()
		{
			if (!Session.IsHost)
			{
				UI.Notify("Host a session to invite friends.");
				return;
			}
			if (!SteamPresence.IsAvailable)
			{
				UI.Notify("Steam isn't running.");
				return;
			}
			if (Session.Locked)
			{
				UI.Notify("Unlock the game under PLAYERS to invite friends.");
				return;
			}
			SteamPresence.Advertise();
			if (!SteamPresence.OpenInviteOverlay())
			{
				UI.Notify("Couldn't open the Steam overlay. Check that it's turned on in Steam.");
			}
		}

		public void JoinSession(string address)
		{
			LogPrivacy.RegisterName(SteamPresence.LocalName);
			Session.LocalName = CoopConfig.EffectivePlayerName;
			Session.LocalSteamId = SteamP2PTransport.LocalSteamIdOrZero;
			INetTransport netTransport = CreateTransport();
			if (!Session.Join(netTransport, address, CoopConfig.EffectivePort))
			{
				UI.Notify(Session.StatusText);
				netTransport.Dispose();
			}
		}

		private LobbyDetails LobbyDetailsNow(float now)
		{
			if (!Session.IsHost || now < _nextLobbyDetails)
			{
				return _lobbyDetails;
			}
			_nextLobbyDetails = now + 2f;
			try
			{
				object obj;
				if (!GameActive || GameState.IsLoadingLevel)
				{
					obj = null;
				}
				else
				{
					PlayerSys instance = PlayerSys.Instance;
					obj = ((instance != null) ? instance.Archive : null);
				}
				ArchiveData val = (ArchiveData)obj;
				if (val != null)
				{
					_lobbyDetails = new LobbyDetails
					{
						Area = _levelId,
						NewGame = val._NewGameCount,
						Level = val._Level
					};
				}
			}
			catch
			{
			}
			return _lobbyDetails;
		}

		public void SetLocked(bool locked)
		{
			if (!Session.IsHost || Session.Locked == locked)
			{
				return;
			}
			Session.Locked = locked;
			if (Session.Transport is SteamP2PTransport)
			{
				if (locked)
				{
					SteamPresence.StopAdvertising();
				}
				else
				{
					SteamPresence.Advertise();
				}
			}
			Log.Info("[Session] the host " + (locked ? "locked" : "unlocked") + " the game");
		}

		public void LeaveSession()
		{
			SteamPresence.StopAdvertising();
			_autoStarted = true;
			_autoRetries = int.MaxValue;
			if (Session.IsActive)
			{
				Session.Leave();
			}
			else
			{
				UI.Notify("You're not in a session.");
			}
		}

		public void BeforeMonsterReset()
		{
			Encounters?.OnReset(GameState.CurrentLevelId);
			Summons?.OnReset();
			Presentation?.OnSceneReset();
			Threat.Clear();
			MonsterClient.ReleaseAll();
			HealthScaling.RestoreAll();
			MonsterIndex.Invalidate();
			HitRelay.ClearCaches();
			MonsterHost.OnLevelChanged();
		}

		public void OnRemoteRest(int levelId)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (!Session.IsHost || !Session.IsConnected)
			{
				return;
			}
			if (GameState.CurrentLevelId == levelId && GameActive && !Loading)
			{
				LevelRoot currentLevelRoot = GameState.CurrentLevelRoot;
				if (currentLevelRoot != null)
				{
					currentLevelRoot.ResetMonster();
				}
				OnLocalSceneReset(isDead: false);
			}
			else
			{
				Session.SendSceneReset(new SceneResetMsg
				{
					LevelId = levelId,
					IsDead = false
				});
			}
		}

		public void OnLocalSceneReset(bool isDead)
		{
			Threat.Clear();
			MonsterIndex.Invalidate();
			HitRelay.ClearCaches();
			MonsterHost.OnLevelChanged();
			if (Session.IsHost && Session.IsConnected)
			{
				MonsterClient.ReleaseAll();
				Authority.Clear();
				Log.Msg("[Game] telling clients to reset their monsters (host " + (isDead ? "died" : "rested") + ")");
				Session.SendSceneReset(new SceneResetMsg
				{
					LevelId = _levelId,
					IsDead = isDead
				});
			}
		}

		public void OnGameLoadNewScene()
		{
			World.Clear();
			HealthScaling.RestoreAll();
			Log.Info("[Game] ProcedureManager.OnLoadNewScene");
			GameState.InvalidateFrameCache();
			MonsterIndex.Invalidate();
			HitRelay.ClearCaches();
		}

		public void OnGameStart()
		{
			Log.Info("[Game] ProcedureManager.StartGameInitAllLogic -> game active");
			GameState.InvalidateFrameCache();
			try
			{
				AnimSync.PlayerParamHashes();
			}
			catch
			{
			}
			GameActive = true;
			_levelId = -1;
		}

		public void OnGameClose()
		{
			World.Clear();
			HealthScaling.RestoreAll();
			Log.Info("[Game] ProcedureManager.CloseAllLogic -> game inactive");
			GameState.InvalidateFrameCache();
			GameActive = false;
			Life.OnGameClose();
			Threat.Clear();
			Rewards.OnGameClose();
			Progress.Clear();
			PlayerFx.Clear();
			PlayerShots.Clear();
			PlayerWorldFx.Clear();
			BossWake.Clear();
			RogueTrial.Clear();
			RoomClear.Clear();
			Summons.Clear();
			Guardians.Clear();
			WeakPoints.Clear();
			RogueLayout.OnGameClose();
			Encounters.OnGameClose();
			Presentation.OnGameClose();
			_levelId = -1;
			_loading = true;
			MonsterIndex.Invalidate();
			HitRelay.ClearCaches();
			MonsterHost.OnLevelChanged();
			MonsterClient.ReleaseAll();
			Authority.Clear();
			Ghosts.DespawnAll();
			Sampler.Bind(null);
			if (_fakeGhost != null)
			{
				ToggleFakeGhost();
			}
		}

		public void RunEachFrame(float seconds, Action action)
		{
			_frameAction = action;
			_frameActionUntil = Time.realtimeSinceStartup + seconds;
		}

		public void RunAfter(float seconds, Action action)
		{
			_delayedAction = action;
			_delayedAt = Time.realtimeSinceStartup + seconds;
		}

		private void PumpFrameAction(float now)
		{
			if (_delayedAction != null && now >= _delayedAt)
			{
				Action delayedAction = _delayedAction;
				_delayedAction = null;
				try
				{
					delayedAction();
				}
				catch (Exception ex)
				{
					Log.Warn("[Dev] delayed action: " + ex.Message);
				}
			}
			if (_frameAction == null)
			{
				return;
			}
			if (now > _frameActionUntil)
			{
				_frameAction = null;
				return;
			}
			try
			{
				_frameAction();
			}
			catch (Exception ex2)
			{
				Log.Warn("[Dev] frame action: " + ex2.Message);
				_frameAction = null;
			}
		}

		public void ToggleFakeGhost()
		{
			if (_fakeGhost != null)
			{
				try
				{
					_fakeGhost.Despawn();
				}
				catch (Exception ex)
				{
					Log.Error("[Fake] despawn", ex);
				}
				_fakeGhost = null;
				_fakePeer = null;
				Log.Msg("[Fake] fake ghost removed");
			}
			else
			{
				_fakePeer = new Peer
				{
					Id = 250,
					Name = "FakeGhost",
					HandshakeDone = true
				};
				_fakeGhost = new RemotePlayer(_fakePeer);
				Log.Msg("[Fake] fake ghost enabled (mirrors the local player 2m to the side)");
			}
		}

		private void UpdateFakeGhost(float now)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			if (_fakeGhost == null)
			{
				return;
			}
			Player localPlayer = GameState.LocalPlayer;
			Sampler.Bind(localPlayer);
			if ((Object)(object)localPlayer != (Object)null && now >= _nextFakeSend)
			{
				_nextFakeSend = now + 0.05f;
				PlayerStateMsg o = Sampler.Sample(_levelId, PlayerFlags.None);
				_fakeState.CopyFrom(o);
				Transform val = GameState.SafeRoot(localPlayer);
				Vector3 val2 = (((Object)(object)val != (Object)null) ? val.right : Vector3.right);
				_fakeState.X += val2.x * 2f;
				_fakeState.Z += val2.z * 2f;
				_fakeState.PeerId = 250;
				_fakeGhost.OnState(_fakeState, now);
				if (!_fakeGhost.IsSpawned && (Object)(object)Sampler.Player != (Object)null)
				{
					_fakeGhost.OnEquip(Sampler.SampleEquip("FakeGhost"));
				}
			}
			_fakeGhost.Update(now, _levelId, _loading, Ghosts.HolderTransform);
		}
	}
	public sealed class MonsterIndex
	{
		private readonly Dictionary<int, Monster> _map = new Dictionary<int, Monster>();

		private float _builtAt = float.NegativeInfinity;

		private int _levelId = -1;

		private IntPtr _root;

		private const float RefreshSeconds = 2f;

		private const float MissingRetrySeconds = 0.5f;

		public int Count => _map.Count;

		public long RebuildCount { get; private set; }

		public long MissCount { get; private set; }

		public void Invalidate()
		{
			_map.Clear();
			_builtAt = float.NegativeInfinity;
		}

		public Monster Find(int instanceId)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			int currentLevelId = GameState.CurrentLevelId;
			LevelRoot currentLevelRoot = GameState.CurrentLevelRoot;
			IntPtr intPtr = ((currentLevelRoot != null) ? ((Il2CppObjectBase)currentLevelRoot).Pointer : IntPtr.Zero);
			if (currentLevelId != _levelId || intPtr != _root)
			{
				Invalidate();
				_levelId = currentLevelId;
				_root = intPtr;
			}
			Monster value;
			bool flag = _map.TryGetValue(instanceId, out value) && Il2CppUtil.Alive((Object)(object)value);
			float num = realtimeSinceStartup - _builtAt;
			if (num < 0f || num >= (flag ? 2f : 0.5f))
			{
				_builtAt = realtimeSinceStartup;
				RebuildCount++;
				_map.Clear();
				foreach (Monster item in GameState.CollectMonsters(currentLevelRoot))
				{
					if (Il2CppUtil.Alive((Object)(object)item))
					{
						int num2 = GameState.MonsterInstanceId(item);
						if (num2 >= 0)
						{
							_map[num2] = item;
						}
					}
				}
				flag = _map.TryGetValue(instanceId, out value) && Il2CppUtil.Alive((Object)(object)value);
			}
			if (!flag)
			{
				MissCount++;
			}
			if (!flag)
			{
				return null;
			}
			return value;
		}
	}
	public static class InstanceProfile
	{
		public static string Name = "";

		public static string PlayerName;

		public static bool ReadOnlySaves;

		public static int Port = -1;

		public static bool AutoContinue;

		public static bool AutoHost;

		public static string AutoJoin;

		public static string FileSuffix
		{
			get
			{
				if (!string.IsNullOrEmpty(Name))
				{
					return "." + Name;
				}
				return "";
			}
		}

		public static bool IsSecondary => !string.IsNullOrEmpty(Name);

		public static void Init()
		{
			Name = Clean(Get("AILIMITCOOP_PROFILE"));
			PlayerName = Get("AILIMITCOOP_NAME");
			ReadOnlySaves = Flag("AILIMITCOOP_READONLY_SAVE");
			AutoContinue = Flag("AILIMITCOOP_AUTOCONTINUE");
			AutoHost = Flag("AILIMITCOOP_AUTOHOST");
			AutoJoin = Get("AILIMITCOOP_AUTOJOIN");
			string text = Get("AILIMITCOOP_PORT");
			if (!string.IsNullOrEmpty(text) && int.TryParse(text, out var result))
			{
				Port = result;
			}
		}

		public static string Describe()
		{
			if (IsSecondary || ReadOnlySaves || AutoContinue || AutoHost || !string.IsNullOrEmpty(AutoJoin))
			{
				return $"profile='{Name}' name='{PlayerName}' readOnlySaves={ReadOnlySaves} autoContinue={AutoContinue} autoHost={AutoHost} autoJoin='{AutoJoin}' port={((Port > 0) ? Port.ToString() : "config")}";
			}
			return "";
		}

		private static string Get(string key)
		{
			try
			{
				return Environment.GetEnvironmentVariable(key)?.Trim();
			}
			catch
			{
				return null;
			}
		}

		private static bool Flag(string key)
		{
			string text = Get(key);
			if (!string.IsNullOrEmpty(text) && text != "0")
			{
				return !text.Equals("false", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private static string Clean(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			char[] array = s.ToCharArray();
			for (int i = 0; i < array.Length; i++)
			{
				if (!char.IsLetterOrDigit(array[i]) && array[i] != '_' && array[i] != '-')
				{
					array[i] = '_';
				}
			}
			return new string(array);
		}
	}
	[BepInPlugin("com.ailimit.coop", "AI LIMIT Co-op", "0.4.3")]
	public class Plugin : BasePlugin
	{
		public const string Guid = "com.ailimit.coop";

		public const string Name = "AI LIMIT Co-op";

		public const string Version = "0.4.3";

		public const string DisplayVersion = "0.4.3 (protocol 46)";

		private static WillRenderCanvases _frameAction;

		private static Action _beforeInput;

		public override void Load()
		{
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			InstanceProfile.Init();
			Log.Init(((BasePlugin)this).Log, Path.Combine(Paths.BepInExRootPath, "coop_trace" + InstanceProfile.FileSuffix + ".txt"));
			ManagedExceptionCounter.Install();
			((BasePlugin)this).Config.SaveOnConfigSet = false;
			CoopConfig.Bind(((BasePlugin)this).Config);
			((BasePlugin)this).Config.SaveOnConfigSet = !InstanceProfile.IsSecondary;
			if (((BasePlugin)this).Config.SaveOnConfigSet)
			{
				try
				{
					((BasePlugin)this).Config.Save();
				}
				catch (IOException ex)
				{
					Log.Warn("Config is busy; using loaded settings: " + ex.Message);
				}
			}
			Log.Verbose = CoopConfig.Verbose.Value;
			CoopConfig.Verbose.SettingChanged += delegate
			{
				Log.Verbose = CoopConfig.Verbose.Value;
			};
			Log.Msg($"{"AI LIMIT Co-op"} {"0.4.3 (protocol 46)"} loading (transport {CoopConfig.Transport.Value}, port {CoopConfig.EffectivePort})");
			Log.Info($"[Net] Protocol {46}, monster message budget {1100} bytes; send acceptance is local only.");
			Log.Info("[Party life] Death spectating enabled; rest or boss rewards revive, party wipe resumes native respawn.");
			Log.Info("[MonsterSync] Proximity simulation ownership with combat locks and independent multiplayer threat.");
			string text = InstanceProfile.Describe();
			if (text.Length > 0)
			{
				Log.Msg("Instance profile: " + text);
			}
			Log.Trace("config bound");
			if (CoopConfig.ForceRunInBackground.Value || InstanceProfile.IsSecondary)
			{
				try
				{
					Application.runInBackground = true;
					Log.Trace("runInBackground forced");
				}
				catch (Exception ex2)
				{
					Log.Warn("Could not set runInBackground: " + ex2.Message);
				}
			}
			CoopRuntime.Create();
			Log.Trace("runtime created");
			try
			{
				Hooks.Apply();
				Log.Trace("hooks applied");
			}
			catch (Exception ex3)
			{
				Log.Error("Failed to apply Harmony patches", ex3);
			}
			RegisterFrameDriver();
			RegisterEarlyInput();
			Log.Msg($"{"AI LIMIT Co-op"} loaded. Keys: {CoopConfig.ToggleMenuKey.Value} menu, {CoopConfig.HostKey.Value} host, {CoopConfig.JoinKey.Value} join, {CoopConfig.LeaveKey.Value} leave.");
		}

		private static void RegisterEarlyInput()
		{
			try
			{
				_beforeInput = DelegateSupport.ConvertDelegate<Action>((Delegate)(Action)delegate
				{
					CoopRuntime.Instance?.BeforeInputUpdate();
				});
				InputSystem.onBeforeUpdate += _beforeInput;
				MenuInputFocus.EarlyInputRegistered = true;
				Log.Info("[Menu input] " + MenuInputFocus.Readiness);
			}
			catch (Exception ex)
			{
				Log.Error("Could not register menu input capture", ex);
			}
		}

		private static void RegisterFrameDriver()
		{
			try
			{
				_frameAction = DelegateSupport.ConvertDelegate<WillRenderCanvases>((Delegate)new Action(Hooks.FrameHooks.Tick));
				Canvas.willRenderCanvases += _frameAction;
				Log.Trace("frame driver registered (Canvas.willRenderCanvases)");
			}
			catch (Exception ex)
			{
				Log.Error("Failed to register the per-frame callback; the mod cannot run", ex);
			}
		}
	}
}
namespace AILimitCoop.Util
{
	internal enum CoopWork
	{
		Input,
		Network,
		Life,
		LocalState,
		Ghosts,
		MonsterSend,
		MonsterReceive,
		Threat,
		Rewards,
		PlayerFx,
		Rogue,
		Other,
		Menu,
		FrameGap,
		Count
	}
	internal sealed class FrameTimingWindow
	{
		private readonly double[] _sum = new double[14];

		private readonly double[] _max = new double[14];

		private readonly int[] _count = new int[14];

		public int Count(CoopWork stage)
		{
			return _count[(int)stage];
		}

		public double Mean(CoopWork stage)
		{
			if (Count(stage) != 0)
			{
				return _sum[(int)stage] / (double)Count(stage);
			}
			return 0.0;
		}

		public double Max(CoopWork stage)
		{
			return _max[(int)stage];
		}

		public void Record(CoopWork stage, double milliseconds)
		{
			if (double.IsFinite(milliseconds) && !(milliseconds < 0.0) && stage >= CoopWork.Input && stage < CoopWork.Count)
			{
				_count[(int)stage]++;
				_sum[(int)stage] += milliseconds;
				_max[(int)stage] = Math.Max(_max[(int)stage], milliseconds);
			}
		}

		public void Clear()
		{
			Array.Clear(_sum, 0, _sum.Length);
			Array.Clear(_max, 0, _max.Length);
			Array.Clear(_count, 0, _count.Length);
		}

		public string Describe()
		{
			StringBuilder stringBuilder = new StringBuilder("stage ms mean/max (calls):");
			for (int i = 0; i < _count.Length; i++)
			{
				if (_count[i] != 0)
				{
					stringBuilder.Append(' ').Append((CoopWork)i).Append('=')
						.Append(Mean((CoopWork)i).ToString("F2", CultureInfo.InvariantCulture))
						.Append('/')
						.Append(_max[i].ToString("F2", CultureInfo.InvariantCulture))
						.Append('(')
						.Append(_count[i])
						.Append(')');
				}
			}
			return stringBuilder.ToString();
		}
	}
	public static class GameBuildId
	{
		private static string _cached;

		public static string Describe()
		{
			if (_cached != null)
			{
				return _cached;
			}
			string text = "?";
			try
			{
				text = Application.version;
			}
			catch
			{
			}
			string text2 = "?";
			try
			{
				FileInfo fileInfo = new FileInfo(Path.Combine(Paths.GameRootPath, "GameAssembly.dll"));
				if (fileInfo.Exists)
				{
					text2 = fileInfo.Length.ToString();
				}
			}
			catch
			{
			}
			_cached = text + "/" + text2;
			return _cached;
		}
	}
	public sealed class GlbModel
	{
		public sealed class Node
		{
			public string Name;

			public int Parent = -1;

			public float[] T = new float[3];

			public float[] R = new float[4] { 0f, 0f, 0f, 1f };

			public float[] S = new float[3] { 1f, 1f, 1f };
		}

		public sealed class Channel
		{
			public int Node;

			public char Path;

			public bool Step;

			public float[] Times;

			public float[] Values;
		}

		public sealed class Clip
		{
			public string Name;

			public float Start;

			public float End;

			public Channel[] Channels;
		}

		public float[] Positions;

		public float[] Normals;

		public float[] Uvs;

		public int[] Triangles;

		public byte[] Image;

		public byte[][] Images;

		public int[] Joints;

		public float[] Weights;

		public Node[] Nodes;

		public int MeshNode = -1;

		public int[] SkinJoints;

		public float[] InverseBind;

		public Clip[] Clips;

		public int VertexCount => Positions.Length / 3;

		public int TriangleCount => Triangles.Length / 3;

		public static GlbModel Read(byte[] glb)
		{
			if (glb == null || glb.Length < 28 || BitConverter.ToUInt32(glb, 0) != 1179937895)
			{
				throw new FormatException("not a binary glTF file");
			}
			int num = BitConverter.ToInt32(glb, 12);
			if (BitConverter.ToUInt32(glb, 16) != 1313821514)
			{
				throw new FormatException("the first chunk is not JSON");
			}
			int binStart = 20 + num + 8;
			if (binStart > glb.Length || BitConverter.ToUInt32(glb, 20 + num + 4) != 5130562)
			{
				throw new FormatException("no binary chunk");
			}
			JsonElement accessors;
			JsonElement views;
			using (JsonDocument jsonDocument = JsonDocument.Parse(new ReadOnlyMemory<byte>(glb, 20, num)))
			{
				JsonElement rootElement = jsonDocument.RootElement;
				accessors = rootElement.GetProperty("accessors");
				views = rootElement.GetProperty("bufferViews");
				JsonElement jsonElement = rootElement.GetProperty("meshes")[0].GetProperty("primitives")[0];
				JsonElement property = jsonElement.GetProperty("attributes");
				GlbModel glbModel = new GlbModel
				{
					Positions = Floats(property.GetProperty("POSITION").GetInt32(), 3)
				};
				if (property.TryGetProperty("NORMAL", out var value))
				{
					glbModel.Normals = Floats(value.GetInt32(), 3);
				}
				if (property.TryGetProperty("TEXCOORD_0", out var value2))
				{
					glbModel.Uvs = Floats(value2.GetInt32(), 2);
				}
				int vertexCount = glbModel.VertexCount;
				for (int i = 0; i < vertexCount; i++)
				{
					glbModel.Positions[i * 3] = 0f - glbModel.Positions[i * 3];
					if (glbModel.Normals != null)
					{
						glbModel.Normals[i * 3] = 0f - glbModel.Normals[i * 3];
					}
					if (glbModel.Uvs != null)
					{
						glbModel.Uvs[i * 2 + 1] = 1f - glbModel.Uvs[i * 2 + 1];
					}
				}
				JsonElement a = accessors[jsonElement.GetProperty("indices").GetInt32()];
				int @int = a.GetProperty("count").GetInt32();
				int int2 = a.GetProperty("componentType").GetInt32();
				int num2 = Start(a);
				int num3 = int2 switch
				{
					5123 => 2, 
					5125 => 4, 
					_ => 1, 
				};
				if (@int % 3 != 0 || num2 + @int * num3 > glb.Length)
				{
					throw new FormatException("bad index data");
				}
				glbModel.Triangles = new int[@int];
				for (int j = 0; j < @int; j += 3)
				{
					int num4 = Index(glb, num2, int2, j);
					int num5 = Index(glb, num2, int2, j + 1);
					int num6 = Index(glb, num2, int2, j + 2);
					if (num4 >= vertexCount || num5 >= vertexCount || num6 >= vertexCount)
					{
						throw new FormatException("an index points past the vertices");
					}
					glbModel.Triangles[j] = num4;
					glbModel.Triangles[j + 1] = num6;
					glbModel.Triangles[j + 2] = num5;
				}
				if (rootElement.TryGetProperty("images", out var value3))
				{
					glbModel.Images = new byte[value3.GetArrayLength()][];
					for (int k = 0; k < glbModel.Images.Length; k++)
					{
						if (value3[k].TryGetProperty("bufferView", out var value4))
						{
							JsonElement jsonElement2 = views[value4.GetInt32()];
							int num7 = ViewStart(value4.GetInt32());
							int int3 = jsonElement2.GetProperty("byteLength").GetInt32();
							if (num7 + int3 <= glb.Length)
							{
								glbModel.Images[k] = new byte[int3];
								Buffer.BlockCopy(glb, num7, glbModel.Images[k], 0, int3);
							}
						}
					}
					if (glbModel.Images.Length != 0)
					{
						glbModel.Image = glbModel.Images[0];
					}
				}
				if (property.TryGetProperty("JOINTS_0", out var value5) && property.TryGetProperty("WEIGHTS_0", out var value6) && rootElement.TryGetProperty("skins", out var value7))
				{
					JsonElement a2 = accessors[value5.GetInt32()];
					int int4 = a2.GetProperty("componentType").GetInt32();
					int num8 = Start(a2);
					if (int4 != 5121 && int4 != 5123)
					{
						throw new FormatException("joint indices are not bytes or shorts");
					}
					if (num8 + vertexCount * 4 * ((int4 == 5121) ? 1 : 2) > glb.Length)
					{
						throw new FormatException("joint data outside the file");
					}
					glbModel.Joints = new int[vertexCount * 4];
					for (int l = 0; l < glbModel.Joints.Length; l++)
					{
						glbModel.Joints[l] = Index(glb, num8, int4, l);
					}
					glbModel.Weights = Floats(value6.GetInt32(), 4);
					ReadSkin(rootElement, value7[0], glbModel, Floats);
				}
				if (rootElement.TryGetProperty("animations", out var value8))
				{
					glbModel.Clips = ReadClips(value8, Floats);
				}
				return glbModel;
			}
			float[] Floats(int index, int width)
			{
				JsonElement a3 = accessors[index];
				if (a3.GetProperty("componentType").GetInt32() != 5126)
				{
					throw new FormatException("vertex data is not float");
				}
				int num9 = a3.GetProperty("count").GetInt32() * width;
				int num10 = Start(a3);
				if (num10 < binStart || num10 + num9 * 4 > glb.Length)
				{
					throw new FormatException("vertex data outside the file");
				}
				float[] array = new float[num9];
				Buffer.BlockCopy(glb, num10, array, 0, num9 * 4);
				return array;
			}
			int Start(JsonElement jsonElement3)
			{
				JsonElement value9;
				return ViewStart(jsonElement3.GetProperty("bufferView").GetInt32()) + (jsonElement3.TryGetProperty("byteOffset", out value9) ? value9.GetInt32() : 0);
			}
			int ViewStart(int view)
			{
				JsonElement jsonElement3 = views[view];
				JsonElement value9;
				return binStart + (jsonElement3.TryGetProperty("byteOffset", out value9) ? value9.GetInt32() : 0);
			}
		}

		private static void ReadSkin(JsonElement j, JsonElement skin, GlbModel m, Func<int, int, float[]> floats)
		{
			JsonElement property = j.GetProperty("nodes");
			m.Nodes = new Node[property.GetArrayLength()];
			for (int i = 0; i < m.Nodes.Length; i++)
			{
				JsonElement jsonElement = property[i];
				ref Node reference = ref m.Nodes[i];
				Node node = reference ?? (reference = new Node());
				node.Name = (jsonElement.TryGetProperty("name", out var value) ? value.GetString() : ("node" + i));
				JsonElement value3;
				if (jsonElement.TryGetProperty("translation", out var value2))
				{
					float[] obj = new float[3]
					{
						0f - value2[0].GetSingle(),
						value2[1].GetSingle(),
						0f
					};
					value3 = value2[2];
					obj[2] = value3.GetSingle();
					node.T = obj;
				}
				if (jsonElement.TryGetProperty("rotation", out var value4))
				{
					float[] obj2 = new float[4]
					{
						value4[0].GetSingle(),
						0f - value4[1].GetSingle(),
						0f - value4[2].GetSingle(),
						0f
					};
					value3 = value4[3];
					obj2[3] = value3.GetSingle();
					node.R = obj2;
				}
				if (jsonElement.TryGetProperty("scale", out var value5))
				{
					float[] obj3 = new float[3]
					{
						value5[0].GetSingle(),
						value5[1].GetSingle(),
						0f
					};
					value3 = value5[2];
					obj3[2] = value3.GetSingle();
					node.S = obj3;
				}
				if (jsonElement.TryGetProperty("matrix", out value3))
				{
					throw new FormatException("node " + node.Name + " uses a matrix");
				}
				if (jsonElement.TryGetProperty("mesh", out var value6) && value6.GetInt32() == 0 && m.MeshNode < 0)
				{
					m.MeshNode = i;
				}
				if (!jsonElement.TryGetProperty("children", out var value7))
				{
					continue;
				}
				foreach (JsonElement item in value7.EnumerateArray())
				{
					int @int = item.GetInt32();
					reference = ref m.Nodes[@int];
					(reference ?? (reference = new Node())).Parent = i;
				}
			}
			JsonElement property2 = skin.GetProperty("joints");
			m.SkinJoints = new int[property2.GetArrayLength()];
			for (int k = 0; k < m.SkinJoints.Length; k++)
			{
				m.SkinJoints[k] = property2[k].GetInt32();
			}
			for (int l = 0; l < m.Joints.Length; l++)
			{
				if (m.Joints[l] >= m.SkinJoints.Length)
				{
					throw new FormatException("a vertex names a joint the skin does not have");
				}
			}
			if (!skin.TryGetProperty("inverseBindMatrices", out var value8))
			{
				throw new FormatException("the skin has no inverse bind matrices");
			}
			m.InverseBind = floats(value8.GetInt32(), 16);
			for (int n = 0; n < m.SkinJoints.Length; n++)
			{
				for (int num = 0; num < 4; num++)
				{
					for (int num2 = 0; num2 < 4; num2++)
					{
						if (num2 == 0 != (num == 0))
						{
							m.InverseBind[n * 16 + num * 4 + num2] = 0f - m.InverseBind[n * 16 + num * 4 + num2];
						}
					}
				}
			}
		}

		private static Clip[] ReadClips(JsonElement anims, Func<int, int, float[]> floats)
		{
			Clip[] array = new Clip[anims.GetArrayLength()];
			for (int i = 0; i < array.Length; i++)
			{
				JsonElement jsonElement = anims[i];
				JsonElement property = jsonElement.GetProperty("samplers");
				JsonElement property2 = jsonElement.GetProperty("channels");
				JsonElement value;
				Clip clip = (array[i] = new Clip
				{
					Name = (jsonElement.TryGetProperty("name", out value) ? value.GetString() : ("clip" + i)),
					Start = float.MaxValue,
					End = 0f,
					Channels = new Channel[property2.GetArrayLength()]
				});
				for (int j = 0; j < clip.Channels.Length; j++)
				{
					JsonElement property3 = property2[j].GetProperty("target");
					JsonElement jsonElement2 = property[property2[j].GetProperty("sampler").GetInt32()];
					char c = property3.GetProperty("path").GetString() switch
					{
						"scale" => 'S', 
						"rotation" => 'R', 
						"translation" => 'T', 
						_ => '?', 
					};
					if (c == '?' || !property3.TryGetProperty("node", out var value2))
					{
						continue;
					}
					JsonElement value3;
					string text = (jsonElement2.TryGetProperty("interpolation", out value3) ? value3.GetString() : "LINEAR");
					if (text == "CUBICSPLINE")
					{
						throw new FormatException("cubic spline keys are not supported");
					}
					int num = ((c == 'R') ? 4 : 3);
					Channel channel = new Channel
					{
						Node = value2.GetInt32(),
						Path = c,
						Step = (text == "STEP"),
						Times = floats(jsonElement2.GetProperty("input").GetInt32(), 1),
						Values = floats(jsonElement2.GetProperty("output").GetInt32(), num)
					};
					if (channel.Values.Length != channel.Times.Length * num)
					{
						throw new FormatException("key count mismatch in " + clip.Name);
					}
					for (int k = 0; k < channel.Times.Length; k++)
					{
						switch (c)
						{
						case 'T':
							channel.Values[k * 3] = 0f - channel.Values[k * 3];
							break;
						case 'R':
							channel.Values[k * 4 + 1] = 0f - channel.Values[k * 4 + 1];
							channel.Values[k * 4 + 2] = 0f - channel.Values[k * 4 + 2];
							break;
						}
					}
					if (channel.Times.Length != 0)
					{
						clip.Start = Math.Min(clip.Start, channel.Times[0]);
						clip.End = Math.Max(clip.End, channel.Times[channel.Times.Length - 1]);
					}
					clip.Channels[j] = channel;
				}
				clip.Channels = Array.FindAll(clip.Channels, (Channel x) => x != null);
				if (clip.Start > clip.End)
				{
					clip.Start = clip.End;
				}
			}
			return array;
		}

		public Clip FindClip(string name)
		{
			if (Clips != null)
			{
				return Array.Find(Clips, (Clip c) => c.Name == name);
			}
			return null;
		}

		public static void Sample(Channel ch, float t, float[] into)
		{
			int num = ch.Times.Length;
			int num2 = ((ch.Path == 'R') ? 4 : 3);
			if (num == 0)
			{
				return;
			}
			int num3 = Array.BinarySearch(ch.Times, t);
			if (num3 < 0)
			{
				num3 = ~num3 - 1;
			}
			if (num3 < 0)
			{
				Array.Copy(ch.Values, 0, into, 0, num2);
				return;
			}
			if (num3 >= num - 1 || ch.Step)
			{
				Array.Copy(ch.Values, Math.Min(num3, num - 1) * num2, into, 0, num2);
				return;
			}
			float num4 = (t - ch.Times[num3]) / Math.Max(1E-06f, ch.Times[num3 + 1] - ch.Times[num3]);
			int num5 = num3 * num2;
			int num6 = num5 + num2;
			float num7 = 1f;
			if (num2 == 4 && ch.Values[num5] * ch.Values[num6] + ch.Values[num5 + 1] * ch.Values[num6 + 1] + ch.Values[num5 + 2] * ch.Values[num6 + 2] + ch.Values[num5 + 3] * ch.Values[num6 + 3] < 0f)
			{
				num7 = -1f;
			}
			float num8 = 0f;
			for (int i = 0; i < num2; i++)
			{
				into[i] = ch.Values[num5 + i] * (1f - num4) + num7 * ch.Values[num6 + i] * num4;
				num8 += into[i] * into[i];
			}
			if (num2 == 4 && num8 > 1E-12f)
			{
				num8 = (float)Math.Sqrt(num8);
				for (int j = 0; j < 4; j++)
				{
					into[j] /= num8;
				}
			}
		}

		private static int Index(byte[] b, int offset, int type, int i)
		{
			return type switch
			{
				5125 => (int)BitConverter.ToUInt32(b, offset + i * 4), 
				5123 => BitConverter.ToUInt16(b, offset + i * 2), 
				_ => b[offset + i], 
			};
		}

		public GlbModel Lining(Func<float, float, float, bool> keep, float inset)
		{
			int[] array = new int[VertexCount];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = -1;
			}
			List<int> list = new List<int>();
			int num = 0;
			for (int j = 0; j < Triangles.Length; j += 3)
			{
				int num2 = Triangles[j];
				int num3 = Triangles[j + 1];
				int num4 = Triangles[j + 2];
				float arg = (Positions[num2 * 3] + Positions[num3 * 3] + Positions[num4 * 3]) / 3f;
				float arg2 = (Positions[num2 * 3 + 1] + Positions[num3 * 3 + 1] + Positions[num4 * 3 + 1]) / 3f;
				float arg3 = (Positions[num2 * 3 + 2] + Positions[num3 * 3 + 2] + Positions[num4 * 3 + 2]) / 3f;
				if (!keep(arg, arg2, arg3))
				{
					continue;
				}
				int[] array2 = new int[3] { num2, num4, num3 };
				foreach (int num5 in array2)
				{
					if (array[num5] < 0)
					{
						array[num5] = num++;
					}
					list.Add(array[num5]);
				}
			}
			GlbModel glbModel = new GlbModel
			{
				Positions = new float[num * 3],
				Normals = new float[num * 3],
				Uvs = ((Uvs != null) ? new float[num * 2] : null),
				Triangles = list.ToArray()
			};
			for (int l = 0; l < array.Length; l++)
			{
				int num6 = array[l];
				if (num6 >= 0)
				{
					float num7 = ((Normals != null) ? Normals[l * 3] : 0f);
					float num8 = ((Normals != null) ? Normals[l * 3 + 1] : 0f);
					float num9 = ((Normals != null) ? Normals[l * 3 + 2] : 0f);
					glbModel.Positions[num6 * 3] = Positions[l * 3] - num7 * inset;
					glbModel.Positions[num6 * 3 + 1] = Positions[l * 3 + 1] - num8 * inset;
					glbModel.Positions[num6 * 3 + 2] = Positions[l * 3 + 2] - num9 * inset;
					glbModel.Normals[num6 * 3] = 0f - num7;
					glbModel.Normals[num6 * 3 + 1] = 0f - num8;
					glbModel.Normals[num6 * 3 + 2] = 0f - num9;
					if (glbModel.Uvs != null)
					{
						glbModel.Uvs[num6 * 2] = Uvs[l * 2];
						glbModel.Uvs[num6 * 2 + 1] = Uvs[l * 2 + 1];
					}
				}
			}
			return glbModel;
		}
	}
	public static class Il2CppUtil
	{
		public static Object StringKey(string s)
		{
			return (Object)(object)String.op_Implicit(s);
		}

		public static bool Alive(Object o)
		{
			try
			{
				if (o == null || ((Il2CppObjectBase)o).Pointer == IntPtr.Zero)
				{
					return false;
				}
				return o.m_CachedPtr != IntPtr.Zero || o != (Object)null;
			}
			catch
			{
				return false;
			}
		}

		public static Vector3 MakeVec3(float x, float y, float z)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3
			{
				x = x,
				y = y,
				z = z
			};
		}

		public static Rect MakeRect(float x, float y, float width, float height)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			return new Rect
			{
				m_XMin = x,
				m_YMin = y,
				m_Width = width,
				m_Height = height
			};
		}

		public static Color MakeColor(float r, float g, float b, float a)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			return new Color
			{
				r = r,
				g = g,
				b = b,
				a = a
			};
		}

		public static Quaternion Yaw(float degrees)
		{
			//IL_000f: 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)
			double num = (double)degrees * (Math.PI / 360.0);
			return new Quaternion
			{
				y = (float)Math.Sin(num),
				w = (float)Math.Cos(num)
			};
		}

		public static float SqrDistance(Vector3 a, Vector3 b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			/

BepInEx/plugins/AILimitCoop/LiteNetLib.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using LiteNetLib.Layers;
using LiteNetLib.Utils;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Ruslan Pyrch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2024 Ruslan Pyrch")]
[assembly: AssemblyDescription("Lite reliable UDP library for .NET, Mono, and .NET Core")]
[assembly: AssemblyFileVersion("1.3.1")]
[assembly: AssemblyInformationalVersion("1.0.0+f57b9eafe72b924681a371d671af911478b6ab88")]
[assembly: AssemblyProduct("LiteNetLib")]
[assembly: AssemblyTitle("LiteNetLib")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/RevenantX/LiteNetLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
}
namespace LiteNetLib
{
	internal abstract class BaseChannel
	{
		protected readonly NetPeer Peer;

		protected readonly Queue<NetPacket> OutgoingQueue = new Queue<NetPacket>(64);

		private int _isAddedToPeerChannelSendQueue;

		public int PacketsInQueue => OutgoingQueue.Count;

		protected BaseChannel(NetPeer peer)
		{
			Peer = peer;
		}

		public void AddToQueue(NetPacket packet)
		{
			lock (OutgoingQueue)
			{
				OutgoingQueue.Enqueue(packet);
			}
			AddToPeerChannelSendQueue();
		}

		protected void AddToPeerChannelSendQueue()
		{
			if (Interlocked.CompareExchange(ref _isAddedToPeerChannelSendQueue, 1, 0) == 0)
			{
				Peer.AddToReliableChannelSendQueue(this);
			}
		}

		public bool SendAndCheckQueue()
		{
			bool num = SendNextPackets();
			if (!num)
			{
				Interlocked.Exchange(ref _isAddedToPeerChannelSendQueue, 0);
			}
			return num;
		}

		protected abstract bool SendNextPackets();

		public abstract bool ProcessPacket(NetPacket packet);
	}
	internal enum ConnectionRequestResult
	{
		None,
		Accept,
		Reject,
		RejectForce
	}
	public class ConnectionRequest
	{
		private readonly NetManager _listener;

		private int _used;

		internal NetConnectRequestPacket InternalPacket;

		public readonly IPEndPoint RemoteEndPoint;

		public NetDataReader Data => InternalPacket.Data;

		internal ConnectionRequestResult Result { get; private set; }

		internal void UpdateRequest(NetConnectRequestPacket connectRequest)
		{
			if (connectRequest.ConnectionTime >= InternalPacket.ConnectionTime && (connectRequest.ConnectionTime != InternalPacket.ConnectionTime || connectRequest.ConnectionNumber != InternalPacket.ConnectionNumber))
			{
				InternalPacket = connectRequest;
			}
		}

		private bool TryActivate()
		{
			return Interlocked.CompareExchange(ref _used, 1, 0) == 0;
		}

		internal ConnectionRequest(IPEndPoint remoteEndPoint, NetConnectRequestPacket requestPacket, NetManager listener)
		{
			InternalPacket = requestPacket;
			RemoteEndPoint = remoteEndPoint;
			_listener = listener;
		}

		public NetPeer AcceptIfKey(string key)
		{
			if (!TryActivate())
			{
				return null;
			}
			try
			{
				if (Data.GetString() == key)
				{
					Result = ConnectionRequestResult.Accept;
				}
			}
			catch
			{
				NetDebug.WriteError("[AC] Invalid incoming data");
			}
			if (Result == ConnectionRequestResult.Accept)
			{
				return _listener.OnConnectionSolved(this, null, 0, 0);
			}
			Result = ConnectionRequestResult.Reject;
			_listener.OnConnectionSolved(this, null, 0, 0);
			return null;
		}

		public NetPeer Accept()
		{
			if (!TryActivate())
			{
				return null;
			}
			Result = ConnectionRequestResult.Accept;
			return _listener.OnConnectionSolved(this, null, 0, 0);
		}

		public void Reject(byte[] rejectData, int start, int length, bool force)
		{
			if (TryActivate())
			{
				Result = (force ? ConnectionRequestResult.RejectForce : ConnectionRequestResult.Reject);
				_listener.OnConnectionSolved(this, rejectData, start, length);
			}
		}

		public void Reject(byte[] rejectData, int start, int length)
		{
			Reject(rejectData, start, length, force: false);
		}

		public void RejectForce(byte[] rejectData, int start, int length)
		{
			Reject(rejectData, start, length, force: true);
		}

		public void RejectForce()
		{
			Reject(null, 0, 0, force: true);
		}

		public void RejectForce(byte[] rejectData)
		{
			Reject(rejectData, 0, rejectData.Length, force: true);
		}

		public void RejectForce(NetDataWriter rejectData)
		{
			Reject(rejectData.Data, 0, rejectData.Length, force: true);
		}

		public void Reject()
		{
			Reject(null, 0, 0, force: false);
		}

		public void Reject(byte[] rejectData)
		{
			Reject(rejectData, 0, rejectData.Length, force: false);
		}

		public void Reject(NetDataWriter rejectData)
		{
			Reject(rejectData.Data, 0, rejectData.Length, force: false);
		}
	}
	public enum UnconnectedMessageType
	{
		BasicMessage,
		Broadcast
	}
	public enum DisconnectReason
	{
		ConnectionFailed,
		Timeout,
		HostUnreachable,
		NetworkUnreachable,
		RemoteConnectionClose,
		DisconnectPeerCalled,
		ConnectionRejected,
		InvalidProtocol,
		UnknownHost,
		Reconnect,
		PeerToPeerConnection,
		PeerNotFound
	}
	public struct DisconnectInfo
	{
		public DisconnectReason Reason;

		public SocketError SocketErrorCode;

		public NetPacketReader AdditionalData;
	}
	public interface INetEventListener
	{
		void OnPeerConnected(NetPeer peer);

		void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo);

		void OnNetworkError(IPEndPoint endPoint, SocketError socketError);

		void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod);

		void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType);

		void OnNetworkLatencyUpdate(NetPeer peer, int latency);

		void OnConnectionRequest(ConnectionRequest request);
	}
	public interface IDeliveryEventListener
	{
		void OnMessageDelivered(NetPeer peer, object userData);
	}
	public interface INtpEventListener
	{
		void OnNtpResponse(NtpPacket packet);
	}
	public interface IPeerAddressChangedListener
	{
		void OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress);
	}
	public class EventBasedNetListener : INetEventListener, IDeliveryEventListener, INtpEventListener, IPeerAddressChangedListener
	{
		public delegate void OnPeerConnected(NetPeer peer);

		public delegate void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo);

		public delegate void OnNetworkError(IPEndPoint endPoint, SocketError socketError);

		public delegate void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod);

		public delegate void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType);

		public delegate void OnNetworkLatencyUpdate(NetPeer peer, int latency);

		public delegate void OnConnectionRequest(ConnectionRequest request);

		public delegate void OnDeliveryEvent(NetPeer peer, object userData);

		public delegate void OnNtpResponseEvent(NtpPacket packet);

		public delegate void OnPeerAddressChangedEvent(NetPeer peer, IPEndPoint previousAddress);

		public event OnPeerConnected PeerConnectedEvent;

		public event OnPeerDisconnected PeerDisconnectedEvent;

		public event OnNetworkError NetworkErrorEvent;

		public event OnNetworkReceive NetworkReceiveEvent;

		public event OnNetworkReceiveUnconnected NetworkReceiveUnconnectedEvent;

		public event OnNetworkLatencyUpdate NetworkLatencyUpdateEvent;

		public event OnConnectionRequest ConnectionRequestEvent;

		public event OnDeliveryEvent DeliveryEvent;

		public event OnNtpResponseEvent NtpResponseEvent;

		public event OnPeerAddressChangedEvent PeerAddressChangedEvent;

		public void ClearPeerConnectedEvent()
		{
			this.PeerConnectedEvent = null;
		}

		public void ClearPeerDisconnectedEvent()
		{
			this.PeerDisconnectedEvent = null;
		}

		public void ClearNetworkErrorEvent()
		{
			this.NetworkErrorEvent = null;
		}

		public void ClearNetworkReceiveEvent()
		{
			this.NetworkReceiveEvent = null;
		}

		public void ClearNetworkReceiveUnconnectedEvent()
		{
			this.NetworkReceiveUnconnectedEvent = null;
		}

		public void ClearNetworkLatencyUpdateEvent()
		{
			this.NetworkLatencyUpdateEvent = null;
		}

		public void ClearConnectionRequestEvent()
		{
			this.ConnectionRequestEvent = null;
		}

		public void ClearDeliveryEvent()
		{
			this.DeliveryEvent = null;
		}

		public void ClearNtpResponseEvent()
		{
			this.NtpResponseEvent = null;
		}

		public void ClearPeerAddressChangedEvent()
		{
			this.PeerAddressChangedEvent = null;
		}

		void INetEventListener.OnPeerConnected(NetPeer peer)
		{
			if (this.PeerConnectedEvent != null)
			{
				this.PeerConnectedEvent(peer);
			}
		}

		void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
		{
			if (this.PeerDisconnectedEvent != null)
			{
				this.PeerDisconnectedEvent(peer, disconnectInfo);
			}
		}

		void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode)
		{
			if (this.NetworkErrorEvent != null)
			{
				this.NetworkErrorEvent(endPoint, socketErrorCode);
			}
		}

		void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod)
		{
			if (this.NetworkReceiveEvent != null)
			{
				this.NetworkReceiveEvent(peer, reader, channelNumber, deliveryMethod);
			}
		}

		void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
		{
			if (this.NetworkReceiveUnconnectedEvent != null)
			{
				this.NetworkReceiveUnconnectedEvent(remoteEndPoint, reader, messageType);
			}
		}

		void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency)
		{
			if (this.NetworkLatencyUpdateEvent != null)
			{
				this.NetworkLatencyUpdateEvent(peer, latency);
			}
		}

		void INetEventListener.OnConnectionRequest(ConnectionRequest request)
		{
			if (this.ConnectionRequestEvent != null)
			{
				this.ConnectionRequestEvent(request);
			}
		}

		void IDeliveryEventListener.OnMessageDelivered(NetPeer peer, object userData)
		{
			if (this.DeliveryEvent != null)
			{
				this.DeliveryEvent(peer, userData);
			}
		}

		void INtpEventListener.OnNtpResponse(NtpPacket packet)
		{
			if (this.NtpResponseEvent != null)
			{
				this.NtpResponseEvent(packet);
			}
		}

		void IPeerAddressChangedListener.OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress)
		{
			if (this.PeerAddressChangedEvent != null)
			{
				this.PeerAddressChangedEvent(peer, previousAddress);
			}
		}
	}
	internal sealed class NetConnectRequestPacket
	{
		public const int HeaderSize = 18;

		public readonly long ConnectionTime;

		public byte ConnectionNumber;

		public readonly byte[] TargetAddress;

		public readonly NetDataReader Data;

		public readonly int PeerId;

		private NetConnectRequestPacket(long connectionTime, byte connectionNumber, int localId, byte[] targetAddress, NetDataReader data)
		{
			ConnectionTime = connectionTime;
			ConnectionNumber = connectionNumber;
			TargetAddress = targetAddress;
			Data = data;
			PeerId = localId;
		}

		public static int GetProtocolId(NetPacket packet)
		{
			return BitConverter.ToInt32(packet.RawData, 1);
		}

		public static NetConnectRequestPacket FromData(NetPacket packet)
		{
			if (packet.ConnectionNumber >= 4)
			{
				return null;
			}
			long connectionTime = BitConverter.ToInt64(packet.RawData, 5);
			int localId = BitConverter.ToInt32(packet.RawData, 13);
			int num = packet.RawData[17];
			if (num != 16 && num != 28)
			{
				return null;
			}
			byte[] array = new byte[num];
			Buffer.BlockCopy(packet.RawData, 18, array, 0, num);
			NetDataReader netDataReader = new NetDataReader(null, 0, 0);
			if (packet.Size > 18 + num)
			{
				netDataReader.SetSource(packet.RawData, 18 + num, packet.Size);
			}
			return new NetConnectRequestPacket(connectionTime, packet.ConnectionNumber, localId, array, netDataReader);
		}

		public static NetPacket Make(NetDataWriter connectData, SocketAddress addressBytes, long connectTime, int localId)
		{
			NetPacket netPacket = new NetPacket(PacketProperty.ConnectRequest, connectData.Length + addressBytes.Size);
			FastBitConverter.GetBytes(netPacket.RawData, 1, 13);
			FastBitConverter.GetBytes(netPacket.RawData, 5, connectTime);
			FastBitConverter.GetBytes(netPacket.RawData, 13, localId);
			netPacket.RawData[17] = (byte)addressBytes.Size;
			for (int i = 0; i < addressBytes.Size; i++)
			{
				netPacket.RawData[18 + i] = addressBytes[i];
			}
			Buffer.BlockCopy(connectData.Data, 0, netPacket.RawData, 18 + addressBytes.Size, connectData.Length);
			return netPacket;
		}
	}
	internal sealed class NetConnectAcceptPacket
	{
		public const int Size = 15;

		public readonly long ConnectionTime;

		public readonly byte ConnectionNumber;

		public readonly int PeerId;

		public readonly bool PeerNetworkChanged;

		private NetConnectAcceptPacket(long connectionTime, byte connectionNumber, int peerId, bool peerNetworkChanged)
		{
			ConnectionTime = connectionTime;
			ConnectionNumber = connectionNumber;
			PeerId = peerId;
			PeerNetworkChanged = peerNetworkChanged;
		}

		public static NetConnectAcceptPacket FromData(NetPacket packet)
		{
			if (packet.Size != 15)
			{
				return null;
			}
			long connectionTime = BitConverter.ToInt64(packet.RawData, 1);
			byte b = packet.RawData[9];
			if (b >= 4)
			{
				return null;
			}
			byte b2 = packet.RawData[10];
			if (b2 > 1)
			{
				return null;
			}
			int num = BitConverter.ToInt32(packet.RawData, 11);
			if (num < 0)
			{
				return null;
			}
			return new NetConnectAcceptPacket(connectionTime, b, num, b2 == 1);
		}

		public static NetPacket Make(long connectTime, byte connectNum, int localPeerId)
		{
			NetPacket netPacket = new NetPacket(PacketProperty.ConnectAccept, 0);
			FastBitConverter.GetBytes(netPacket.RawData, 1, connectTime);
			netPacket.RawData[9] = connectNum;
			FastBitConverter.GetBytes(netPacket.RawData, 11, localPeerId);
			return netPacket;
		}

		public static NetPacket MakeNetworkChanged(NetPeer peer)
		{
			NetPacket netPacket = new NetPacket(PacketProperty.PeerNotFound, 14);
			FastBitConverter.GetBytes(netPacket.RawData, 1, peer.ConnectTime);
			netPacket.RawData[9] = peer.ConnectionNum;
			netPacket.RawData[10] = 1;
			FastBitConverter.GetBytes(netPacket.RawData, 11, peer.RemoteId);
			return netPacket;
		}
	}
	internal static class NativeSocket
	{
		private static class WinSock
		{
			private const string LibName = "ws2_32.dll";

			[DllImport("ws2_32.dll", SetLastError = true)]
			public static extern int recvfrom(IntPtr socketHandle, [In][Out] byte[] pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [Out] byte[] socketAddress, [In][Out] ref int socketAddressSize);

			[DllImport("ws2_32.dll", SetLastError = true)]
			internal unsafe static extern int sendto(IntPtr socketHandle, byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [In] byte[] socketAddress, [In] int socketAddressSize);
		}

		private static class UnixSock
		{
			private const string LibName = "libc";

			[DllImport("libc", SetLastError = true)]
			public static extern int recvfrom(IntPtr socketHandle, [In][Out] byte[] pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [Out] byte[] socketAddress, [In][Out] ref int socketAddressSize);

			[DllImport("libc", SetLastError = true)]
			internal unsafe static extern int sendto(IntPtr socketHandle, byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [In] byte[] socketAddress, [In] int socketAddressSize);
		}

		public static readonly bool IsSupported;

		public static readonly bool UnixMode;

		public const int IPv4AddrSize = 16;

		public const int IPv6AddrSize = 28;

		public const int AF_INET = 2;

		public const int AF_INET6 = 10;

		private static readonly Dictionary<int, SocketError> NativeErrorToSocketError;

		static NativeSocket()
		{
			IsSupported = false;
			UnixMode = false;
			NativeErrorToSocketError = new Dictionary<int, SocketError>
			{
				{
					13,
					SocketError.AccessDenied
				},
				{
					98,
					SocketError.AddressAlreadyInUse
				},
				{
					99,
					SocketError.AddressNotAvailable
				},
				{
					97,
					SocketError.AddressFamilyNotSupported
				},
				{
					11,
					SocketError.WouldBlock
				},
				{
					114,
					SocketError.AlreadyInProgress
				},
				{
					9,
					SocketError.OperationAborted
				},
				{
					125,
					SocketError.OperationAborted
				},
				{
					103,
					SocketError.ConnectionAborted
				},
				{
					111,
					SocketError.ConnectionRefused
				},
				{
					104,
					SocketError.ConnectionReset
				},
				{
					89,
					SocketError.DestinationAddressRequired
				},
				{
					14,
					SocketError.Fault
				},
				{
					112,
					SocketError.HostDown
				},
				{
					6,
					SocketError.HostNotFound
				},
				{
					113,
					SocketError.HostUnreachable
				},
				{
					115,
					SocketError.InProgress
				},
				{
					4,
					SocketError.Interrupted
				},
				{
					22,
					SocketError.InvalidArgument
				},
				{
					106,
					SocketError.IsConnected
				},
				{
					24,
					SocketError.TooManyOpenSockets
				},
				{
					90,
					SocketError.MessageSize
				},
				{
					100,
					SocketError.NetworkDown
				},
				{
					102,
					SocketError.NetworkReset
				},
				{
					101,
					SocketError.NetworkUnreachable
				},
				{
					23,
					SocketError.TooManyOpenSockets
				},
				{
					105,
					SocketError.NoBufferSpaceAvailable
				},
				{
					61,
					SocketError.NoData
				},
				{
					2,
					SocketError.AddressNotAvailable
				},
				{
					92,
					SocketError.ProtocolOption
				},
				{
					107,
					SocketError.NotConnected
				},
				{
					88,
					SocketError.NotSocket
				},
				{
					3440,
					SocketError.OperationNotSupported
				},
				{
					1,
					SocketError.AccessDenied
				},
				{
					32,
					SocketError.Shutdown
				},
				{
					96,
					SocketError.ProtocolFamilyNotSupported
				},
				{
					93,
					SocketError.ProtocolNotSupported
				},
				{
					91,
					SocketError.ProtocolType
				},
				{
					94,
					SocketError.SocketNotSupported
				},
				{
					108,
					SocketError.Disconnecting
				},
				{
					110,
					SocketError.TimedOut
				},
				{
					0,
					SocketError.Success
				}
			};
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
			{
				IsSupported = true;
				UnixMode = true;
			}
			else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				IsSupported = true;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int RecvFrom(IntPtr socketHandle, byte[] pinnedBuffer, int len, byte[] socketAddress, ref int socketAddressSize)
		{
			if (!UnixMode)
			{
				return WinSock.recvfrom(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, ref socketAddressSize);
			}
			return UnixSock.recvfrom(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, ref socketAddressSize);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static int SendTo(IntPtr socketHandle, byte* pinnedBuffer, int len, byte[] socketAddress, int socketAddressSize)
		{
			if (!UnixMode)
			{
				return WinSock.sendto(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, socketAddressSize);
			}
			return UnixSock.sendto(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, socketAddressSize);
		}

		public static SocketError GetSocketError()
		{
			int lastWin32Error = Marshal.GetLastWin32Error();
			if (UnixMode)
			{
				if (!NativeErrorToSocketError.TryGetValue(lastWin32Error, out var value))
				{
					return SocketError.SocketError;
				}
				return value;
			}
			return (SocketError)lastWin32Error;
		}

		public static SocketException GetSocketException()
		{
			int lastWin32Error = Marshal.GetLastWin32Error();
			if (UnixMode)
			{
				if (!NativeErrorToSocketError.TryGetValue(lastWin32Error, out var value))
				{
					return new SocketException(-1);
				}
				return new SocketException((int)value);
			}
			return new SocketException(lastWin32Error);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short GetNativeAddressFamily(IPEndPoint remoteEndPoint)
		{
			if (!UnixMode)
			{
				return (short)remoteEndPoint.AddressFamily;
			}
			return (short)((remoteEndPoint.AddressFamily == AddressFamily.InterNetwork) ? 2 : 10);
		}
	}
	public enum NatAddressType
	{
		Internal,
		External
	}
	public interface INatPunchListener
	{
		void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token);

		void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token);
	}
	public class EventBasedNatPunchListener : INatPunchListener
	{
		public delegate void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token);

		public delegate void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token);

		public event OnNatIntroductionRequest NatIntroductionRequest;

		public event OnNatIntroductionSuccess NatIntroductionSuccess;

		void INatPunchListener.OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token)
		{
			if (this.NatIntroductionRequest != null)
			{
				this.NatIntroductionRequest(localEndPoint, remoteEndPoint, token);
			}
		}

		void INatPunchListener.OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token)
		{
			if (this.NatIntroductionSuccess != null)
			{
				this.NatIntroductionSuccess(targetEndPoint, type, token);
			}
		}
	}
	public sealed class NatPunchModule
	{
		private struct RequestEventData
		{
			public IPEndPoint LocalEndPoint;

			public IPEndPoint RemoteEndPoint;

			public string Token;
		}

		private struct SuccessEventData
		{
			public IPEndPoint TargetEndPoint;

			public NatAddressType Type;

			public string Token;
		}

		private class NatIntroduceRequestPacket
		{
			public IPEndPoint Internal
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}

			public string Token
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}
		}

		private class NatIntroduceResponsePacket
		{
			public IPEndPoint Internal
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}

			public IPEndPoint External
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}

			public string Token
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}
		}

		private class NatPunchPacket
		{
			public string Token
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}

			public bool IsExternal
			{
				[Preserve]
				get;
				[Preserve]
				set;
			}
		}

		private readonly NetManager _socket;

		private readonly ConcurrentQueue<RequestEventData> _requestEvents = new ConcurrentQueue<RequestEventData>();

		private readonly ConcurrentQueue<SuccessEventData> _successEvents = new ConcurrentQueue<SuccessEventData>();

		private readonly NetDataReader _cacheReader = new NetDataReader();

		private readonly NetDataWriter _cacheWriter = new NetDataWriter();

		private readonly NetPacketProcessor _netPacketProcessor = new NetPacketProcessor(256);

		private INatPunchListener _natPunchListener;

		public const int MaxTokenLength = 256;

		public bool UnsyncedEvents;

		internal NatPunchModule(NetManager socket)
		{
			_socket = socket;
			_netPacketProcessor.SubscribeReusable<NatIntroduceResponsePacket>(OnNatIntroductionResponse);
			_netPacketProcessor.SubscribeReusable<NatIntroduceRequestPacket, IPEndPoint>(OnNatIntroductionRequest);
			_netPacketProcessor.SubscribeReusable<NatPunchPacket, IPEndPoint>(OnNatPunch);
		}

		internal void ProcessMessage(IPEndPoint senderEndPoint, NetPacket packet)
		{
			lock (_cacheReader)
			{
				_cacheReader.SetSource(packet.RawData, 1, packet.Size);
				_netPacketProcessor.ReadAllPackets(_cacheReader, senderEndPoint);
			}
		}

		public void Init(INatPunchListener listener)
		{
			_natPunchListener = listener;
		}

		private void Send<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T packet, IPEndPoint target) where T : class, new()
		{
			_cacheWriter.Reset();
			_cacheWriter.Put((byte)16);
			_netPacketProcessor.Write(_cacheWriter, packet);
			_socket.SendRaw(_cacheWriter.Data, 0, _cacheWriter.Length, target);
		}

		public void NatIntroduce(IPEndPoint hostInternal, IPEndPoint hostExternal, IPEndPoint clientInternal, IPEndPoint clientExternal, string additionalInfo)
		{
			NatIntroduceResponsePacket natIntroduceResponsePacket = new NatIntroduceResponsePacket
			{
				Token = additionalInfo
			};
			natIntroduceResponsePacket.Internal = hostInternal;
			natIntroduceResponsePacket.External = hostExternal;
			Send(natIntroduceResponsePacket, clientExternal);
			natIntroduceResponsePacket.Internal = clientInternal;
			natIntroduceResponsePacket.External = clientExternal;
			Send(natIntroduceResponsePacket, hostExternal);
		}

		public void PollEvents()
		{
			if (!UnsyncedEvents && _natPunchListener != null && (!_successEvents.IsEmpty || !_requestEvents.IsEmpty))
			{
				SuccessEventData result;
				while (_successEvents.TryDequeue(out result))
				{
					_natPunchListener.OnNatIntroductionSuccess(result.TargetEndPoint, result.Type, result.Token);
				}
				RequestEventData result2;
				while (_requestEvents.TryDequeue(out result2))
				{
					_natPunchListener.OnNatIntroductionRequest(result2.LocalEndPoint, result2.RemoteEndPoint, result2.Token);
				}
			}
		}

		public void SendNatIntroduceRequest(string host, int port, string additionalInfo)
		{
			SendNatIntroduceRequest(NetUtils.MakeEndPoint(host, port), additionalInfo);
		}

		public void SendNatIntroduceRequest(IPEndPoint masterServerEndPoint, string additionalInfo)
		{
			string localIp = NetUtils.GetLocalIp(LocalAddrType.IPv4);
			if (string.IsNullOrEmpty(localIp) || masterServerEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
			{
				localIp = NetUtils.GetLocalIp(LocalAddrType.IPv6);
			}
			Send(new NatIntroduceRequestPacket
			{
				Internal = NetUtils.MakeEndPoint(localIp, _socket.LocalPort),
				Token = additionalInfo
			}, masterServerEndPoint);
		}

		private void OnNatIntroductionRequest(NatIntroduceRequestPacket req, IPEndPoint senderEndPoint)
		{
			if (UnsyncedEvents)
			{
				_natPunchListener.OnNatIntroductionRequest(req.Internal, senderEndPoint, req.Token);
				return;
			}
			_requestEvents.Enqueue(new RequestEventData
			{
				LocalEndPoint = req.Internal,
				RemoteEndPoint = senderEndPoint,
				Token = req.Token
			});
		}

		private void OnNatIntroductionResponse(NatIntroduceResponsePacket req)
		{
			NatPunchPacket natPunchPacket = new NatPunchPacket
			{
				Token = req.Token
			};
			Send(natPunchPacket, req.Internal);
			_socket.Ttl = 2;
			_socket.SendRaw(new byte[1] { 17 }, 0, 1, req.External);
			_socket.Ttl = 255;
			natPunchPacket.IsExternal = true;
			Send(natPunchPacket, req.External);
		}

		private void OnNatPunch(NatPunchPacket req, IPEndPoint senderEndPoint)
		{
			if (UnsyncedEvents)
			{
				_natPunchListener.OnNatIntroductionSuccess(senderEndPoint, req.IsExternal ? NatAddressType.External : NatAddressType.Internal, req.Token);
				return;
			}
			_successEvents.Enqueue(new SuccessEventData
			{
				TargetEndPoint = senderEndPoint,
				Type = (req.IsExternal ? NatAddressType.External : NatAddressType.Internal),
				Token = req.Token
			});
		}
	}
	public enum DeliveryMethod : byte
	{
		Unreliable = 4,
		ReliableUnordered = 0,
		Sequenced = 1,
		ReliableOrdered = 2,
		ReliableSequenced = 3
	}
	public static class NetConstants
	{
		public const int DefaultWindowSize = 64;

		public const int SocketBufferSize = 1048576;

		public const int SocketTTL = 255;

		public const int HeaderSize = 1;

		public const int ChanneledHeaderSize = 4;

		public const int FragmentHeaderSize = 6;

		public const int FragmentedHeaderTotalSize = 10;

		public const ushort MaxSequence = 32768;

		public const ushort HalfMaxSequence = 16384;

		internal const int ProtocolId = 13;

		internal const int MaxUdpHeaderSize = 68;

		internal const int ChannelTypeCount = 4;

		internal static readonly int[] PossibleMtu = new int[6] { 1024, 1164, 1392, 1404, 1424, 1432 };

		public static readonly int InitialMtu = PossibleMtu[0];

		public static readonly int MaxPacketSize = PossibleMtu[PossibleMtu.Length - 1];

		public static readonly int MaxUnreliableDataSize = MaxPacketSize - 1;

		public const byte MaxConnectionNumber = 4;
	}
	public class InvalidPacketException : ArgumentException
	{
		public InvalidPacketException(string message)
			: base(message)
		{
		}
	}
	public class TooBigPacketException : InvalidPacketException
	{
		public TooBigPacketException(string message)
			: base(message)
		{
		}
	}
	public enum NetLogLevel
	{
		Warning,
		Error,
		Trace,
		Info
	}
	public interface INetLogger
	{
		void WriteNet(NetLogLevel level, string str, params object[] args);
	}
	public static class NetDebug
	{
		public static INetLogger Logger = null;

		private static readonly object DebugLogLock = new object();

		private static void WriteLogic(NetLogLevel logLevel, string str, params object[] args)
		{
			lock (DebugLogLock)
			{
				if (Logger == null)
				{
					Console.WriteLine(str, args);
				}
				else
				{
					Logger.WriteNet(logLevel, str, args);
				}
			}
		}

		[Conditional("DEBUG_MESSAGES")]
		internal static void Write(string str)
		{
			WriteLogic(NetLogLevel.Trace, str);
		}

		[Conditional("DEBUG_MESSAGES")]
		internal static void Write(NetLogLevel level, string str)
		{
			WriteLogic(level, str);
		}

		[Conditional("DEBUG_MESSAGES")]
		[Conditional("DEBUG")]
		internal static void WriteForce(string str)
		{
			WriteLogic(NetLogLevel.Trace, str);
		}

		[Conditional("DEBUG_MESSAGES")]
		[Conditional("DEBUG")]
		internal static void WriteForce(NetLogLevel level, string str)
		{
			WriteLogic(level, str);
		}

		internal static void WriteError(string str)
		{
			WriteLogic(NetLogLevel.Error, str);
		}
	}
	public sealed class NetPacketReader : NetDataReader
	{
		private NetPacket _packet;

		private readonly NetManager _manager;

		private readonly NetEvent _evt;

		internal NetPacketReader(NetManager manager, NetEvent evt)
		{
			_manager = manager;
			_evt = evt;
		}

		internal void SetSource(NetPacket packet, int headerSize)
		{
			if (packet != null)
			{
				_packet = packet;
				SetSource(packet.RawData, headerSize, packet.Size);
			}
		}

		internal void RecycleInternal()
		{
			Clear();
			if (_packet != null)
			{
				_manager.PoolRecycle(_packet);
			}
			_packet = null;
			_manager.RecycleEvent(_evt);
		}

		public void Recycle()
		{
			if (!_manager.AutoRecycle)
			{
				RecycleInternal();
			}
		}
	}
	internal sealed class NetEvent
	{
		public enum EType
		{
			Connect,
			Disconnect,
			Receive,
			ReceiveUnconnected,
			Error,
			ConnectionLatencyUpdated,
			Broadcast,
			ConnectionRequest,
			MessageDelivered,
			PeerAddressChanged
		}

		public NetEvent Next;

		public EType Type;

		public NetPeer Peer;

		public IPEndPoint RemoteEndPoint;

		public object UserData;

		public int Latency;

		public SocketError ErrorCode;

		public DisconnectReason DisconnectReason;

		public ConnectionRequest ConnectionRequest;

		public DeliveryMethod DeliveryMethod;

		public byte ChannelNumber;

		public readonly NetPacketReader DataReader;

		public NetEvent(NetManager manager)
		{
			DataReader = new NetPacketReader(manager, this);
		}
	}
	public class NetManager : IEnumerable<NetPeer>, IEnumerable
	{
		public struct NetPeerEnumerator : IEnumerator<NetPeer>, IEnumerator, IDisposable
		{
			private readonly NetPeer _initialPeer;

			private NetPeer _p;

			public NetPeer Current => _p;

			object IEnumerator.Current => _p;

			public NetPeerEnumerator(NetPeer p)
			{
				_initialPeer = p;
				_p = null;
			}

			public void Dispose()
			{
			}

			public bool MoveNext()
			{
				_p = ((_p == null) ? _initialPeer : _p.NextPeer);
				return _p != null;
			}

			public void Reset()
			{
				throw new NotSupportedException();
			}
		}

		private struct IncomingData
		{
			public NetPacket Data;

			public IPEndPoint EndPoint;

			public DateTime TimeWhenGet;
		}

		private struct Slot
		{
			internal int HashCode;

			internal int Next;

			internal NetPeer Value;
		}

		private readonly List<IncomingData> _pingSimulationList = new List<IncomingData>();

		private readonly Random _randomGenerator = new Random();

		private const int MinLatencyThreshold = 5;

		private Thread _logicThread;

		private bool _manualMode;

		private readonly AutoResetEvent _updateTriggerEvent = new AutoResetEvent(initialState: true);

		private NetEvent _pendingEventHead;

		private NetEvent _pendingEventTail;

		private NetEvent _netEventPoolHead;

		private readonly INetEventListener _netEventListener;

		private readonly IDeliveryEventListener _deliveryEventListener;

		private readonly INtpEventListener _ntpEventListener;

		private readonly IPeerAddressChangedListener _peerAddressChangedListener;

		private readonly Dictionary<IPEndPoint, ConnectionRequest> _requestsDict = new Dictionary<IPEndPoint, ConnectionRequest>();

		private readonly ConcurrentDictionary<IPEndPoint, NtpRequest> _ntpRequests = new ConcurrentDictionary<IPEndPoint, NtpRequest>();

		private long _connectedPeersCount;

		private readonly List<NetPeer> _connectedPeerListCache = new List<NetPeer>();

		private readonly PacketLayerBase _extraPacketLayer;

		private int _lastPeerId;

		private ConcurrentQueue<int> _peerIds = new ConcurrentQueue<int>();

		private byte _channelsCount = 1;

		private readonly object _eventLock = new object();

		private bool _dropPacket;

		public bool UnconnectedMessagesEnabled;

		public bool NatPunchEnabled;

		public int UpdateTime = 15;

		public int PingInterval = 1000;

		public int DisconnectTimeout = 5000;

		public bool SimulatePacketLoss;

		public bool SimulateLatency;

		public int SimulationPacketLossChance = 10;

		public int SimulationMinLatency = 30;

		public int SimulationMaxLatency = 100;

		public bool UnsyncedEvents;

		public bool UnsyncedReceiveEvent;

		public bool UnsyncedDeliveryEvent;

		public bool BroadcastReceiveEnabled;

		public int ReconnectDelay = 500;

		public int MaxConnectAttempts = 10;

		public bool ReuseAddress;

		public bool DontRoute;

		public readonly NetStatistics Statistics = new NetStatistics();

		public bool EnableStatistics;

		public readonly NatPunchModule NatPunchModule;

		public bool AutoRecycle;

		public bool IPv6Enabled = true;

		public int MtuOverride;

		public bool MtuDiscovery;

		public bool UseNativeSockets;

		public bool DisconnectOnUnreachable;

		public bool AllowPeerAddressChange;

		private const int MaxPrimeArrayLength = 2147483587;

		private const int HashPrime = 101;

		private const int Lower31BitMask = int.MaxValue;

		private static readonly int[] Primes;

		private int[] _buckets;

		private Slot[] _slots;

		private int _count;

		private int _lastIndex;

		private int _freeList = -1;

		private NetPeer[] _peersArray = new NetPeer[32];

		private readonly ReaderWriterLockSlim _peersLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

		private volatile NetPeer _headPeer;

		private NetPacket _poolHead;

		private int _poolCount;

		private readonly object _poolLock = new object();

		public int PacketPoolSize = 1000;

		private const int ReceivePollingTime = 500000;

		private Socket _udpSocketv4;

		private Socket _udpSocketv6;

		private Thread _receiveThread;

		private IPEndPoint _bufferEndPointv4;

		private IPEndPoint _bufferEndPointv6;

		private const int SioUdpConnreset = -1744830452;

		private static readonly IPAddress MulticastAddressV6;

		public static readonly bool IPv6Support;

		internal bool NotConnected;

		public bool IsRunning { get; private set; }

		public int LocalPort { get; private set; }

		public NetPeer FirstPeer => _headPeer;

		public byte ChannelsCount
		{
			get
			{
				return _channelsCount;
			}
			set
			{
				if (value < 1 || value > 64)
				{
					throw new ArgumentException("Channels count must be between 1 and 64");
				}
				_channelsCount = value;
			}
		}

		public List<NetPeer> ConnectedPeerList
		{
			get
			{
				GetPeersNonAlloc(_connectedPeerListCache, ConnectionState.Connected);
				return _connectedPeerListCache;
			}
		}

		public int ConnectedPeersCount => (int)Interlocked.Read(ref _connectedPeersCount);

		public int ExtraPacketSizeForLayer => _extraPacketLayer?.ExtraPacketSizeForLayer ?? 0;

		public int PoolCount => _poolCount;

		public short Ttl
		{
			get
			{
				return _udpSocketv4.Ttl;
			}
			internal set
			{
				_udpSocketv4.Ttl = value;
			}
		}

		public NetManager(INetEventListener listener, PacketLayerBase extraPacketLayer = null)
		{
			_netEventListener = listener;
			_deliveryEventListener = listener as IDeliveryEventListener;
			_ntpEventListener = listener as INtpEventListener;
			_peerAddressChangedListener = listener as IPeerAddressChangedListener;
			NatPunchModule = new NatPunchModule(this);
			_extraPacketLayer = extraPacketLayer;
		}

		internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency)
		{
			CreateEvent(NetEvent.EType.ConnectionLatencyUpdated, fromPeer, null, SocketError.Success, latency, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
		}

		internal void MessageDelivered(NetPeer fromPeer, object userData)
		{
			if (_deliveryEventListener != null)
			{
				CreateEvent(NetEvent.EType.MessageDelivered, fromPeer, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, null, userData);
			}
		}

		internal void DisconnectPeerForce(NetPeer peer, DisconnectReason reason, SocketError socketErrorCode, NetPacket eventData)
		{
			DisconnectPeer(peer, reason, socketErrorCode, force: true, null, 0, 0, eventData);
		}

		private void DisconnectPeer(NetPeer peer, DisconnectReason reason, SocketError socketErrorCode, bool force, byte[] data, int start, int count, NetPacket eventData)
		{
			switch (peer.Shutdown(data, start, count, force))
			{
			case ShutdownResult.None:
				return;
			case ShutdownResult.WasConnected:
				Interlocked.Decrement(ref _connectedPeersCount);
				break;
			}
			CreateEvent(NetEvent.EType.Disconnect, peer, null, socketErrorCode, 0, reason, null, DeliveryMethod.Unreliable, 0, eventData);
		}

		private void CreateEvent(NetEvent.EType type, NetPeer peer = null, IPEndPoint remoteEndPoint = null, SocketError errorCode = SocketError.Success, int latency = 0, DisconnectReason disconnectReason = DisconnectReason.ConnectionFailed, ConnectionRequest connectionRequest = null, DeliveryMethod deliveryMethod = DeliveryMethod.Unreliable, byte channelNumber = 0, NetPacket readerSource = null, object userData = null)
		{
			bool flag = UnsyncedEvents;
			switch (type)
			{
			case NetEvent.EType.Connect:
				Interlocked.Increment(ref _connectedPeersCount);
				break;
			case NetEvent.EType.MessageDelivered:
				flag = UnsyncedDeliveryEvent;
				break;
			}
			NetEvent netEvent;
			lock (_eventLock)
			{
				netEvent = _netEventPoolHead;
				if (netEvent == null)
				{
					netEvent = new NetEvent(this);
				}
				else
				{
					_netEventPoolHead = netEvent.Next;
				}
			}
			netEvent.Next = null;
			netEvent.Type = type;
			netEvent.DataReader.SetSource(readerSource, readerSource?.GetHeaderSize() ?? 0);
			netEvent.Peer = peer;
			netEvent.RemoteEndPoint = remoteEndPoint;
			netEvent.Latency = latency;
			netEvent.ErrorCode = errorCode;
			netEvent.DisconnectReason = disconnectReason;
			netEvent.ConnectionRequest = connectionRequest;
			netEvent.DeliveryMethod = deliveryMethod;
			netEvent.ChannelNumber = channelNumber;
			netEvent.UserData = userData;
			if (flag || _manualMode)
			{
				ProcessEvent(netEvent);
				return;
			}
			lock (_eventLock)
			{
				if (_pendingEventTail == null)
				{
					_pendingEventHead = netEvent;
				}
				else
				{
					_pendingEventTail.Next = netEvent;
				}
				_pendingEventTail = netEvent;
			}
		}

		private void ProcessEvent(NetEvent evt)
		{
			bool isNull = evt.DataReader.IsNull;
			switch (evt.Type)
			{
			case NetEvent.EType.Connect:
				_netEventListener.OnPeerConnected(evt.Peer);
				break;
			case NetEvent.EType.Disconnect:
			{
				DisconnectInfo disconnectInfo = default(DisconnectInfo);
				disconnectInfo.Reason = evt.DisconnectReason;
				disconnectInfo.AdditionalData = evt.DataReader;
				disconnectInfo.SocketErrorCode = evt.ErrorCode;
				DisconnectInfo disconnectInfo2 = disconnectInfo;
				_netEventListener.OnPeerDisconnected(evt.Peer, disconnectInfo2);
				break;
			}
			case NetEvent.EType.Receive:
				_netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader, evt.ChannelNumber, evt.DeliveryMethod);
				break;
			case NetEvent.EType.ReceiveUnconnected:
				_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.BasicMessage);
				break;
			case NetEvent.EType.Broadcast:
				_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Broadcast);
				break;
			case NetEvent.EType.Error:
				_netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.ErrorCode);
				break;
			case NetEvent.EType.ConnectionLatencyUpdated:
				_netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.Latency);
				break;
			case NetEvent.EType.ConnectionRequest:
				_netEventListener.OnConnectionRequest(evt.ConnectionRequest);
				break;
			case NetEvent.EType.MessageDelivered:
				_deliveryEventListener.OnMessageDelivered(evt.Peer, evt.UserData);
				break;
			case NetEvent.EType.PeerAddressChanged:
			{
				_peersLock.EnterUpgradeableReadLock();
				IPEndPoint iPEndPoint = null;
				if (ContainsPeer(evt.Peer))
				{
					_peersLock.EnterWriteLock();
					RemovePeerFromSet(evt.Peer);
					iPEndPoint = new IPEndPoint(evt.Peer.Address, evt.Peer.Port);
					evt.Peer.FinishEndPointChange(evt.RemoteEndPoint);
					AddPeerToSet(evt.Peer);
					_peersLock.ExitWriteLock();
				}
				_peersLock.ExitUpgradeableReadLock();
				if (iPEndPoint != null && _peerAddressChangedListener != null)
				{
					_peerAddressChangedListener.OnPeerAddressChanged(evt.Peer, iPEndPoint);
				}
				break;
			}
			}
			if (isNull)
			{
				RecycleEvent(evt);
			}
			else if (AutoRecycle)
			{
				evt.DataReader.RecycleInternal();
			}
		}

		internal void RecycleEvent(NetEvent evt)
		{
			evt.Peer = null;
			evt.ErrorCode = SocketError.Success;
			evt.RemoteEndPoint = null;
			evt.ConnectionRequest = null;
			lock (_eventLock)
			{
				evt.Next = _netEventPoolHead;
				_netEventPoolHead = evt;
			}
		}

		private void UpdateLogic()
		{
			List<NetPeer> list = new List<NetPeer>();
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			while (IsRunning)
			{
				try
				{
					float num = (float)((double)stopwatch.ElapsedTicks / (double)Stopwatch.Frequency * 1000.0);
					num = ((num <= 0f) ? 0.001f : num);
					stopwatch.Restart();
					for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
					{
						if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > (float)DisconnectTimeout)
						{
							list.Add(netPeer);
						}
						else
						{
							netPeer.Update(num);
						}
					}
					if (list.Count > 0)
					{
						_peersLock.EnterWriteLock();
						for (int i = 0; i < list.Count; i++)
						{
							RemovePeer(list[i], enableWriteLock: false);
						}
						_peersLock.ExitWriteLock();
						list.Clear();
					}
					ProcessNtpRequests(num);
					int num2 = UpdateTime - (int)stopwatch.ElapsedMilliseconds;
					if (num2 > 0)
					{
						_updateTriggerEvent.WaitOne(num2);
					}
				}
				catch (ThreadAbortException)
				{
					return;
				}
				catch (Exception ex2)
				{
					NetDebug.WriteError("[NM] LogicThread error: " + ex2);
				}
			}
			stopwatch.Stop();
		}

		[Conditional("DEBUG")]
		private void ProcessDelayedPackets()
		{
			if (!SimulateLatency)
			{
				return;
			}
			DateTime utcNow = DateTime.UtcNow;
			lock (_pingSimulationList)
			{
				for (int i = 0; i < _pingSimulationList.Count; i++)
				{
					IncomingData incomingData = _pingSimulationList[i];
					if (incomingData.TimeWhenGet <= utcNow)
					{
						HandleMessageReceived(incomingData.Data, incomingData.EndPoint);
						_pingSimulationList.RemoveAt(i);
						i--;
					}
				}
			}
		}

		private void ProcessNtpRequests(float elapsedMilliseconds)
		{
			List<IPEndPoint> list = null;
			foreach (KeyValuePair<IPEndPoint, NtpRequest> ntpRequest in _ntpRequests)
			{
				ntpRequest.Value.Send(_udpSocketv4, elapsedMilliseconds);
				if (ntpRequest.Value.NeedToKill)
				{
					if (list == null)
					{
						list = new List<IPEndPoint>();
					}
					list.Add(ntpRequest.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (IPEndPoint item in list)
			{
				_ntpRequests.TryRemove(item, out var _);
			}
		}

		public void ManualUpdate(float elapsedMilliseconds)
		{
			if (!_manualMode)
			{
				return;
			}
			for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
			{
				if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > (float)DisconnectTimeout)
				{
					RemovePeer(netPeer, enableWriteLock: false);
				}
				else
				{
					netPeer.Update(elapsedMilliseconds);
				}
			}
			ProcessNtpRequests(elapsedMilliseconds);
		}

		internal NetPeer OnConnectionSolved(ConnectionRequest request, byte[] rejectData, int start, int length)
		{
			NetPeer actualValue = null;
			if (request.Result == ConnectionRequestResult.RejectForce)
			{
				if (rejectData != null && length > 0)
				{
					NetPacket netPacket = PoolGetWithProperty(PacketProperty.Disconnect, length);
					netPacket.ConnectionNumber = request.InternalPacket.ConnectionNumber;
					FastBitConverter.GetBytes(netPacket.RawData, 1, request.InternalPacket.ConnectionTime);
					if (netPacket.Size >= NetConstants.PossibleMtu[0])
					{
						NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU!");
					}
					else
					{
						Buffer.BlockCopy(rejectData, start, netPacket.RawData, 9, length);
					}
					SendRawAndRecycle(netPacket, request.RemoteEndPoint);
				}
				lock (_requestsDict)
				{
					_requestsDict.Remove(request.RemoteEndPoint);
				}
			}
			else
			{
				lock (_requestsDict)
				{
					if (!TryGetPeer(request.RemoteEndPoint, out actualValue))
					{
						if (request.Result == ConnectionRequestResult.Reject)
						{
							actualValue = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId());
							actualValue.Reject(request.InternalPacket, rejectData, start, length);
							AddPeer(actualValue);
						}
						else
						{
							actualValue = new NetPeer(this, request, GetNextPeerId());
							AddPeer(actualValue);
							CreateEvent(NetEvent.EType.Connect, actualValue, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
						}
					}
					_requestsDict.Remove(request.RemoteEndPoint);
				}
			}
			return actualValue;
		}

		private int GetNextPeerId()
		{
			if (!_peerIds.TryDequeue(out var result))
			{
				return _lastPeerId++;
			}
			return result;
		}

		private void ProcessConnectRequest(IPEndPoint remoteEndPoint, NetPeer netPeer, NetConnectRequestPacket connRequest)
		{
			if (netPeer != null)
			{
				ConnectRequestResult connectRequestResult = netPeer.ProcessConnectRequest(connRequest);
				switch (connectRequestResult)
				{
				default:
					return;
				case ConnectRequestResult.Reconnection:
					DisconnectPeerForce(netPeer, DisconnectReason.Reconnect, SocketError.Success, null);
					RemovePeer(netPeer, enableWriteLock: true);
					break;
				case ConnectRequestResult.NewConnection:
					RemovePeer(netPeer, enableWriteLock: true);
					break;
				case ConnectRequestResult.P2PLose:
					DisconnectPeerForce(netPeer, DisconnectReason.PeerToPeerConnection, SocketError.Success, null);
					RemovePeer(netPeer, enableWriteLock: true);
					break;
				}
				if (connectRequestResult != ConnectRequestResult.P2PLose)
				{
					connRequest.ConnectionNumber = (byte)((netPeer.ConnectionNum + 1) % 4);
				}
			}
			ConnectionRequest value;
			lock (_requestsDict)
			{
				if (_requestsDict.TryGetValue(remoteEndPoint, out value))
				{
					value.UpdateRequest(connRequest);
					return;
				}
				value = new ConnectionRequest(remoteEndPoint, connRequest, this);
				_requestsDict.Add(remoteEndPoint, value);
			}
			CreateEvent(NetEvent.EType.ConnectionRequest, null, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, value, DeliveryMethod.Unreliable, 0);
		}

		private void OnMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			if (packet.Size == 0)
			{
				PoolRecycle(packet);
				return;
			}
			_dropPacket = false;
			if (!_dropPacket)
			{
				HandleMessageReceived(packet, remoteEndPoint);
			}
		}

		[Conditional("DEBUG")]
		private void HandleSimulateLatency(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			if (!SimulateLatency)
			{
				return;
			}
			int num = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency);
			if (num > 5)
			{
				lock (_pingSimulationList)
				{
					_pingSimulationList.Add(new IncomingData
					{
						Data = packet,
						EndPoint = remoteEndPoint,
						TimeWhenGet = DateTime.UtcNow.AddMilliseconds(num)
					});
				}
				_dropPacket = true;
			}
		}

		[Conditional("DEBUG")]
		private void HandleSimulatePacketLoss()
		{
			if (SimulatePacketLoss && _randomGenerator.NextDouble() * 100.0 < (double)SimulationPacketLossChance)
			{
				_dropPacket = true;
			}
		}

		private void HandleMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			int size = packet.Size;
			if (EnableStatistics)
			{
				Statistics.IncrementPacketsReceived();
				Statistics.AddBytesReceived(size);
			}
			if (_ntpRequests.Count > 0 && _ntpRequests.TryGetValue(remoteEndPoint, out var _))
			{
				if (packet.Size >= 48)
				{
					byte[] array = new byte[packet.Size];
					Buffer.BlockCopy(packet.RawData, 0, array, 0, packet.Size);
					NtpPacket ntpPacket = NtpPacket.FromServerResponse(array, DateTime.UtcNow);
					try
					{
						ntpPacket.ValidateReply();
					}
					catch (InvalidOperationException)
					{
						ntpPacket = null;
					}
					if (ntpPacket != null)
					{
						_ntpRequests.TryRemove(remoteEndPoint, out var _);
						_ntpEventListener?.OnNtpResponse(ntpPacket);
					}
				}
				return;
			}
			if (_extraPacketLayer != null)
			{
				_extraPacketLayer.ProcessInboundPacket(ref remoteEndPoint, ref packet.RawData, ref packet.Size);
				if (packet.Size == 0)
				{
					return;
				}
			}
			if (!packet.Verify())
			{
				NetDebug.WriteError("[NM] DataReceived: bad!");
				PoolRecycle(packet);
				return;
			}
			switch (packet.Property)
			{
			case PacketProperty.ConnectRequest:
				if (NetConnectRequestPacket.GetProtocolId(packet) != 13)
				{
					SendRawAndRecycle(PoolGetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint);
					return;
				}
				break;
			case PacketProperty.Broadcast:
				if (BroadcastReceiveEnabled)
				{
					CreateEvent(NetEvent.EType.Broadcast, null, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, packet);
				}
				return;
			case PacketProperty.UnconnectedMessage:
				if (UnconnectedMessagesEnabled)
				{
					CreateEvent(NetEvent.EType.ReceiveUnconnected, null, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, packet);
				}
				return;
			case PacketProperty.NatMessage:
				if (NatPunchEnabled)
				{
					NatPunchModule.ProcessMessage(remoteEndPoint, packet);
				}
				return;
			}
			NetPeer actualValue = remoteEndPoint as NetPeer;
			bool flag = actualValue != null || TryGetPeer(remoteEndPoint, out actualValue);
			if (flag && EnableStatistics)
			{
				actualValue.Statistics.IncrementPacketsReceived();
				actualValue.Statistics.AddBytesReceived(size);
			}
			switch (packet.Property)
			{
			case PacketProperty.ConnectRequest:
			{
				NetConnectRequestPacket netConnectRequestPacket = NetConnectRequestPacket.FromData(packet);
				if (netConnectRequestPacket != null)
				{
					ProcessConnectRequest(remoteEndPoint, actualValue, netConnectRequestPacket);
				}
				break;
			}
			case PacketProperty.PeerNotFound:
				if (flag)
				{
					if (actualValue.ConnectionState == ConnectionState.Connected)
					{
						if (packet.Size == 1)
						{
							actualValue.ResetMtu();
							SendRaw(NetConnectAcceptPacket.MakeNetworkChanged(actualValue), remoteEndPoint);
						}
						else if (packet.Size == 2 && packet.RawData[1] == 1)
						{
							DisconnectPeerForce(actualValue, DisconnectReason.PeerNotFound, SocketError.Success, null);
						}
					}
				}
				else
				{
					if (packet.Size <= 1)
					{
						break;
					}
					bool flag2 = false;
					if (AllowPeerAddressChange)
					{
						NetConnectAcceptPacket netConnectAcceptPacket = NetConnectAcceptPacket.FromData(packet);
						if (netConnectAcceptPacket != null && netConnectAcceptPacket.PeerNetworkChanged && netConnectAcceptPacket.PeerId < _peersArray.Length)
						{
							_peersLock.EnterUpgradeableReadLock();
							NetPeer netPeer = _peersArray[netConnectAcceptPacket.PeerId];
							_peersLock.ExitUpgradeableReadLock();
							if (netPeer != null && netPeer.ConnectTime == netConnectAcceptPacket.ConnectionTime && netPeer.ConnectionNum == netConnectAcceptPacket.ConnectionNumber)
							{
								if (netPeer.ConnectionState == ConnectionState.Connected)
								{
									netPeer.InitiateEndPointChange();
									CreateEvent(NetEvent.EType.PeerAddressChanged, netPeer, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
								}
								flag2 = true;
							}
						}
					}
					PoolRecycle(packet);
					if (!flag2)
					{
						NetPacket netPacket = PoolGetWithProperty(PacketProperty.PeerNotFound, 1);
						netPacket.RawData[1] = 1;
						SendRawAndRecycle(netPacket, remoteEndPoint);
					}
				}
				break;
			case PacketProperty.InvalidProtocol:
				if (flag && actualValue.ConnectionState == ConnectionState.Outgoing)
				{
					DisconnectPeerForce(actualValue, DisconnectReason.InvalidProtocol, SocketError.Success, null);
				}
				break;
			case PacketProperty.Disconnect:
				if (flag)
				{
					DisconnectResult disconnectResult = actualValue.ProcessDisconnect(packet);
					if (disconnectResult == DisconnectResult.None)
					{
						PoolRecycle(packet);
						break;
					}
					DisconnectPeerForce(actualValue, (disconnectResult == DisconnectResult.Disconnect) ? DisconnectReason.RemoteConnectionClose : DisconnectReason.ConnectionRejected, SocketError.Success, packet);
				}
				else
				{
					PoolRecycle(packet);
				}
				SendRawAndRecycle(PoolGetWithProperty(PacketProperty.ShutdownOk), remoteEndPoint);
				break;
			case PacketProperty.ConnectAccept:
				if (flag)
				{
					NetConnectAcceptPacket netConnectAcceptPacket2 = NetConnectAcceptPacket.FromData(packet);
					if (netConnectAcceptPacket2 != null && actualValue.ProcessConnectAccept(netConnectAcceptPacket2))
					{
						CreateEvent(NetEvent.EType.Connect, actualValue, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
					}
				}
				break;
			default:
				if (flag)
				{
					actualValue.ProcessPacket(packet);
				}
				else
				{
					SendRawAndRecycle(PoolGetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint);
				}
				break;
			}
		}

		internal void CreateReceiveEvent(NetPacket packet, DeliveryMethod method, byte channelNumber, int headerSize, NetPeer fromPeer)
		{
			if (UnsyncedEvents || UnsyncedReceiveEvent || _manualMode)
			{
				NetEvent netEvent;
				lock (_eventLock)
				{
					netEvent = _netEventPoolHead;
					if (netEvent == null)
					{
						netEvent = new NetEvent(this);
					}
					else
					{
						_netEventPoolHead = netEvent.Next;
					}
				}
				netEvent.Next = null;
				netEvent.Type = NetEvent.EType.Receive;
				netEvent.DataReader.SetSource(packet, headerSize);
				netEvent.Peer = fromPeer;
				netEvent.DeliveryMethod = method;
				netEvent.ChannelNumber = channelNumber;
				ProcessEvent(netEvent);
				return;
			}
			lock (_eventLock)
			{
				NetEvent netEvent = _netEventPoolHead;
				if (netEvent == null)
				{
					netEvent = new NetEvent(this);
				}
				else
				{
					_netEventPoolHead = netEvent.Next;
				}
				netEvent.Next = null;
				netEvent.Type = NetEvent.EType.Receive;
				netEvent.DataReader.SetSource(packet, headerSize);
				netEvent.Peer = fromPeer;
				netEvent.DeliveryMethod = method;
				netEvent.ChannelNumber = channelNumber;
				if (_pendingEventTail == null)
				{
					_pendingEventHead = netEvent;
				}
				else
				{
					_pendingEventTail.Next = netEvent;
				}
				_pendingEventTail = netEvent;
			}
		}

		public void SendToAll(NetDataWriter writer, DeliveryMethod options)
		{
			SendToAll(writer.Data, 0, writer.Length, options);
		}

		public void SendToAll(byte[] data, DeliveryMethod options)
		{
			SendToAll(data, 0, data.Length, options);
		}

		public void SendToAll(byte[] data, int start, int length, DeliveryMethod options)
		{
			SendToAll(data, start, length, 0, options);
		}

		public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options)
		{
			SendToAll(writer.Data, 0, writer.Length, channelNumber, options);
		}

		public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options)
		{
			SendToAll(data, 0, data.Length, channelNumber, options);
		}

		public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options)
		{
			try
			{
				_peersLock.EnterReadLock();
				for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
				{
					netPeer.Send(data, start, length, channelNumber, options);
				}
			}
			finally
			{
				_peersLock.ExitReadLock();
			}
		}

		public void SendToAll(NetDataWriter writer, DeliveryMethod options, NetPeer excludePeer)
		{
			SendToAll(writer.Data, 0, writer.Length, 0, options, excludePeer);
		}

		public void SendToAll(byte[] data, DeliveryMethod options, NetPeer excludePeer)
		{
			SendToAll(data, 0, data.Length, 0, options, excludePeer);
		}

		public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, NetPeer excludePeer)
		{
			SendToAll(data, start, length, 0, options, excludePeer);
		}

		public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
		{
			SendToAll(writer.Data, 0, writer.Length, channelNumber, options, excludePeer);
		}

		public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
		{
			SendToAll(data, 0, data.Length, channelNumber, options, excludePeer);
		}

		public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
		{
			try
			{
				_peersLock.EnterReadLock();
				for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
				{
					if (netPeer != excludePeer)
					{
						netPeer.Send(data, start, length, channelNumber, options);
					}
				}
			}
			finally
			{
				_peersLock.ExitReadLock();
			}
		}

		public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options)
		{
			SendToAll(data, 0, options, null);
		}

		public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options, NetPeer excludePeer)
		{
			SendToAll(data, 0, options, excludePeer);
		}

		public void SendToAll(ReadOnlySpan<byte> data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
		{
			try
			{
				_peersLock.EnterReadLock();
				for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
				{
					if (netPeer != excludePeer)
					{
						netPeer.Send(data, channelNumber, options);
					}
				}
			}
			finally
			{
				_peersLock.ExitReadLock();
			}
		}

		public bool SendUnconnectedMessage(ReadOnlySpan<byte> message, IPEndPoint remoteEndPoint)
		{
			int headerSize = NetPacket.GetHeaderSize(PacketProperty.UnconnectedMessage);
			NetPacket netPacket = PoolGetPacket(message.Length + headerSize);
			netPacket.Property = PacketProperty.UnconnectedMessage;
			message.CopyTo(new Span<byte>(netPacket.RawData, headerSize, message.Length));
			return SendRawAndRecycle(netPacket, remoteEndPoint) > 0;
		}

		public bool Start()
		{
			return Start(0);
		}

		public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port)
		{
			return Start(addressIPv4, addressIPv6, port, manualMode: false);
		}

		public bool Start(string addressIPv4, string addressIPv6, int port)
		{
			IPAddress addressIPv7 = NetUtils.ResolveAddress(addressIPv4);
			IPAddress addressIPv8 = NetUtils.ResolveAddress(addressIPv6);
			return Start(addressIPv7, addressIPv8, port);
		}

		public bool Start(int port)
		{
			return Start(IPAddress.Any, IPAddress.IPv6Any, port);
		}

		public bool StartInManualMode(IPAddress addressIPv4, IPAddress addressIPv6, int port)
		{
			return Start(addressIPv4, addressIPv6, port, manualMode: true);
		}

		public bool StartInManualMode(string addressIPv4, string addressIPv6, int port)
		{
			IPAddress addressIPv7 = NetUtils.ResolveAddress(addressIPv4);
			IPAddress addressIPv8 = NetUtils.ResolveAddress(addressIPv6);
			return StartInManualMode(addressIPv7, addressIPv8, port);
		}

		public bool StartInManualMode(int port)
		{
			return StartInManualMode(IPAddress.Any, IPAddress.IPv6Any, port);
		}

		public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEndPoint)
		{
			return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint);
		}

		public bool SendUnconnectedMessage(NetDataWriter writer, string address, int port)
		{
			IPEndPoint remoteEndPoint = NetUtils.MakeEndPoint(address, port);
			return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint);
		}

		public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint remoteEndPoint)
		{
			return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint);
		}

		public bool SendUnconnectedMessage(byte[] message, int start, int length, IPEndPoint remoteEndPoint)
		{
			NetPacket packet = PoolGetWithData(PacketProperty.UnconnectedMessage, message, start, length);
			return SendRawAndRecycle(packet, remoteEndPoint) > 0;
		}

		public void TriggerUpdate()
		{
			_updateTriggerEvent.Set();
		}

		public void PollEvents(int maxProcessedEvents = 0)
		{
			if (_manualMode)
			{
				if (_udpSocketv4 != null)
				{
					ManualReceive(_udpSocketv4, _bufferEndPointv4, maxProcessedEvents);
				}
				if (_udpSocketv6 != null && _udpSocketv6 != _udpSocketv4)
				{
					ManualReceive(_udpSocketv6, _bufferEndPointv6, maxProcessedEvents);
				}
			}
			else
			{
				if (UnsyncedEvents)
				{
					return;
				}
				NetEvent netEvent;
				lock (_eventLock)
				{
					netEvent = _pendingEventHead;
					_pendingEventHead = null;
					_pendingEventTail = null;
				}
				int num = 0;
				while (netEvent != null)
				{
					NetEvent next = netEvent.Next;
					ProcessEvent(netEvent);
					netEvent = next;
					num++;
					if (num == maxProcessedEvents)
					{
						break;
					}
				}
			}
		}

		public NetPeer Connect(string address, int port, string key)
		{
			return Connect(address, port, NetDataWriter.FromString(key));
		}

		public NetPeer Connect(string address, int port, NetDataWriter connectionData)
		{
			IPEndPoint target;
			try
			{
				target = NetUtils.MakeEndPoint(address, port);
			}
			catch
			{
				CreateEvent(NetEvent.EType.Disconnect, null, null, SocketError.Success, 0, DisconnectReason.UnknownHost, null, DeliveryMethod.Unreliable, 0);
				return null;
			}
			return Connect(target, connectionData);
		}

		public NetPeer Connect(IPEndPoint target, string key)
		{
			return Connect(target, NetDataWriter.FromString(key));
		}

		public NetPeer Connect(IPEndPoint target, NetDataWriter connectionData)
		{
			if (!IsRunning)
			{
				throw new InvalidOperationException("Client is not running");
			}
			lock (_requestsDict)
			{
				if (_requestsDict.ContainsKey(target))
				{
					return null;
				}
				byte connectNum = 0;
				if (TryGetPeer(target, out var actualValue))
				{
					ConnectionState connectionState = actualValue.ConnectionState;
					if (connectionState == ConnectionState.Outgoing || connectionState == ConnectionState.Connected)
					{
						return actualValue;
					}
					connectNum = (byte)((actualValue.ConnectionNum + 1) % 4);
					RemovePeer(actualValue, enableWriteLock: true);
				}
				actualValue = new NetPeer(this, target, GetNextPeerId(), connectNum, connectionData);
				AddPeer(actualValue);
				return actualValue;
			}
		}

		public void Stop()
		{
			Stop(sendDisconnectMessages: true);
		}

		public void Stop(bool sendDisconnectMessages)
		{
			if (IsRunning)
			{
				for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
				{
					netPeer.Shutdown(null, 0, 0, !sendDisconnectMessages);
				}
				CloseSocket();
				_updateTriggerEvent.Set();
				if (!_manualMode)
				{
					_logicThread.Join();
					_logicThread = null;
				}
				ClearPeerSet();
				_peerIds = new ConcurrentQueue<int>();
				_lastPeerId = 0;
				_connectedPeersCount = 0L;
				_pendingEventHead = null;
				_pendingEventTail = null;
			}
		}

		[Conditional("DEBUG")]
		private void ClearPingSimulationList()
		{
			lock (_pingSimulationList)
			{
				_pingSimulationList.Clear();
			}
		}

		public int GetPeersCount(ConnectionState peerState)
		{
			int num = 0;
			_peersLock.EnterReadLock();
			for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
			{
				if ((netPeer.ConnectionState & peerState) != 0)
				{
					num++;
				}
			}
			_peersLock.ExitReadLock();
			return num;
		}

		public void GetPeersNonAlloc(List<NetPeer> peers, ConnectionState peerState)
		{
			peers.Clear();
			_peersLock.EnterReadLock();
			for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
			{
				if ((netPeer.ConnectionState & peerState) != 0)
				{
					peers.Add(netPeer);
				}
			}
			_peersLock.ExitReadLock();
		}

		public void DisconnectAll()
		{
			DisconnectAll(null, 0, 0);
		}

		public void DisconnectAll(byte[] data, int start, int count)
		{
			_peersLock.EnterReadLock();
			for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
			{
				DisconnectPeer(netPeer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, start, count, null);
			}
			_peersLock.ExitReadLock();
		}

		public void DisconnectPeerForce(NetPeer peer)
		{
			DisconnectPeerForce(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, null);
		}

		public void DisconnectPeer(NetPeer peer)
		{
			DisconnectPeer(peer, null, 0, 0);
		}

		public void DisconnectPeer(NetPeer peer, byte[] data)
		{
			DisconnectPeer(peer, data, 0, data.Length);
		}

		public void DisconnectPeer(NetPeer peer, NetDataWriter writer)
		{
			DisconnectPeer(peer, writer.Data, 0, writer.Length);
		}

		public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count)
		{
			DisconnectPeer(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, start, count, null);
		}

		public void CreateNtpRequest(IPEndPoint endPoint)
		{
			_ntpRequests.TryAdd(endPoint, new NtpRequest(endPoint));
		}

		public void CreateNtpRequest(string ntpServerAddress, int port)
		{
			IPEndPoint iPEndPoint = NetUtils.MakeEndPoint(ntpServerAddress, port);
			_ntpRequests.TryAdd(iPEndPoint, new NtpRequest(iPEndPoint));
		}

		public void CreateNtpRequest(string ntpServerAddress)
		{
			IPEndPoint iPEndPoint = NetUtils.MakeEndPoint(ntpServerAddress, 123);
			_ntpRequests.TryAdd(iPEndPoint, new NtpRequest(iPEndPoint));
		}

		public NetPeerEnumerator GetEnumerator()
		{
			return new NetPeerEnumerator(_headPeer);
		}

		IEnumerator<NetPeer> IEnumerable<NetPeer>.GetEnumerator()
		{
			return new NetPeerEnumerator(_headPeer);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new NetPeerEnumerator(_headPeer);
		}

		private static int HashSetGetPrime(int min)
		{
			int[] primes = Primes;
			foreach (int num in primes)
			{
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
			static bool IsPrime(int candidate)
			{
				if (((uint)candidate & (true ? 1u : 0u)) != 0)
				{
					int num2 = (int)Math.Sqrt(candidate);
					for (int k = 3; k <= num2; k += 2)
					{
						if (candidate % k == 0)
						{
							return false;
						}
					}
					return true;
				}
				return candidate == 2;
			}
		}

		private void ClearPeerSet()
		{
			_peersLock.EnterWriteLock();
			_headPeer = null;
			if (_lastIndex > 0)
			{
				Array.Clear(_slots, 0, _lastIndex);
				Array.Clear(_buckets, 0, _buckets.Length);
				_lastIndex = 0;
				_count = 0;
				_freeList = -1;
			}
			_peersArray = new NetPeer[32];
			_peersLock.ExitWriteLock();
		}

		private bool ContainsPeer(NetPeer item)
		{
			if (item == null)
			{
				NetDebug.WriteError($"Contains peer null: {item}");
				return false;
			}
			if (_buckets != null)
			{
				int num = item.GetHashCode() & 0x7FFFFFFF;
				for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next)
				{
					if (_slots[num2].HashCode == num && _slots[num2].Value.Equals(item))
					{
						return true;
					}
				}
			}
			return false;
		}

		public NetPeer GetPeerById(int id)
		{
			if (id < 0 || id >= _peersArray.Length)
			{
				return null;
			}
			return _peersArray[id];
		}

		public bool TryGetPeerById(int id, out NetPeer peer)
		{
			peer = GetPeerById(id);
			return peer != null;
		}

		private void AddPeer(NetPeer peer)
		{
			if (peer == null)
			{
				NetDebug.WriteError($"Add peer null: {peer}");
				return;
			}
			_peersLock.EnterWriteLock();
			if (_headPeer != null)
			{
				peer.NextPeer = _headPeer;
				_headPeer.PrevPeer = peer;
			}
			_headPeer = peer;
			AddPeerToSet(peer);
			if (peer.Id >= _peersArray.Length)
			{
				int num = _peersArray.Length * 2;
				while (peer.Id >= num)
				{
					num *= 2;
				}
				Array.Resize(ref _peersArray, num);
			}
			_peersArray[peer.Id] = peer;
			_peersLock.ExitWriteLock();
		}

		private void RemovePeer(NetPeer peer, bool enableWriteLock)
		{
			if (enableWriteLock)
			{
				_peersLock.EnterWriteLock();
			}
			if (!RemovePeerFromSet(peer))
			{
				if (enableWriteLock)
				{
					_peersLock.ExitWriteLock();
				}
				return;
			}
			if (peer == _headPeer)
			{
				_headPeer = peer.NextPeer;
			}
			if (peer.PrevPeer != null)
			{
				peer.PrevPeer.NextPeer = peer.NextPeer;
			}
			if (peer.NextPeer != null)
			{
				peer.NextPeer.PrevPeer = peer.PrevPeer;
			}
			peer.PrevPeer = null;
			_peersArray[peer.Id] = null;
			_peerIds.Enqueue(peer.Id);
			if (enableWriteLock)
			{
				_peersLock.ExitWriteLock();
			}
		}

		private bool RemovePeerFromSet(NetPeer peer)
		{
			if (_buckets == null || peer == null)
			{
				return false;
			}
			int num = peer.GetHashCode() & 0x7FFFFFFF;
			int num2 = num % _buckets.Length;
			int num3 = -1;
			for (int num4 = _buckets[num2] - 1; num4 >= 0; num4 = _slots[num4].Next)
			{
				if (_slots[num4].HashCode == num && _slots[num4].Value.Equals(peer))
				{
					if (num3 < 0)
					{
						_buckets[num2] = _slots[num4].Next + 1;
					}
					else
					{
						_slots[num3].Next = _slots[num4].Next;
					}
					_slots[num4].HashCode = -1;
					_slots[num4].Value = null;
					_slots[num4].Next = _freeList;
					_count--;
					if (_count == 0)
					{
						_lastIndex = 0;
						_freeList = -1;
					}
					else
					{
						_freeList = num4;
					}
					return true;
				}
				num3 = num4;
			}
			return false;
		}

		private bool TryGetPeer(IPEndPoint endPoint, out NetPeer actualValue)
		{
			if (_buckets != null)
			{
				int num = endPoint.GetHashCode() & 0x7FFFFFFF;
				_peersLock.EnterReadLock();
				for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next)
				{
					if (_slots[num2].HashCode == num && _slots[num2].Value.Equals(endPoint))
					{
						actualValue = _slots[num2].Value;
						_peersLock.ExitReadLock();
						return true;
					}
				}
				_peersLock.ExitReadLock();
			}
			actualValue = null;
			return false;
		}

		private bool TryGetPeer(SocketAddress saddr, out NetPeer actualValue)
		{
			if (_buckets != null)
			{
				int num = saddr.GetHashCode() & 0x7FFFFFFF;
				_peersLock.EnterReadLock();
				for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next)
				{
					if (_slots[num2].HashCode == num && _slots[num2].Value.Serialize().Equals(saddr))
					{
						actualValue = _slots[num2].Value;
						_peersLock.ExitReadLock();
						return true;
					}
				}
				_peersLock.ExitReadLock();
			}
			actualValue = null;
			return false;
		}

		private bool AddPeerToSet(NetPeer value)
		{
			if (_buckets == null)
			{
				int num = HashSetGetPrime(0);
				_buckets = new int[num];
				_slots = new Slot[num];
			}
			int num2 = value.GetHashCode() & 0x7FFFFFFF;
			int num3 = num2 % _buckets.Length;
			for (int num4 = _buckets[num2 % _buckets.Length] - 1; num4 >= 0; num4 = _slots[num4].Next)
			{
				if (_slots[num4].HashCode == num2 && _slots[num4].Value.Equals(value))
				{
					return false;
				}
			}
			int num5;
			if (_freeList >= 0)
			{
				num5 = _freeList;
				_freeList = _slots[num5].Next;
			}
			else
			{
				if (_lastIndex == _slots.Length)
				{
					int num6 = 2 * _count;
					num6 = (((uint)num6 > 2147483587u && 2147483587 > _count) ? 2147483587 : HashSetGetPrime(num6));
					Slot[] array = new Slot[num6];
					Array.Copy(_slots, 0, array, 0, _lastIndex);
					_buckets = new int[num6];
					for (int i = 0; i < _lastIndex; i++)
					{
						int num7 = array[i].HashCode % num6;
						array[i].Next = _buckets[num7] - 1;
						_buckets[num7] = i + 1;
					}
					_slots = array;
					num3 = num2 % _buckets.Length;
				}
				num5 = _lastIndex;
				_lastIndex++;
			}
			_slots[num5].HashCode = num2;
			_slots[num5].Value = value;
			_slots[num5].Next = _buckets[num3] - 1;
			_buckets[num3] = num5 + 1;
			_count++;
			return true;
		}

		private NetPacket PoolGetWithData(PacketProperty property, byte[] data, int start, int length)
		{
			int headerSize = NetPacket.GetHeaderSize(property);
			NetPacket netPacket = PoolGetPacket(length + headerSize);
			netPacket.Property = property;
			Buffer.BlockCopy(data, start, netPacket.RawData, headerSize, length);
			return netPacket;
		}

		private NetPacket PoolGetWithProperty(PacketProperty property, int size)
		{
			NetPacket netPacket = PoolGetPacket(size + NetPacket.GetHeaderSize(property));
			netPacket.Property = property;
			return netPacket;
		}

		private NetPacket PoolGetWithProperty(PacketProperty property)
		{
			NetPacket netPacket = PoolGetPacket(NetPacket.GetHeaderSize(property));
			netPacket.Property = property;
			return netPacket;
		}

		internal NetPacket PoolGetPacket(int size)
		{
			if (size > NetConstants.MaxPacketSize)
			{
				return new NetPacket(size);
			}
			NetPacket poolHead;
			lock (_poolLock)
			{
				poolHead = _poolHead;
				if (poolHead == null)
				{
					return new NetPacket(size);
				}
				_poolHead = _poolHead.Next;
				_poolCount--;
			}
			poolHead.Size = size;
			if (poolHead.RawData.Length < size)
			{
				poolHead.RawData = new byte[size];
			}
			return poolHead;
		}

		internal void PoolRecycle(NetPacket packet)
		{
			if (packet.RawData.Length > NetConstants.MaxPacketSize || _poolCount >= PacketPoolSize)
			{
				return;
			}
			packet.RawData[0] = 0;
			lock (_poolLock)
			{
				packet.Next = _poolHead;
				_poolHead = packet;
				_poolCount++;
			}
		}

		static NetManager()
		{
			Primes = new int[72]
			{
				3, 7, 11, 17, 23, 29, 37, 47, 59, 71,
				89, 107, 131, 163, 197, 239, 293, 353, 431, 521,
				631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371,
				4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023,
				25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363,
				156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403,
				968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559,
				5999471, 7199369
			};
			MulticastAddressV6 = IPAddress.Parse("ff02::1");
			IPv6Support = Socket.OSSupportsIPv6;
		}

		private bool ProcessError(SocketException ex)
		{
			switch (ex.SocketErrorCode)
			{
			case SocketError.NotConnected:
				NotConnected = true;
				return true;
			case SocketError.OperationAborted:
			case SocketError.Interrupted:
			case SocketError.NotSocket:
				return true;
			default:
				NetDebug.WriteError($"[R]Error code: {ex.SocketErrorCode} - {ex}");
				CreateEvent(NetEvent.EType.Error, null, null, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
				break;
			case SocketError.WouldBlock:
			case SocketError.MessageSize:
			case SocketError.NetworkReset:
			case SocketError.ConnectionReset:
			case SocketError.TimedOut:
				break;
			}
			return false;
		}

		private void ManualReceive(Socket socket, EndPoint bufferEndPoint, int maxReceive)
		{
			try
			{
				int num = 0;
				while (socket.Available > 0)
				{
					ReceiveFrom(socket, ref bufferEndPoint);
					num++;
					if (num == maxReceive)
					{
						break;
					}
				}
			}
			catch (SocketException ex)
			{
				ProcessError(ex);
			}
			catch (ObjectDisposedException)
			{
			}
			catch (Exception ex3)
			{
				NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex3);
			}
		}

		private void NativeReceiveLogic()
		{
			IntPtr handle = _udpSocketv4.Handle;
			IntPtr s2 = _udpSocketv6?.Handle ?? IntPtr.Zero;
			byte[] address2 = new byte[16];
			byte[] address3 = new byte[28];
			IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Any, 0);
			List<Socket> list = new List<Socket>(2);
			Socket udpSocketv = _udpSocketv4;
			Socket udpSocketv2 = _udpSocketv6;
			NetPacket packet = PoolGetPacket(NetConstants.MaxPacketSize);
			while (IsRunning)
			{
				try
				{
					if (udpSocketv2 == null)
					{
						if (!NativeReceiveFrom(handle, address2))
						{
							break;
						}
						continue;
					}
					bool flag = false;
					if (udpSocketv.Available != 0 || list.Contains(udpSocketv))
					{
						if (!NativeReceiveFrom(handle, address2))
						{
							break;
						}
						flag = true;
					}
					if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2))
					{
						if (!NativeReceiveFrom(s2, address3))
						{
							break;
						}
						flag = true;
					}
					list.Clear();
					if (!flag)
					{
						list.Add(udpSocketv);
						list.Add(udpSocketv2);
						Socket.Select(list, null, null, 500000);
					}
				}
				catch (SocketException ex)
				{
					if (ProcessError(ex))
					{
						break;
					}
				}
				catch (ObjectDisposedException)
				{
					break;
				}
				catch (ThreadAbortException)
				{
					break;
				}
				catch (Exception ex4)
				{
					NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex4);
				}
			}
			bool NativeReceiveFrom(IntPtr s, byte[] address)
			{
				int socketAddressSize = address.Length;
				packet.Size = NativeSocket.RecvFrom(s, packet.RawData, NetConstants.MaxPacketSize, address, ref socketAddressSize);
				if (packet.Size == 0)
				{
					return true;
				}
				if (packet.Size == -1)
				{
					return !ProcessError(new SocketException((int)NativeSocket.GetSocketError()));
				}
				short num = (short)((address[1] << 8) | address[0]);
				tempEndPoint.Port = (ushort)((address[2] << 8) | address[3]);
				if ((NativeSocket.UnixMode && num == 10) || (!NativeSocket.UnixMode && num == 23))
				{
					uint num2 = (uint)((address[27] << 24) + (address[26] << 16) + (address[25] << 8) + address[24]);
					tempEndPoint.Address = new IPAddress(new ReadOnlySpan<byte>(address, 8, 16), num2);
				}
				else
				{
					long newAddress = (uint)((address[4] & 0xFF) | ((address[5] << 8) & 0xFF00) | ((address[6] << 16) & 0xFF0000) | (address[7] << 24));
					tempEndPoint.Address = new IPAddress(newAddress);
				}
				if (TryGetPeer(tempEndPoint, out var actualValue))
				{
					OnMessageReceived(packet, actualValue);
				}
				else
				{
					OnMessageReceived(packet, tempEndPoint);
					tempEndPoint = new IPEndPoint(IPAddress.Any, 0);
				}
				packet = PoolGetPacket(NetConstants.MaxPacketSize);
				return true;
			}
		}

		private void ReceiveFrom(Socket s, ref EndPoint bufferEndPoint)
		{
			NetPacket netPacket = PoolGetPacket(NetConstants.MaxPacketSize);
			netPacket.Size = s.ReceiveFrom(netPacket.RawData, 0, NetConstants.MaxPacketSize, SocketFlags.None, ref bufferEndPoint);
			OnMessageReceived(netPacket, (IPEndPoint)bufferEndPoint);
		}

		private void ReceiveLogic()
		{
			EndPoint bufferEndPoint = new IPEndPoint(IPAddress.Any, 0);
			EndPoint bufferEndPoint2 = new IPEndPoint(IPAddress.IPv6Any, 0);
			List<Socket> list = new List<Socket>(2);
			Socket udpSocketv = _udpSocketv4;
			Socket udpSocketv2 = _udpSocketv6;
			while (IsRunning)
			{
				try
				{
					if (udpSocketv2 == null)
					{
						if (udpSocketv.Available != 0 || udpSocketv.Poll(500000, SelectMode.SelectRead))
						{
							ReceiveFrom(udpSocketv, ref bufferEndPoint);
						}
						continue;
					}
					bool flag = false;
					if (udpSocketv.Available != 0 || list.Contains(udpSocketv))
					{
						ReceiveFrom(udpSocketv, ref bufferEndPoint);
						flag = true;
					}
					if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2))
					{
						ReceiveFrom(udpSocketv2, ref bufferEndPoint2);
						flag = true;
					}
					list.Clear();
					if (!flag)
					{
						list.Add(udpSocketv);
						list.Add(udpSocketv2);
						Socket.Select(list, null, null, 500000);
					}
				}
				catch (SocketException ex)
				{
					if (ProcessError(ex))
					{
						break;
					}
				}
				catch (ObjectDisposedException)
				{
					break;
				}
				catch (ThreadAbortException)
				{
					break;
				}
				catch (Exception ex4)
				{
					NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex4);
				}
			}
		}

		public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool manualMode)
		{
			if (IsRunning && !NotConnected)
			{
				return false;
			}
			NotConnected = false;
			_manualMode = manualMode;
			UseNativeSockets = UseNativeSockets && NativeSocket.IsSupported;
			_udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			if (!BindSocket(_udpSocketv4, new IPEndPoint(addressIPv4, port)))
			{
				return false;
			}
			LocalPort = ((IPEndPoint)_udpSocketv4.LocalEndPoint).Port;
			IsRunning = true;
			if (_manualMode)
			{
				_bufferEndPointv4 = new IPEndPoint(IPAddress.Any, 0);
			}
			if (IPv6Support && IPv6Enabled)
			{
				_udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
				if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort)))
				{
					if (_manualMode)
					{
						_bufferEndPointv6 = new IPEndPoint(IPAddress.IPv6Any, 0);
					}
				}
				else
				{
					_udpSocketv6 = null;
				}
			}
			if (!manualMode)
			{
				ThreadStart start = ReceiveLogic;
				if (UseNativeSockets)
				{
					start = NativeReceiveLogic;
				}
				_receiveThread = new Thread(start)
				{
					Name = $"ReceiveThread({LocalPort})",
					IsBackground = true
				};
				_receiveThread.Start();
				if (_logicThread == null)
				{
					_logicThread = new Thread(UpdateLogic)
					{
						Name = "LogicThread",
						IsBackground = true
					};
					_logicThread.Start();
				}
			}
			return true;
		}

		private bool BindSocket(Socket socket, IPEndPoint ep)
		{
			socket.ReceiveTimeout = 500;
			socket.SendTimeout = 500;
			socket.ReceiveBufferSize = 1048576;
			socket.SendBufferSize = 1048576;
			socket.Blocking = true;
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				try
				{
					socket.IOControl(-1744830452, new byte[1], null);
				}
				catch
				{
				}
			}
			try
			{
				socket.ExclusiveAddressUse = !ReuseAddress;
				socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, ReuseAddress);
				socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, DontRoute);
			}
			catch
			{
			}
			if (ep.AddressFamily == AddressFamily.InterNetwork)
			{
				Ttl = 255;
				try
				{
					socket.EnableBroadcast = true;
				}
				catch (SocketException ex)
				{
					NetDebug.WriteError($"[B]Broadcast error: {ex.SocketErrorCode}");
				}
				if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
				{
					try
					{
						socket.DontFragment = true;
					}
					catch (SocketException ex2)
					{
						NetDebug.WriteError($"[B]DontFragment error: {ex2.SocketErrorCode}");
					}
				}
			}
			try
			{
				socket.Bind(ep);
				if (ep.AddressFamily == AddressFamily.InterNetworkV6)
				{
					try
					{
						socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(MulticastAddressV6));
					}
					catch (Exception)
					{
					}
				}
			}
			catch (SocketException ex4)
			{
				switch (ex4.SocketErrorCode)
				{
				case SocketError.AddressAlreadyInUse:
					if (socket.AddressFamily == AddressFamily.InterNetworkV6)
					{
						try
						{
							socket.DualMode = false;
							socket.Bind(ep);
						}
						catch (SocketException ex5)
						{
							NetDebug.WriteError($"[B]Bind exception: {ex5}, errorCode: {ex5.SocketErrorCode}");
							return false;
						}
						return true;
					}
					break;
				case SocketError.AddressFamilyNotSupported:
					return true;
				}
				NetDebug.WriteError($"[B]Bind exception: {ex4}, errorCode: {ex4.SocketErrorCode}");
				return false;
			}
			return true;
		}

		internal int SendRawAndRecycle(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			int result = SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint);
			PoolRecycle(packet);
			return result;
		}

		internal int SendRaw(NetPacket packet, IPEndPoint remoteEndPoint)
		{
			return SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint);
		}

		internal unsafe int SendRaw(byte[] message, int start, int length, IPEndPoint remoteEndPoint)
		{
			if (!IsRunning)
			{
				return 0;
			}
			NetPacket netPacket = null;
			if (_extraPacketLayer != null)
			{
				netPacket = PoolGetPacket(length + _extraPacketLayer.ExtraPacketSizeForLayer);
				Buffer.BlockCopy(message, start, netPacket.RawData, 0, length);
				start = 0;
				_extraPacketLayer.ProcessOutBoundPacket(ref remoteEndPoint, ref netPacket.RawData, ref start, ref length);
				message = netPacket.RawData;
			}
			Socket socket = _udpSocketv4;
			if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support)
			{
				socket = _udpSocketv6;
				if (socket == null)
				{
					return 0;
				}
			}
			int num;
			try
			{
				if (UseNativeSockets && remoteEndPoint is NetPeer netPeer)
				{
					fixed (byte* pinnedBuffer = &message[start])
					{
						num = NativeSocket.SendTo(socket.Handle, pinnedBuffer, length, netPeer.NativeAddress, netPeer.NativeAddress.Length);
					}
					if (num == -1)
					{
						throw NativeSocket.GetSocketException();
					}
				}
				else
				{
					num = socket.SendTo(message, start, length, SocketFlags.None, remoteEndPoint);
				}
			}
			catch (SocketException ex)
			{
				switch (ex.SocketErrorCode)
				{
				case SocketError.Interrupted:
				case SocketError.NoBufferSpaceAvailable:
					return 0;
				case SocketError.MessageSize:
					return 0;
				case SocketError.NetworkUnreachable:
				case SocketError.HostUnreachable:
					if (DisconnectOnUnreachable && remoteEndPoint is NetPeer peer)
					{
						DisconnectPeerForce(peer, (ex.SocketErrorCode == SocketError.HostUnreachable) ? DisconnectReason.HostUnreachable : DisconnectReason.NetworkUnreachable, ex.SocketErrorCode, null);
					}
					CreateEvent(NetEvent.EType.Error, null, remoteEndPoint, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
					return -1;
				case SocketError.Shutdown:
					CreateEvent(NetEvent.EType.Error, null, remoteEndPoint, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0);
					return -1;
				default:
					NetDebug.WriteError($"[S] {ex}");
					return -1;
				}
			}
			catch (Exception value)
			{
				NetDebug.WriteError($"[S] {value}");
				return 0;
			}
			finally
			{
				if (netPacket != null)
				{
					PoolRecycle(netPacket);
				}
			}
			if (num <= 0)
			{
				return 0;
			}
			if (EnableStatistics)
			{
				Statistics.IncrementPacketsSent();
				Statistics.AddBytesSent(length);
			}
			return num;
		}

		public bool SendBroadcast(NetDataWriter writer, int port)
		{
			return SendBroadcast(writer.Data, 0, writer.Length, port);
		}

		public bool SendBroadcast(byte[] data, int port)
		{
			return SendBroadcast(data, 0, data.Length, port);
		}

		public bool SendBroadcast(byte[] data, int start, int length, int port)
		{
			if (!IsRunning)
			{
				return false;
			}
			NetPacket netPacket;
			if (_extraPacketLayer != null)
			{
				int headerSize = NetPacket.GetHeaderSize(PacketProperty.Broadcast);
				netPacket = PoolGetPacket(headerSize + length + _extraPacketLayer.ExtraPacketSizeForLayer);
				netPacket.Property = PacketProperty.Broadcast;
				Buffer.BlockCopy(data, start, netPacket.RawData, headerSize, length);
				int offset = 0;
				int length2 = length + headerSize;
				IPEndPoint endPoint = null;
				_extraPacketLayer.ProcessOutBoundPacket(ref endPoint, ref netPacket.RawData, ref offset, ref length2);
			}
			else
			{
				netPacket = PoolGetWithData(PacketProperty.Broadcast, data, start, length);
			}
			bool flag = false;
			bool flag2 = false;
			try
			{
				flag = _udpSocketv4.SendTo(netPacket.RawData, 0, netPacket.Size, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port)) > 0;
				if (_udpSocketv6 != null)
				{
					flag2 = _udpSocketv6.SendTo(netPacket.RawData, 0, netPacket.Size, SocketFlags.None, new IPEndPoint(MulticastAddressV6, port)) > 0;
				}
			}
			catch (SocketException ex)
			{
				if (ex.SocketErrorCode == SocketError.HostUnreachable)
				{
					return flag;
				}
				NetDebug.WriteError($"[S][MCAST] {ex}");
				return flag;
			}
			catch (Exception value)
			{
				NetDebug.WriteError($"[S][MCAST] {value}");
				return flag;
			}
			finally
			{
				PoolRecycle(netPacket);
			}
			return flag || flag2;
		}

		private void CloseSocket()
		{
			IsRunning = false;
			_udpSocketv4?.Close();
			_udpSocketv6?.Close();
			_udpSocketv4 = null;
			_udpSocketv6 = null;
			if (_receiveThread != null && _receiveThread != Thread.CurrentThread)
			{
				_receiveThread.Join();
			}
			_receiveThread = null;
		}
	}
	internal enum PacketProperty : byte
	{
		Unreliable,
		Channeled,
		Ack,
		Ping,
		Pong,
		ConnectRequest,
		ConnectAccept,
		Disconnect,
		UnconnectedMessage,
		MtuCheck,
		MtuOk,
		Broadcast,
		Merged,
		ShutdownOk,
		PeerNotFound,
		InvalidProtocol,
		NatMessage,
		Empty
	}
	internal sealed class NetPacket
	{
		private static readonly int PropertiesCount;

		private static readonly int[] HeaderSizes;

		public byte[] RawData;

		public int Size;

		public object UserData;

		public NetPacket Next;

		public PacketProperty Property
		{
			get
			{
				return (PacketProperty)(RawData[0] & 0x1Fu);
			}
			set
			{
				RawData[0] = (byte)((RawData[0] & 0xE0u) | (uint)value);
			}
		}

		public byte ConnectionNumber
		{
			get
			{
				return (byte)((RawData[0] & 0x60) >> 5);
			}
			set
			{
				RawData[0] = (byte)((RawData[0] & 0x9Fu) | (uint)(value << 5));
			}
		}

		public ushort Sequence
		{
			get
			{
				return BitConverter.ToUInt16(RawData, 1);
			}
			set
			{
				FastBitConverter.GetBytes(RawData, 1, value);
			}
		}

		public bool IsFragmented => (RawData[0] & 0x80) != 0;

		public byte ChannelId
		{
			get
			{
				return RawData[3];
			}
			set
			{
				RawData[3] = value;
			}
		}

		public ushort FragmentId
		{
			get
			{
				return BitConverter.ToUInt16(RawData, 4);
			}
			set
			{
				FastBitConverter.GetBytes(RawData, 4, value);
			}
		}

		public ushort FragmentPart
		{
			get
			{
				return BitConverter.ToUInt16(RawData, 6);
			}
			set
			{
				FastBitConverter.GetBytes(RawData, 6, value);
			}
		}

		public ushort FragmentsTotal
		{
			get
			{
				return BitConverter.ToUInt16(RawData, 8);
			}
			set
			{
				FastBitConverter.GetBytes(RawData, 8, value);
			}
		}

		static NetPacket()
		{
			PropertiesCount = Enum.GetValues(typeof(PacketProperty)).Length;
			HeaderSizes = NetUtils.AllocatePinnedUninitializedArray<int>(PropertiesCount);
			for (int i = 0; i < HeaderSizes.Length; i++)
			{
				switch ((PacketProperty)(byte)i)
				{
				case PacketProperty.Channeled:
				case PacketProperty.Ack:
					HeaderSizes[i] = 4;
					break;
				case PacketProperty.Ping:
					HeaderSizes[i] = 3;
					break;
				case PacketProperty.ConnectRequest:
					HeaderSizes[i] = 18;
					break;
				case PacketProperty.ConnectAccept:
					HeaderSizes[i] = 15;
					break;
				case PacketProperty.Disconnect:
					HeaderSizes[i] = 9;
					break;
				case PacketProperty.Pong:
					HeaderSizes[i] = 11;
					break;
				default:
					HeaderSizes[i] = 1;
					break;
				}
			}
		}

		public void MarkFragmented()
		{
			RawData[0] |= 128;
		}

		public NetPacket(int size)
		{
			RawData = new byte[size];
			Size = size;
		}

		public NetPacket(PacketProperty property, int size)
		{
			size += GetHeaderSize(property);
			RawData = new byte[size];
			Property = property;
			Size = size;
		}

		public static int GetHeaderSize(PacketProperty property)
		{
			return HeaderSizes[(uint)property];
		}

		public int GetHeaderSize()
		{
			return HeaderSizes[RawData[0] & 0x1F];
		}

		public bool Verify()
		{
			byte b = (byte)(RawData[0] & 0x1Fu);
			if (b >= PropertiesCount)
			{
				return false;
			}
			int num = HeaderSizes[b];
			bool flag = (RawData[0] & 0x80) != 0;
			if (Size >= num)
			{
				if (flag)
				{
					return Size >= num + 6;
				}
				return true;
			}
			return false;
		}

		public static implicit operator Span<byte>(NetPacket p)
		{
			return new Span<byte>(p.RawData, 0, p.Size);
		}
	}
	[Flags]
	public enum ConnectionState : byte
	{
		Outgoing = 2,
		Connected = 4,
		ShutdownRequested = 8,
		Disconnected = 0x10,
		EndPointChange = 0x20,
		Any = 0x2E
	}
	internal enum ConnectRequestResult
	{
		None,
		P2PLose,
		Reconnection,
		NewConnection
	}
	internal enum DisconnectResult
	{
		None,
		Reject,
		Disconnect
	}
	internal enum ShutdownResult
	{
		None,
		Success,
		WasConnected
	}
	public class NetPeer : IPEndPoint
	{
		private class IncomingFragments
		{
			public NetPacket[] Fragments;

			public int ReceivedCount;

			public int TotalSize;

			public byte ChannelId;
		}

		private int _rtt;

		private int _avgRtt;

		private int _rttCount;

		private double _resendDelay = 27.0;

		private float _pingSendTimer;

		private float _rttResetTimer;

		private readonly Stopwatch _pingTimer = new Stopwatch();

		private volatile float _timeSinceLastPacket;

		private long _remoteDelta;

		private readonly object _shutdownLock = new object();

		internal volatile NetPeer NextPeer;

		internal NetPeer PrevPeer;

		private NetPacket[] _unreliableSecondQueue;

		private NetPacket[] _unreliableChannel;

		private int _unreliablePendingCount;

		private readonly object _unreliableChannelLock = new object();

		private readonly ConcurrentQueue<BaseChannel> _channelSendQueue;

		private readonly BaseChannel[] _channels;

		private int _mtu;

		private int _mtuIdx;

		private bool _finishMtu;

		private float _mtuCheckTimer;

		private int _mtuCheckAttempts;

		private const int MtuCheckDelay = 1000;

		private const int MaxMtuCheckAttempts = 4;

		private readonly object _mtuMutex = new object();

		private int _fragmentId;

		private readonly Dictionary<ushort, IncomingFragments> _holdedFragments;

		private readonly Dictionary<ushort, ushort> _deliveredFragments;

		private readonly NetPacket _mergeData;

		private int _mergePos;

		private int _mergeCount;

		private int _connectAttempts;

		private float _connectTimer;

		private long _connectTime;

		private byte _connectNum;

		private ConnectionState _connectionState;

		private NetPacket _shutdownPacket;

		private const int ShutdownDelay = 300;

		private float _shutdownTimer;

		private readonly NetPacket _pingPacket;

		private readonly NetPacket _pongPacket;

		private readonly NetPacket _connectRequestPacket;

		private readonly NetPacket _connectAcceptPacket;

		public readonly NetManager NetManager;

		public readonly int Id;

		public object Tag;

		public readonly NetStatistics Statistics;

		private SocketAddress _cachedSocketAddr;

		private int _cachedHashCode;

		internal byte[] NativeAddress;

		internal byte ConnectionNum
		{
			get
			{
				return _connectNum;
			}
			private set
			{
				_connectNum = value;
				_mergeData.ConnectionNumber = value;
				_pingPacket.ConnectionNumber = value;
				_pongPacket.ConnectionNumber = value;
			}
		}

		public ConnectionState ConnectionState => _connectionState;

		internal long ConnectTime => _connectTime;

		public int RemoteId { get; private set; }

		public int Ping => _avgRtt / 2;

		public int RoundTripTime => _avgRtt;

		public int Mtu => _mtu;

		public long RemoteTimeDelta => _remoteDelta;

		public DateTime RemoteUtcTime => new DateTime(DateTime.UtcNow.Ticks + _remoteDelta);

		public float TimeSinceLastPacket => _timeSinceLastPacket;

		internal double ResendDelay => _resendDelay;

		public override SocketAddress Serialize()
		{
			return _cachedSocketAddr;
		}

		public override int GetHashCode()
		{
			return _cachedHashCode;
		}

		internal NetPeer(NetManager netManager, IPEndPoint remoteEndPoint, int id)
			: base(remoteEndPoint.Address, remoteEndPoint.Port)
		{
			Id = id;
			Statistics = new NetStatistics();
			NetManager = netManager;
			_cachedSocketAddr = base.Serialize();
			if (NetManager.UseNativeSockets)
			{
				NativeAddress = new byte[_cachedSocketAddr.Size];
				for (int i = 0; i < _cachedSocketAddr.Size; i++)
				{
					NativeAddress[i] = _cachedSocketAddr[i];
				}
			}
			_cachedHashCode = base.GetHashCode();
			ResetMtu();
			_connectionState = ConnectionState.Connected;
			_mergeData = new NetPacket(PacketProperty.Merged, NetConstants.MaxPacketSize);
			_pongPacket = new NetPacket(PacketProperty.Pong, 0);
			_pingPacket = new NetPacket(PacketProperty.Ping, 0)
			{
				Sequence = 1
			};
			_unreliableSecondQueue = new NetPacket[8];
			_unreliableChannel = new NetPacket[8];
			_holdedFragments = new Dictionary<ushort, IncomingFragments>();
			_deliveredFragments = new Dictionary<ushort, ushort>();
			_channels = new BaseChannel[netManager.ChannelsCount * 4];
			_channelSendQueue = new ConcurrentQueue<BaseChannel>();
		}

		internal void InitiateEndPointChange()
		{
			ResetMtu();
			_connectionState = ConnectionState.EndPointChange;
		}

		internal void FinishEndPointChange(IPEndPoint newEndPoint)
		{
			if (_connectionState != ConnectionState.EndPointChange)
			{
				return;
			}
			_connectionState = ConnectionState.Connected;
			base.Address = newEndPoint.Address;
			base.Port = newEndPoint.Port;
			if (NetManager.UseNativeSockets)
			{
				NativeAddress = new byte[_cachedSocketAddr.Size];
				for (int i = 0; i < _cachedSocketAddr.Size; i++)
				{
					NativeAddress[i] = _cachedSocketAddr[i];
				}
			}
			_cachedSocketAddr = base.Serialize();
			_cachedHashCode = base.GetHashCode();
		}

		internal void ResetMtu()
		{
			_finishMtu = !NetManager.MtuDiscovery;
			if (NetManager.MtuOverride > 0)
			{
				OverrideMtu(NetManager.MtuOverride);
			}
			else
			{
				SetMtu(0);
			}
		}

		private void SetMtu(int mtuIdx)
		{
			_mtuIdx = mtuIdx;
			_mtu = NetConstants.PossibleMtu[mtuIdx] - NetManager.ExtraPacketSizeForLayer;
		}

		private void OverrideMtu(int mtuValue)
		{
			_mtu = mtuValue;
			_finishMtu = true;
		}

		public int GetPacketsCountInReliableQueue(byte channelNumber, bool ordered)
		{
			int num = channelNumber * 4 + (ordered ? 2 : 0);
			BaseChannel baseChannel = _channels[num];
			if (baseChannel == null)
			{
				return 0;
			}
			return ((ReliableChannel)baseChannel).PacketsInQueue;
		}

		public PooledPacket CreatePacketFromPool(DeliveryMethod deliveryMethod, byte channelNumber)
		{
			int mtu = _mtu;
			NetPacket netPacket = NetManager.PoolGetPacket(mtu);
			if (deliveryMethod == DeliveryMethod.Unreliable)
			{
				netPacket.Property = PacketProperty.Unreliable;
				return new PooledPacket(netPacket, mtu, 0);
			}
			netPacket.Property = PacketProperty.Channeled;
			return new PooledPacket(netPacket, mtu, (byte)((uint)(channelNumber * 4) + (ui

BepInEx/plugins/AILimitPhotoMode/AILimitPhotoMode.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GameDef;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using MagicaCloth2;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Samples;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("AILimitCoop contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2+844729c83d448e6315b248b396253c4bbd88ad75")]
[assembly: AssemblyProduct("AI LIMIT Photo Mode")]
[assembly: AssemblyTitle("AILimitPhotoMode")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AILimitPhotoMode
{
	internal static class PhotoConfig
	{
		public static ConfigEntry<Key> OpenKey;

		public static ConfigEntry<bool> ControllerHoldView;

		public static ConfigEntry<bool> ControllerViewA;

		public static ConfigEntry<Key> QuickPhotoKey;

		public static ConfigEntry<float> MaxDistance;

		public static ConfigEntry<float> LookSpeed;

		public static ConfigEntry<float> MoveSpeed;

		public static ConfigEntry<bool> InvertLook;

		public static ConfigEntry<bool> LiveCloth;

		public static ConfigEntry<string> PhotoFolder;

		public static ConfigEntry<int> PhotoScale;

		public static ConfigEntry<bool> DevCommands;

		public static void Bind(ConfigFile cfg)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			OpenKey = cfg.Bind<Key>("Keys", "PhotoMode", (Key)103, "Opens and closes photo mode (with AI LIMIT Together installed, its menu's PHOTO MODE button works too).");
			ControllerHoldView = cfg.Bind<bool>("Keys", "ControllerHoldView", true, "Holding View (Create on PlayStation) opens photo mode; a short press still opens the map. With AI LIMIT Together installed, holding View opens its menu instead, which has the PHOTO MODE button.");
			QuickPhotoKey = cfg.Bind<Key>("Keys", "QuickPhoto", (Key)104, "Takes a photo straight away while you play, the game's interface included, into the photos folder. None turns it off.");
			ControllerViewA = cfg.Bind<bool>("Keys", "ControllerViewA", true, "View + A (Create + Cross on PlayStation) opens photo mode straight away: press A while View is down. With AI LIMIT Together installed this skips its menu.");
			MaxDistance = cfg.Bind<float>("Camera", "MaxDistance", 30f, new ConfigDescription("How far from your character the camera may fly, in metres. The game only loads the world round your character, so far beyond this it may show holes.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 60f), Array.Empty<object>()));
			LookSpeed = cfg.Bind<float>("Camera", "LookSpeed", 1f, new ConfigDescription("Mouse and stick look speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 4f), Array.Empty<object>()));
			MoveSpeed = cfg.Bind<float>("Camera", "MoveSpeed", 1f, new ConfigDescription("Camera flying speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 4f), Array.Empty<object>()));
			InvertLook = cfg.Bind<bool>("Camera", "InvertLook", false, "Pushing the mouse or stick up looks down.");
			LiveCloth = cfg.Bind<bool>("Character", "LiveHairAndCloth", true, "While time is stopped, your character's hair and clothes keep moving and settle by themselves (the rest of the world stays stopped). Off: they stop with everything else.");
			PhotoFolder = cfg.Bind<string>("Photos", "Folder", "", "Where photos are saved. Empty: your Pictures folder, in 'AI LIMIT Photo Mode'.");
			PhotoScale = cfg.Bind<int>("Photos", "Scale", 1, new ConfigDescription("Photos are taken at this many times the screen's size (2 = twice as wide and tall). Larger takes longer.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>()));
			DevCommands = cfg.Bind<bool>("Dev", "Commands", false, "Testing only: reads commands from BepInEx/photomode_cmd.txt.");
		}
	}
	internal enum FocusMode
	{
		Off,
		Auto,
		Character,
		Manual
	}
	internal sealed class PhotoEffects
	{
		public sealed class Filter
		{
			public string Name;

			public string Chinese;

			public float Saturation;

			public float Contrast;

			public float Temperature;

			public float Vignette;

			public float Grain;

			public float Exposure;

			public uint Tint = 16777215u;
		}

		public readonly struct Aperture
		{
			public readonly string Name;

			public readonly float Band;

			public readonly float Ramp;

			public readonly float NearBlur;

			public readonly float FarBlur;

			public Aperture(string name, float band, float ramp, float nearBlur, float farBlur)
			{
				Name = name;
				Band = band;
				Ramp = ramp;
				NearBlur = nearBlur;
				FarBlur = farBlur;
			}
		}

		public struct DofQuality
		{
			public bool Game;

			public DepthOfFieldResolution Res;

			public int Near;

			public int Far;

			public bool Hq;

			public float BlurScale;

			public override string ToString()
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				if (!Game)
				{
					return $"{Res}/{Near}/{Far}/{(Hq ? "hq" : "-")}/{BlurScale:0.##}";
				}
				return "game";
			}
		}

		public static readonly Filter[] Filters = new Filter[9]
		{
			new Filter
			{
				Name = "None",
				Chinese = "无"
			},
			new Filter
			{
				Name = "Vivid",
				Chinese = "鲜艳",
				Saturation = 30f,
				Contrast = 15f
			},
			new Filter
			{
				Name = "Warm",
				Chinese = "暖色",
				Temperature = 30f,
				Saturation = 5f,
				Vignette = 0.2f
			},
			new Filter
			{
				Name = "Cool",
				Chinese = "冷色",
				Temperature = -30f,
				Saturation = -5f,
				Vignette = 0.2f
			},
			new Filter
			{
				Name = "Black and white",
				Chinese = "黑白",
				Saturation = -100f,
				Contrast = 10f
			},
			new Filter
			{
				Name = "Noir",
				Chinese = "黑色电影",
				Saturation = -100f,
				Contrast = 45f,
				Vignette = 0.45f,
				Grain = 0.35f,
				Exposure = -0.3f
			},
			new Filter
			{
				Name = "Sepia",
				Chinese = "怀旧",
				Saturation = -100f,
				Contrast = 5f,
				Tint = 15914926u,
				Vignette = 0.3f,
				Grain = 0.2f
			},
			new Filter
			{
				Name = "Faded film",
				Chinese = "褪色胶片",
				Saturation = -35f,
				Contrast = -25f,
				Temperature = 12f,
				Grain = 0.45f,
				Vignette = 0.25f
			},
			new Filter
			{
				Name = "Dream",
				Chinese = "梦幻",
				Saturation = 15f,
				Contrast = -20f,
				Tint = 15787775u,
				Exposure = 0.3f,
				Vignette = 0.35f
			}
		};

		public static readonly Aperture[] Apertures = new Aperture[6]
		{
			new Aperture("f/1.4", 0.04f, 0.35f, 8f, 16f),
			new Aperture("f/2", 0.08f, 0.6f, 7f, 14f),
			new Aperture("f/2.8", 0.15f, 1f, 6f, 11f),
			new Aperture("f/4", 0.25f, 1.6f, 5f, 9f),
			new Aperture("f/5.6", 0.4f, 2.6f, 4f, 7f),
			new Aperture("f/8", 0.6f, 4f, 3f, 5f)
		};

		public const int DefaultAperture = 2;

		public const float MinFocus = 0.2f;

		public const float MaxFocus = 300f;

		private GameObject _go;

		private Volume _volume;

		private VolumeProfile _profile;

		private DepthOfField _dof;

		private ColorAdjustments _color;

		private WhiteBalance _white;

		private Vignette _vignette;

		private FilmGrain _grain;

		private float _focus = 10f;

		private Transform _head;

		private Player _headOf;

		private bool _qualityFailed;

		public DofQuality Quality = new DofQuality
		{
			Res = (DepthOfFieldResolution)2,
			Near = 8,
			Far = 16,
			Hq = true,
			BlurScale = 1f
		};

		public FocusMode FocusMode { get; private set; }

		public bool Dof => FocusMode != FocusMode.Off;

		public int ApertureIndex { get; private set; } = 2;

		public Aperture CurrentAperture => Apertures[ApertureIndex];

		public int FilterIndex { get; private set; }

		public float Brightness { get; private set; }

		public float FocusDistance => _focus;

		public Vector2? FocusOnScreen { get; private set; }

		public string Problem { get; private set; }

		public Filter Current => Filters[FilterIndex];

		public bool Ready
		{
			get
			{
				if (U.Alive((Object)(object)_volume))
				{
					return (Object)(object)_dof != (Object)null;
				}
				return false;
			}
		}

		public void Start()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			Stop();
			FocusMode = FocusMode.Off;
			ApertureIndex = 2;
			FilterIndex = 0;
			Brightness = 0f;
			Problem = null;
			FocusOnScreen = null;
			_head = null;
			_headOf = null;
			try
			{
				_go = new GameObject("AILimitPhotoMode_Volume");
				Object.DontDestroyOnLoad((Object)(object)_go);
				_volume = _go.AddComponent<Volume>();
				_volume.isGlobal = true;
				_volume.priority = 10000f;
				_volume.weight = 1f;
				_profile = ScriptableObject.CreateInstance<VolumeProfile>();
				((Object)_profile).hideFlags = (HideFlags)61;
				_dof = Add<DepthOfField>();
				_color = Add<ColorAdjustments>();
				_white = Add<WhiteBalance>();
				_vignette = Add<Vignette>();
				_grain = Add<FilmGrain>();
				_volume.sharedProfile = _profile;
				Apply();
			}
			catch (Exception ex)
			{
				Problem = ex.GetType().Name + ": " + ex.Message;
				Log.Warn("[Photo mode] effects unavailable: " + Problem);
				Stop();
			}
		}

		private T Add<T>() where T : VolumeComponent
		{
			VolumeComponent obj = _profile.Add(Il2CppType.Of<T>(), false);
			T obj2 = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<T>() : default(T));
			if ((Object)(object)obj2 == (Object)null)
			{
				throw new InvalidOperationException("could not add " + typeof(T).Name);
			}
			return obj2;
		}

		public void Stop()
		{
			try
			{
				if (U.Alive((Object)(object)_go))
				{
					Object.Destroy((Object)(object)_go);
				}
			}
			catch
			{
			}
			try
			{
				if (U.Alive((Object)(object)_profile))
				{
					Object.Destroy((Object)(object)_profile);
				}
			}
			catch
			{
			}
			_go = null;
			_volume = null;
			_profile = null;
			_dof = null;
			_color = null;
			_white = null;
			_vignette = null;
			_grain = null;
			_head = null;
			_headOf = null;
			FocusOnScreen = null;
		}

		public void NextFocusMode(int step = 1)
		{
			FocusMode = (FocusMode)((int)(FocusMode + step % 4 + 4) % 4);
			Apply();
		}

		public void SetFocusMode(FocusMode mode)
		{
			FocusMode = mode;
			Apply();
		}

		public void MoveFocus(float amount)
		{
			if (FocusMode != FocusMode.Manual)
			{
				FocusMode = FocusMode.Manual;
			}
			_focus = U.Clamp(_focus * (float)Math.Exp(amount), 0.2f, 300f);
			Apply();
		}

		public void SetFocusDistance(float metres)
		{
			FocusMode = FocusMode.Manual;
			_focus = U.Clamp(metres, 0.2f, 300f);
			Apply();
		}

		public void NextAperture(int step, bool wrap)
		{
			int num = Apertures.Length;
			int num2 = ApertureIndex + step;
			ApertureIndex = (wrap ? ((num2 % num + num) % num) : Math.Max(0, Math.Min(num - 1, num2)));
			if (FocusMode == FocusMode.Off)
			{
				FocusMode = FocusMode.Auto;
			}
			Apply();
		}

		public void NextFilter(int step = 1)
		{
			FilterIndex = (FilterIndex + step + Filters.Length) % Filters.Length;
			Apply();
		}

		public void AddBrightness(float ev)
		{
			Brightness = U.Clamp(Brightness + ev, -3f, 3f);
			Apply();
		}

		public void Reset()
		{
			FocusMode = FocusMode.Off;
			ApertureIndex = 2;
			FilterIndex = 0;
			Brightness = 0f;
			Apply();
		}

		public void UpdateFocus(Camera cam, Player player, float dt)
		{
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			FocusOnScreen = null;
			if (!Dof || !Ready || !U.Alive((Object)(object)cam))
			{
				return;
			}
			Transform transform = ((Component)cam).transform;
			Vector3? val = null;
			float num = _focus;
			try
			{
				if (FocusMode == FocusMode.Auto)
				{
					num = 12f;
					RaycastHit val2 = default(RaycastHit);
					if (Physics.Raycast(transform.position, transform.forward, ref val2, 300f, -1, (QueryTriggerInteraction)1))
					{
						num = ((RaycastHit)(ref val2)).distance;
						val = ((RaycastHit)(ref val2)).point;
					}
					else
					{
						val = transform.position + transform.forward * num;
					}
				}
				else if (FocusMode == FocusMode.Character)
				{
					Transform val3 = Head(player);
					Vector3 val4 = (((Object)(object)val3 != (Object)null) ? val3.position : (GameView.Position(player) + Vector3.up * 1.45f));
					num = Vector3.Dot(val4 - transform.position, transform.forward);
					val = val4;
				}
			}
			catch
			{
			}
			if (FocusMode != FocusMode.Manual)
			{
				num = U.Clamp(num, 0.2f, 300f);
				_focus += (num - _focus) * Math.Min(1f, dt * ((FocusMode == FocusMode.Character) ? 10f : 6f));
			}
			if (val.HasValue)
			{
				try
				{
					Vector3 val5 = cam.WorldToScreenPoint(val.Value);
					if (val5.z > 0f && val5.x >= 0f && val5.x <= (float)Screen.width && val5.y >= 0f && val5.y <= (float)Screen.height)
					{
						FocusOnScreen = new Vector2(val5.x, (float)Screen.height - val5.y);
					}
				}
				catch
				{
				}
			}
			SetFocus();
		}

		private Transform Head(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			if ((Object)(object)_headOf == (Object)(object)player && U.Alive((Object)(object)_head))
			{
				return _head;
			}
			_headOf = player;
			_head = null;
			try
			{
				foreach (Transform item in U.Each<Transform>(((CustomMonoBehaviour)player).gameObject.GetComponentsInChildren<Transform>(true)))
				{
					if (U.Alive((Object)(object)item) && ((Object)item).name == "Bip001 Head")
					{
						_head = item;
						break;
					}
				}
			}
			catch
			{
			}
			return _head;
		}

		private void SetFocus()
		{
			float focus = _focus;
			Aperture currentAperture = CurrentAperture;
			float num = focus * (1f - currentAperture.Band);
			float num2 = focus * (1f + currentAperture.Band);
			((VolumeParameter<float>)(object)_dof.nearFocusStart).value = num / (1f + currentAperture.Ramp);
			((VolumeParameter<float>)(object)_dof.nearFocusEnd).value = num;
			((VolumeParameter<float>)(object)_dof.farFocusStart).value = num2;
			((VolumeParameter<float>)(object)_dof.farFocusEnd).value = num2 + focus * currentAperture.Ramp * 2f + currentAperture.Ramp;
		}

		private void Apply()
		{
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			if (!Ready)
			{
				return;
			}
			try
			{
				bool dof = Dof;
				if (!dof || FocusMode == FocusMode.Manual)
				{
					FocusOnScreen = null;
				}
				((VolumeParameter)_dof.focusMode).overrideState = true;
				((VolumeParameter<DepthOfFieldMode>)(object)_dof.focusMode).value = (DepthOfFieldMode)(dof ? 2 : 0);
				VolumeParameter[] array = (VolumeParameter[])(object)new VolumeParameter[4]
				{
					(VolumeParameter)_dof.nearFocusStart,
					(VolumeParameter)_dof.nearFocusEnd,
					(VolumeParameter)_dof.farFocusStart,
					(VolumeParameter)_dof.farFocusEnd
				};
				for (int i = 0; i < array.Length; i++)
				{
					array[i].overrideState = dof;
				}
				if (dof)
				{
					SetFocus();
					SetQuality();
				}
				Filter current = Current;
				bool flag = FilterIndex != 0 || Brightness != 0f;
				((VolumeComponent)_color).active = flag;
				((VolumeParameter)_color.postExposure).overrideState = flag;
				((VolumeParameter<float>)(object)_color.postExposure).value = current.Exposure + Brightness;
				((VolumeParameter)_color.saturation).overrideState = current.Saturation != 0f;
				((VolumeParameter<float>)(object)_color.saturation).value = current.Saturation;
				((VolumeParameter)_color.contrast).overrideState = current.Contrast != 0f;
				((VolumeParameter<float>)(object)_color.contrast).value = current.Contrast;
				((VolumeParameter)_color.colorFilter).overrideState = current.Tint != 16777215;
				((VolumeParameter<Color>)(object)_color.colorFilter).value = U.Rgb(current.Tint);
				((VolumeComponent)_white).active = current.Temperature != 0f;
				((VolumeParameter)_white.temperature).overrideState = current.Temperature != 0f;
				((VolumeParameter<float>)(object)_white.temperature).value = current.Temperature;
				((VolumeComponent)_vignette).active = current.Vignette > 0f;
				((VolumeParameter)_vignette.intensity).overrideState = current.Vignette > 0f;
				((VolumeParameter<float>)(object)_vignette.intensity).value = current.Vignette;
				((VolumeComponent)_grain).active = current.Grain > 0f;
				((VolumeParameter)_grain.intensity).overrideState = current.Grain > 0f;
				((VolumeParameter<float>)(object)_grain.intensity).value = current.Grain;
			}
			catch (Exception ex)
			{
				Problem = ex.GetType().Name + ": " + ex.Message;
				Log.Warn("[Photo mode] effects: " + Problem);
			}
		}

		public void SetQualityTo(DofQuality q)
		{
			Quality = q;
			Apply();
		}

		private void SetQuality()
		{
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			if (_qualityFailed)
			{
				return;
			}
			try
			{
				Aperture currentAperture = CurrentAperture;
				DofQuality quality = Quality;
				((VolumeParameter)((VolumeComponentWithQuality)_dof).quality).overrideState = !quality.Game;
				((VolumeParameter<int>)(object)((VolumeComponentWithQuality)_dof).quality).value = ScalableSettingLevelParameter.LevelCount;
				VolumeParameter[] array = (VolumeParameter[])(object)new VolumeParameter[6]
				{
					(VolumeParameter)_dof.m_NearSampleCount,
					(VolumeParameter)_dof.m_FarSampleCount,
					(VolumeParameter)_dof.m_NearMaxBlur,
					(VolumeParameter)_dof.m_FarMaxBlur,
					(VolumeParameter)_dof.m_Resolution,
					(VolumeParameter)_dof.m_HighQualityFiltering
				};
				for (int i = 0; i < array.Length; i++)
				{
					array[i].overrideState = !quality.Game;
				}
				if (!quality.Game)
				{
					((VolumeParameter<int>)(object)_dof.m_NearSampleCount).value = quality.Near;
					((VolumeParameter<int>)(object)_dof.m_FarSampleCount).value = quality.Far;
					((VolumeParameter<float>)(object)_dof.m_NearMaxBlur).value = currentAperture.NearBlur * quality.BlurScale;
					((VolumeParameter<float>)(object)_dof.m_FarMaxBlur).value = currentAperture.FarBlur * quality.BlurScale;
					((VolumeParameter<DepthOfFieldResolution>)(object)_dof.m_Resolution).value = quality.Res;
					((VolumeParameter<bool>)(object)_dof.m_HighQualityFiltering).value = quality.Hq;
				}
			}
			catch (Exception ex)
			{
				_qualityFailed = true;
				Log.Warn("[Photo mode] depth of field quality: " + ex.GetType().Name + ": " + ex.Message + " (the game's quality is kept)");
			}
		}

		public string Describe()
		{
			return $"effects ready={Ready} dof={FocusMode} focus={_focus:0.00} aperture={CurrentAperture.Name} range={((Ready && Dof) ? $"{((VolumeParameter<float>)(object)_dof.nearFocusStart).value:0.00}/{((VolumeParameter<float>)(object)_dof.nearFocusEnd).value:0.00}/{((VolumeParameter<float>)(object)_dof.farFocusStart).value:0.00}/{((VolumeParameter<float>)(object)_dof.farFocusEnd).value:0.00}" : "-")} quality={(Ready ? $"{((VolumeParameter<int>)(object)((VolumeComponentWithQuality)_dof).quality).value}/{((VolumeParameter<float>)(object)_dof.m_NearMaxBlur).value:0}/{((VolumeParameter<float>)(object)_dof.m_FarMaxBlur).value:0}" : "-")} dofq={Quality} marker={(FocusOnScreen.HasValue ? "on" : "off")} filter={Current.Name} brightness={Brightness:+0.00;-0.00;0} problem='{Problem}'";
		}
	}
	internal sealed class PhotoMode
	{
		public enum WeaponMode
		{
			Auto,
			InHand,
			PutAway,
			Hidden
		}

		private readonly List<(MagicaCloth cloth, ClothUpdateMode before)> _cloth = new List<(MagicaCloth, ClothUpdateMode)>();

		private IntPtr _clothOwner;

		public static readonly PhotoMode Instance = new PhotoMode();

		public const float MinFov = 10f;

		public const float MaxFov = 100f;

		public const float SlowTime = 0.25f;

		private readonly List<(CanvasGroup Group, bool Added, float Alpha)> _faded = new List<(CanvasGroup, bool, float)>();

		private readonly List<Renderer> _hidden = new List<Renderer>();

		public readonly PhotoEffects Effects = new PhotoEffects();

		private Vector3 _pos;

		private Vector3 _anchor;

		private Vector3 _posBefore;

		private Quaternion _rotBefore;

		private float _yaw;

		private float _pitch;

		private float _roll;

		private float _fov;

		private float _fovStart;

		private float _fovBefore;

		private float _timeBefore;

		private float _setTime = -1f;

		private int _level;

		private Camera _cam;

		private float _viewDownAt = -1f;

		private bool _viewWasDown;

		public string LastResult = "";

		public int Photos;

		private readonly float[] _frameTimes = new float[120];

		private int _frameAt;

		private float _viewPressedAt;

		private int _chordFrame = -1;

		public const float SettleSeconds = 0.5f;

		private Animator _holdAnim;

		private AnimationClip _holdBase;

		private AnimationClip _holdClip;

		private bool _holdKeep;

		private bool _holdEnabled;

		private Vector3 _holdRootPos;

		private Quaternion _holdRootRot;

		private float _holdHp;

		private float _settleAt = -1f;

		private float _settleUntil = -1f;

		private float _settleScale = -1f;

		private string _holdLabel = "";

		private readonly List<AnimationClip> _clips = new List<AnimationClip>();

		private readonly List<Renderer> _weaponHidden = new List<Renderer>();

		private bool? _weaponWasDrawn;

		public bool ClothLive => _cloth.Count > 0;

		public bool Active { get; private set; }

		public bool HintsShown { get; private set; } = true;

		public TimeMode Time { get; private set; }

		public bool CharacterHidden => _hidden.Count > 0;

		public float Fov => _fov;

		public float Roll => _roll;

		public int PhotoFrame { get; private set; } = -1;

		private static IPhotoHost Host => PhotoModeApi.Host;

		private static bool SessionActive => Host?.SessionActive ?? false;

		private static bool TimeAdjustable => (int)InputSystem.settings.updateMode != 2;

		public int PoseIndex { get; private set; } = -1;

		public float PoseMoment { get; private set; }

		public bool PoseHeld => (Object)(object)_holdAnim != (Object)null;

		public string PoseName
		{
			get
			{
				if (PoseIndex < 0)
				{
					if (PoseIndex != -2)
					{
						return "";
					}
					return _holdLabel;
				}
				return PhotoPoses.NameOf(PoseIndex);
			}
		}

		public WeaponMode Weapons { get; private set; }

		public bool WeaponsHidden
		{
			get
			{
				if (PoseHeld)
				{
					return Weapons == WeaponMode.Hidden;
				}
				return false;
			}
		}

		public string PoseClip
		{
			get
			{
				if (!PoseHeld || !U.Alive((Object)(object)_holdClip))
				{
					return null;
				}
				return ((Object)_holdClip).name;
			}
		}

		private void UpdateCloth()
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Invalid comparison between Unknown and I4
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			bool flag = Active && Time == TimeMode.Stopped && PhotoConfig.LiveCloth.Value;
			Player val = (flag ? GameView.LocalPlayer : null);
			if (flag && (Object)(object)val == (Object)null)
			{
				flag = false;
			}
			if (!flag)
			{
				if (ClothLive || _clothOwner != IntPtr.Zero)
				{
					ReleaseCloth();
				}
			}
			else
			{
				if (_clothOwner == ((Il2CppObjectBase)val).Pointer)
				{
					return;
				}
				ReleaseCloth();
				_clothOwner = ((Il2CppObjectBase)val).Pointer;
				int num = 0;
				try
				{
					foreach (MagicaCloth item in U.Each<MagicaCloth>(((Component)val).GetComponentsInChildren<MagicaCloth>(true)))
					{
						if (!U.Alive((Object)(object)item))
						{
							continue;
						}
						ClothSerializeData serializeData = item.SerializeData;
						if (serializeData != null)
						{
							ClothUpdateMode updateMode = serializeData.updateMode;
							if ((int)updateMode == 2)
							{
								num++;
								continue;
							}
							serializeData.updateMode = (ClothUpdateMode)2;
							item.SetParameterChange();
							_cloth.Add((item, updateMode));
						}
					}
				}
				catch (Exception ex)
				{
					Log.Warn("[Photo mode] cloth: " + ex.Message);
				}
				Log.Info($"[Photo mode] hair and cloth on real time: {_cloth.Count} switched, {num} already");
			}
		}

		private void ReleaseCloth()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			_clothOwner = IntPtr.Zero;
			if (_cloth.Count == 0)
			{
				return;
			}
			int num = 0;
			foreach (var (val, updateMode) in _cloth)
			{
				try
				{
					if (U.Alive((Object)(object)val))
					{
						ClothSerializeData serializeData = val.SerializeData;
						if (serializeData != null && (int)serializeData.updateMode == 2)
						{
							serializeData.updateMode = updateMode;
							val.SetParameterChange();
							num++;
						}
					}
				}
				catch (Exception ex)
				{
					Log.Warn("[Photo mode] cloth back: " + ex.Message);
				}
			}
			_cloth.Clear();
			Log.Info($"[Photo mode] hair and cloth back on game time ({num})");
		}

		private string ClothState()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = GameView.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return "CLOTH no character";
			}
			StringBuilder stringBuilder = new StringBuilder("CLOTH");
			int num = 0;
			try
			{
				foreach (MagicaCloth item in U.Each<MagicaCloth>(((Component)localPlayer).GetComponentsInChildren<MagicaCloth>(true)))
				{
					if (U.Alive((Object)(object)item))
					{
						num++;
						ClothSerializeData serializeData = item.SerializeData;
						StringBuilder stringBuilder2 = stringBuilder;
						StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(5, 3, stringBuilder2);
						handler.AppendLiteral(" [");
						handler.AppendFormatted(((Object)((Component)item).gameObject).name);
						handler.AppendLiteral(" ");
						handler.AppendFormatted((serializeData != null) ? ((object)serializeData.updateMode/*cast due to .constrained prefix*/).ToString() : "-");
						handler.AppendLiteral(" ");
						handler.AppendFormatted(((Behaviour)item).isActiveAndEnabled ? "on" : "off");
						handler.AppendLiteral("]");
						stringBuilder2.Append(ref handler);
					}
				}
			}
			catch (Exception ex)
			{
				stringBuilder.Append(" error=" + ex.Message);
			}
			stringBuilder.Insert(5, $" count={num} live={_cloth.Count}");
			return stringBuilder.ToString();
		}

		public string Blocker()
		{
			if (Plugin.Mode == PluginMode.StoodDown)
			{
				return T.Get("Photo mode is off: update AI LIMIT Together.");
			}
			Player localPlayer = GameView.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null || GameView.LevelId < 0 || GameView.Loading)
			{
				return T.Get("Load a save first.");
			}
			if (GameView.Hp(localPlayer) <= 0f)
			{
				return T.Get("Not while down.");
			}
			string text = Host?.Blocker();
			if (text != null)
			{
				return text;
			}
			if (Plugin.Mode == PluginMode.Standalone && !Standalone.InputReady)
			{
				return T.Get("Controls capture unavailable; see the log.");
			}
			if ((Object)(object)GameView.Camera == (Object)null)
			{
				return T.Get("The game's camera isn't ready.");
			}
			return null;
		}

		public bool Enter()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			if (Active)
			{
				return true;
			}
			QuickPhoto.Restore();
			string text = Blocker();
			if (text != null)
			{
				LastResult = text;
				PhotoOverlay.Toast(text);
				return false;
			}
			_cam = GameView.Camera;
			Transform transform = ((Component)_cam).transform;
			_pos = transform.position;
			_posBefore = transform.localPosition;
			_rotBefore = transform.localRotation;
			Quaternion rotation = transform.rotation;
			Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles;
			_yaw = eulerAngles.y;
			_pitch = ((eulerAngles.x > 180f) ? (eulerAngles.x - 360f) : eulerAngles.x);
			_roll = 0f;
			_fov = (_fovStart = (_fovBefore = _cam.fieldOfView));
			_anchor = GameView.Position(GameView.LocalPlayer);
			_level = GameView.LevelId;
			HintsShown = true;
			FadeInterface();
			Effects.Start();
			Time = TimeMode.Running;
			_timeBefore = Time.timeScale;
			if (!SessionActive && TimeAdjustable)
			{
				SetTime(TimeMode.Stopped);
			}
			Active = true;
			UpdateCloth();
			LastResult = $"on (faded {_faded.Count} canvases, time {Time}, effects {(Effects.Ready ? "ready" : "off")})";
			Log.Info("[Photo mode] " + LastResult);
			return true;
		}

		public void Exit(string why)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (!Active)
			{
				return;
			}
			Active = false;
			try
			{
				if (U.Alive((Object)(object)_cam))
				{
					Transform transform = ((Component)_cam).transform;
					transform.localPosition = _posBefore;
					transform.localRotation = _rotBefore;
					_cam.fieldOfView = _fovBefore;
				}
			}
			catch (Exception ex)
			{
				Log.Warn("[Photo mode] camera: " + ex.Message);
			}
			DropPose(null);
			ShowCharacter();
			RestoreInterface();
			Effects.Stop();
			SetTime(TimeMode.Running);
			ReleaseCloth();
			_cam = null;
			PhotoFrame = -1;
			LastResult = "off: " + why;
			Log.Info("[Photo mode] " + LastResult);
		}

		private void SetTime(TimeMode mode)
		{
			EndSettle();
			float timeScale = Time.timeScale;
			if (mode == TimeMode.Running)
			{
				if (_setTime >= 0f && timeScale == _setTime)
				{
					Time.timeScale = ((_timeBefore > 0f) ? _timeBefore : 1f);
				}
				_setTime = -1f;
			}
			else
			{
				if (_setTime < 0f || timeScale != _setTime)
				{
					_timeBefore = timeScale;
				}
				_setTime = ((mode == TimeMode.Stopped) ? 0f : (0.25f * ((_timeBefore > 0f) ? _timeBefore : 1f)));
				Time.timeScale = _setTime;
			}
			Time = mode;
			UpdateCloth();
		}

		public void CycleTime()
		{
			if (SessionActive)
			{
				PhotoOverlay.Toast(T.Get("Time keeps running in a session."));
			}
			else if (!TimeAdjustable)
			{
				PhotoOverlay.Toast(T.Get("Time can't be stopped with this input setting."));
			}
			else
			{
				SetTime((Time == TimeMode.Stopped) ? TimeMode.Slow : ((Time != TimeMode.Slow) ? TimeMode.Stopped : TimeMode.Running));
			}
		}

		public void ToggleHints()
		{
			HintsShown = !HintsShown;
		}

		public void ToggleCharacter()
		{
			if (CharacterHidden)
			{
				ShowCharacter();
				return;
			}
			Player localPlayer = GameView.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			try
			{
				Hide(((CustomMonoBehaviour)localPlayer).gameObject);
				try
				{
					Weapon currentWeapon = localPlayer.CurrentWeapon;
					Hide((currentWeapon != null) ? currentWeapon.Root : null);
				}
				catch
				{
				}
				try
				{
					Weapon reserveWeapon = localPlayer.ReserveWeapon;
					Hide((reserveWeapon != null) ? reserveWeapon.Root : null);
				}
				catch
				{
				}
			}
			catch (Exception ex)
			{
				Log.Warn("[Photo mode] hiding the character: " + ex.Message);
			}
		}

		private void Hide(GameObject root)
		{
			if (!U.Alive((Object)(object)root))
			{
				return;
			}
			foreach (Renderer item in U.Each<Renderer>(root.GetComponentsInChildren<Renderer>(true)))
			{
				if (U.Alive((Object)(object)item) && !item.forceRenderingOff)
				{
					item.forceRenderingOff = true;
					_hidden.Add(item);
				}
			}
		}

		private void ShowCharacter()
		{
			foreach (Renderer item in _hidden)
			{
				try
				{
					if (U.Alive((Object)(object)item))
					{
						item.forceRenderingOff = false;
					}
				}
				catch
				{
				}
			}
			_hidden.Clear();
			if (_weaponHidden.Count == 0)
			{
				ApplyWeapons();
			}
		}

		public void ResetView()
		{
			_roll = 0f;
			_fov = _fovStart;
		}

		public void TakePhoto(bool quick = false)
		{
			try
			{
				string text = PhotoFolder();
				Directory.CreateDirectory(text);
				string text2 = "AI LIMIT " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture);
				string text3 = Path.Combine(text, text2 + ".png");
				int num = 2;
				while (File.Exists(text3))
				{
					text3 = Path.Combine(text, $"{text2} ({num}).png");
					num++;
				}
				PhotoFrame = Time.frameCount;
				ScreenCapture.CaptureScreenshot(text3, Math.Max(1, Math.Min(4, PhotoConfig.PhotoScale.Value)));
				Photos++;
				Log.Info("[Photo mode] photo saved: " + Path.GetFileName(text3));
				PhotoOverlay.Toast(T.Get("Photo saved: ") + Path.GetFileName(text3), 3.5f, PhotoFrame + 2);
			}
			catch (Exception ex)
			{
				Log.Warn("[Photo mode] photo failed: " + ex.Message);
				PhotoOverlay.Toast(T.Get("The photo could not be saved; see the log."));
			}
		}

		public static string PhotoFolder()
		{
			string text = PhotoConfig.PhotoFolder.Value?.Trim();
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "AI LIMIT Photo Mode");
		}

		public float FrameMs()
		{
			float num = 0f;
			int num2 = 0;
			float[] frameTimes = _frameTimes;
			foreach (float num3 in frameTimes)
			{
				if (num3 > 0f)
				{
					num += num3;
					num2++;
				}
			}
			if (num2 <= 0)
			{
				return 0f;
			}
			return num / (float)num2 * 1000f;
		}

		public void Tick()
		{
			_frameTimes[_frameAt++ % _frameTimes.Length] = Time.unscaledDeltaTime;
			try
			{
				TickInner();
			}
			catch (Exception ex)
			{
				Log.Error("[Photo mode] " + ex);
				try
				{
					QuickPhoto.Restore();
				}
				catch
				{
				}
				try
				{
					Exit("an error (see the log)");
				}
				catch
				{
				}
			}
		}

		private void TickInner()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.Mode == PluginMode.StoodDown)
			{
				return;
			}
			bool flag = U.GameHasFocus();
			Keyboard current = Keyboard.current;
			bool flag2 = Host?.Busy ?? false;
			if (flag && !flag2 && current != null && ((ButtonControl)current[PhotoConfig.OpenKey.Value]).wasPressedThisFrame)
			{
				if (Active)
				{
					Exit("closed");
				}
				else
				{
					Enter();
				}
				return;
			}
			QuickPhoto.Tick(this, flag, flag2, current);
			if (_chordFrame == Time.frameCount)
			{
				return;
			}
			if (Plugin.Mode == PluginMode.Standalone && flag && !flag2)
			{
				ControllerOpen();
			}
			if (!Active)
			{
				return;
			}
			Player localPlayer = GameView.LocalPlayer;
			if (GameView.Loading || GameView.LevelId != _level)
			{
				Exit("the level changed");
				return;
			}
			if ((Object)(object)localPlayer == (Object)null || GameView.Hp(localPlayer) <= 0f)
			{
				Exit("the character went down");
				return;
			}
			string text = Host?.MustExit();
			if (text != null)
			{
				Exit(text);
				return;
			}
			if (!U.Alive((Object)(object)_cam))
			{
				Exit("the camera went away");
				return;
			}
			if (Time != TimeMode.Running && SessionActive)
			{
				SetTime(TimeMode.Running);
			}
			if (flag)
			{
				Controls(current, Mouse.current, Gamepad.current);
			}
			if (Active)
			{
				UpdateCloth();
				TickPose();
				Fly(Time.unscaledDeltaTime, flag);
				Effects.UpdateFocus(_cam, localPlayer, Time.unscaledDeltaTime);
			}
		}

		private void ControllerOpen()
		{
			if (!PhotoConfig.ControllerHoldView.Value)
			{
				return;
			}
			bool viewDown = QuickPhoto.ViewDown;
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!viewDown)
			{
				_viewDownAt = -1f;
				return;
			}
			if (QuickPhoto.ViewUsed)
			{
				_viewDownAt = 0f;
				return;
			}
			if (_viewDownAt < 0f)
			{
				_viewDownAt = realtimeSinceStartup;
			}
			if (_viewDownAt > 0f && realtimeSinceStartup - _viewDownAt >= 0.5f)
			{
				_viewDownAt = 0f;
				if (Active)
				{
					Exit("closed");
				}
				else
				{
					Enter();
				}
			}
		}

		private void Controls(Keyboard keyboard, Mouse mouse, Gamepad pad)
		{
			if (keyboard != null)
			{
				if (((ButtonControl)keyboard.escapeKey).wasPressedThisFrame)
				{
					Exit("closed");
					return;
				}
				if (((ButtonControl)keyboard.hKey).wasPressedThisFrame)
				{
					ToggleHints();
				}
				if (((ButtonControl)keyboard.pKey).wasPressedThisFrame)
				{
					TakePhoto();
				}
				if (((ButtonControl)keyboard.fKey).wasPressedThisFrame)
				{
					Effects.NextFocusMode((!((ButtonControl)keyboard.leftShiftKey).isPressed) ? 1 : (-1));
				}
				if (((ButtonControl)keyboard.semicolonKey).wasPressedThisFrame)
				{
					Effects.NextAperture(-1, wrap: false);
				}
				if (((ButtonControl)keyboard.quoteKey).wasPressedThisFrame)
				{
					Effects.NextAperture(1, wrap: false);
				}
				if (((ButtonControl)keyboard.vKey).wasPressedThisFrame)
				{
					Effects.NextFilter((!((ButtonControl)keyboard.leftShiftKey).isPressed) ? 1 : (-1));
				}
				if (((ButtonControl)keyboard.cKey).wasPressedThisFrame)
				{
					ToggleCharacter();
				}
				if (((ButtonControl)keyboard.tKey).wasPressedThisFrame)
				{
					CycleTime();
				}
				if (((ButtonControl)keyboard.rKey).wasPressedThisFrame)
				{
					ResetView();
				}
				if (((ButtonControl)keyboard.backspaceKey).wasPressedThisFrame)
				{
					Effects.Reset();
				}
				if (((ButtonControl)keyboard.nKey).wasPressedThisFrame)
				{
					NextPose((!((ButtonControl)keyboard.leftShiftKey).isPressed) ? 1 : (-1));
				}
				if (((ButtonControl)keyboard.gKey).wasPressedThisFrame)
				{
					CycleWeapons();
				}
			}
			if (pad == null)
			{
				return;
			}
			if (pad.buttonEast.wasPressedThisFrame)
			{
				Exit("closed");
				return;
			}
			if (pad.buttonNorth.wasPressedThisFrame)
			{
				ToggleHints();
			}
			if (pad.buttonSouth.wasPressedThisFrame)
			{
				TakePhoto();
			}
			if (pad.buttonWest.wasPressedThisFrame)
			{
				if (((InputControl<float>)(object)pad.leftTrigger).ReadValue() > 0.5f)
				{
					CycleWeapons();
				}
				else
				{
					ToggleCharacter();
				}
			}
			if (pad.leftStickButton.wasPressedThisFrame)
			{
				Effects.NextFocusMode();
			}
			if (pad.rightStickButton.wasPressedThisFrame)
			{
				Effects.NextFilter();
			}
			if (pad.startButton.wasPressedThisFrame)
			{
				CycleTime();
			}
			if (((InputControl<float>)(object)pad.leftTrigger).ReadValue() > 0.5f)
			{
				if (pad.dpad.right.wasPressedThisFrame)
				{
					NextPose();
				}
				if (pad.dpad.left.wasPressedThisFrame)
				{
					NextPose(-1);
				}
			}
			bool isPressed = pad.selectButton.isPressed;
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (isPressed && !_viewWasDown)
			{
				_viewPressedAt = realtimeSinceStartup;
			}
			if (!isPressed && _viewWasDown && realtimeSinceStartup - _viewPressedAt < 0.45f)
			{
				Effects.NextAperture((((InputControl<float>)(object)pad.leftTrigger).ReadValue() > 0.5f) ? 1 : (-1), wrap: true);
			}
			_viewWasDown = isPressed;
		}

		public bool EnterByChord()
		{
			if (!Enter())
			{
				return false;
			}
			_chordFrame = Time.frameCount;
			_viewWasDown = true;
			_viewPressedAt = -10f;
			return true;
		}

		private void Fly(float dt, bool focus)
		{
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Unknown result type (might be due to invalid IL or missing references)
			//IL_0506: Unknown result type (might be due to invalid IL or missing references)
			//IL_050d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0512: Unknown result type (might be due to invalid IL or missing references)
			//IL_0517: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_056d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0573: Unknown result type (might be due to invalid IL or missing references)
			//IL_0578: Unknown result type (might be due to invalid IL or missing references)
			//IL_057d: Unknown result type (might be due to invalid IL or missing references)
			//IL_058f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0595: Unknown result type (might be due to invalid IL or missing references)
			//IL_059a: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05db: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0611: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0605: Unknown result type (might be due to invalid IL or missing references)
			//IL_060a: Unknown result type (might be due to invalid IL or missing references)
			dt = Math.Min(dt, 0.1f);
			Keyboard val = (focus ? Keyboard.current : null);
			Mouse val2 = (focus ? Mouse.current : null);
			Gamepad val3 = (focus ? Gamepad.current : null);
			float num = 0f;
			float num2 = 0f;
			float num3 = 0f;
			float num4 = 0f;
			float num5 = 0f;
			float num6 = 0f;
			float num7 = 0f;
			float num8 = 0f;
			float num9 = 0f;
			float num10 = 0f;
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			float value = PhotoConfig.LookSpeed.Value;
			float num11 = (PhotoConfig.InvertLook.Value ? (-1f) : 1f);
			if (val != null)
			{
				num += (float)((((ButtonControl)val.dKey).isPressed ? 1 : 0) - (((ButtonControl)val.aKey).isPressed ? 1 : 0));
				num3 += (float)((((ButtonControl)val.wKey).isPressed ? 1 : 0) - (((ButtonControl)val.sKey).isPressed ? 1 : 0));
				num2 += (float)(((((ButtonControl)val.eKey).isPressed || ((ButtonControl)val.spaceKey).isPressed) ? 1 : 0) - (((ButtonControl)val.qKey).isPressed ? 1 : 0));
				num7 += (float)((((ButtonControl)val.xKey).isPressed ? 1 : 0) - (((ButtonControl)val.zKey).isPressed ? 1 : 0));
				num8 += (float)((((ButtonControl)val.equalsKey).isPressed ? 1 : 0) - (((ButtonControl)val.minusKey).isPressed ? 1 : 0));
				num9 += (float)((((ButtonControl)val.periodKey).isPressed ? 1 : 0) - (((ButtonControl)val.commaKey).isPressed ? 1 : 0));
				num10 += (float)((((ButtonControl)val.rightBracketKey).isPressed ? 1 : 0) - (((ButtonControl)val.leftBracketKey).isPressed ? 1 : 0));
				flag2 |= ((ButtonControl)val.leftShiftKey).isPressed;
				flag3 |= ((ButtonControl)val.leftCtrlKey).isPressed;
			}
			if (val2 != null)
			{
				num4 += ((InputControl<float>)(object)((Vector2Control)((Pointer)val2).delta).x).ReadValue() * 0.12f * value;
				num5 -= ((InputControl<float>)(object)((Vector2Control)((Pointer)val2).delta).y).ReadValue() * 0.12f * value * num11;
				num6 -= ((InputControl<float>)(object)((Vector2Control)val2.scroll).y).ReadValue() / 120f * 3f;
			}
			if (val3 != null)
			{
				bool flag4 = ((InputControl<float>)(object)val3.leftTrigger).ReadValue() > 0.5f;
				num += Dead(((InputControl<float>)(object)((Vector2Control)val3.leftStick).x).ReadValue());
				num3 += Dead(((InputControl<float>)(object)((Vector2Control)val3.leftStick).y).ReadValue());
				num2 += (float)((val3.rightShoulder.isPressed ? 1 : 0) - (val3.leftShoulder.isPressed ? 1 : 0));
				num4 += Dead(((InputControl<float>)(object)((Vector2Control)val3.rightStick).x).ReadValue()) * 120f * dt * value;
				num5 -= Dead(((InputControl<float>)(object)((Vector2Control)val3.rightStick).y).ReadValue()) * 90f * dt * value * num11;
				float num12 = (val3.dpad.up.isPressed ? 1 : 0) - (val3.dpad.down.isPressed ? 1 : 0);
				flag = ((InputControl<float>)(object)val3.rightTrigger).ReadValue() > 0.5f;
				if (flag4)
				{
					num8 += num12;
				}
				else if (flag)
				{
					num10 += num12;
				}
				else
				{
					num6 -= num12 * 30f * dt;
				}
				float num13 = (val3.dpad.right.isPressed ? 1 : 0) - (val3.dpad.left.isPressed ? 1 : 0);
				if (flag)
				{
					num9 += num13;
				}
				else if (!flag4)
				{
					num7 += num13;
				}
				flag2 = flag2 || flag;
				flag3 = flag3 || flag4;
			}
			if (num8 != 0f)
			{
				Effects.AddBrightness(num8 * 1.5f * dt);
			}
			if (num9 != 0f)
			{
				MovePose(num9 * 0.25f * dt * (flag3 ? 0.3f : 1f) * ((flag2 && !flag) ? 3f : 1f));
			}
			if (num10 != 0f)
			{
				Effects.MoveFocus(num10 * 0.7f * dt * (flag3 ? 0.25f : 1f) * ((flag2 && !flag) ? 3f : 1f));
			}
			float num14 = (flag3 ? 0.3f : 1f);
			_yaw = (_yaw + num4 * num14) % 360f;
			_pitch = U.Clamp(_pitch + num5 * num14, -89f, 89f);
			_roll = U.Clamp(_roll + num7 * 45f * dt * num14, -90f, 90f);
			_fov = U.Clamp(_fov + num6 * num14, 10f, 100f);
			Quaternion val4 = Quaternion.Euler(_pitch, _yaw, 0f);
			Vector3 val5 = val4 * new Vector3(num, 0f, num3) + Vector3.up * num2;
			if (((Vector3)(ref val5)).sqrMagnitude > 1f)
			{
				((Vector3)(ref val5)).Normalize();
			}
			float num15 = 3.5f * PhotoConfig.MoveSpeed.Value * (flag2 ? 3.4f : 1f) * (flag3 ? 0.2f : 1f);
			_pos += val5 * num15 * dt;
			float value2 = PhotoConfig.MaxDistance.Value;
			Vector3 val6 = _pos - _anchor;
			if (((Vector3)(ref val6)).sqrMagnitude > value2 * value2)
			{
				_pos = _anchor + ((Vector3)(ref val6)).normalized * value2;
			}
			Transform transform = ((Component)_cam).transform;
			transform.position = _pos;
			transform.rotation = ((_roll == 0f) ? val4 : (val4 * Quaternion.Euler(0f, 0f, 0f - _roll)));
			_cam.fieldOfView = _fov;
		}

		private static float Dead(float v)
		{
			if (!(Math.Abs(v) < 0.15f))
			{
				return v;
			}
			return 0f;
		}

		private void FadeInterface()
		{
			_faded.Clear();
			foreach (Object item in U.Each<Object>((Il2CppArrayBase<Object>)(object)Object.FindObjectsOfType(Il2CppType.Of<Canvas>())))
			{
				Canvas val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<Canvas>() : null);
				if ((Object)(object)val == (Object)null || !((Behaviour)val).enabled || !val.isRootCanvas || !((Component)val).gameObject.activeInHierarchy)
				{
					continue;
				}
				try
				{
					CanvasGroup val2 = ((Component)val).GetComponent<CanvasGroup>();
					bool flag = (Object)(object)val2 == (Object)null;
					if (flag)
					{
						val2 = ((Component)val).gameObject.AddComponent<CanvasGroup>();
					}
					_faded.Add((val2, flag, val2.alpha));
					val2.alpha = 0f;
				}
				catch (Exception ex)
				{
					Log.Debug("[Photo mode] canvas: " + ex.Message);
				}
			}
		}

		private void RestoreInterface()
		{
			foreach (var (val, flag, alpha) in _faded)
			{
				try
				{
					if (U.Alive((Object)(object)val))
					{
						if (flag)
						{
							Object.Destroy((Object)(object)val);
						}
						else
						{
							val.alpha = alpha;
						}
					}
				}
				catch (Exception ex)
				{
					Log.Debug("[Photo mode] canvas restore: " + ex.Message);
				}
			}
			_faded.Clear();
		}

		public string Command(string arg)
		{
			//IL_08c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0904: Unknown result type (might be due to invalid IL or missing references)
			//IL_0909: Unknown result type (might be due to invalid IL or missing references)
			//IL_090e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			string[] a = (arg ?? "").Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			string text = ((a.Length != 0) ? a[0] : "status");
			CultureInfo inv = CultureInfo.InvariantCulture;
			switch (text)
			{
			case "on":
				Enter();
				break;
			case "off":
				Exit("command");
				break;
			case "photo":
				if (Active)
				{
					TakePhoto();
				}
				break;
			case "quick":
				if (!Active)
				{
					QuickPhoto.Take(this);
				}
				break;
			case "quickpad":
			{
				string text2 = ((a.Length > 1) ? a[1] : "chord");
				float viewSeconds = F(2, 1f);
				switch (text2)
				{
				case "view":
					QuickPhoto.Simulate(viewSeconds, -1f, -1f);
					break;
				case "late":
					QuickPhoto.Simulate(viewSeconds, 0.6f, 0.75f);
					break;
				case "same":
					QuickPhoto.Simulate(viewSeconds, 0f, 0.25f);
					break;
				default:
					QuickPhoto.Simulate(viewSeconds, 0.1f, 0.25f);
					break;
				}
				break;
			}
			case "dof":
				if (Active)
				{
					if (a.Length > 1 && Enum.TryParse<FocusMode>(a[1], ignoreCase: true, out var result))
					{
						Effects.SetFocusMode(result);
					}
					else
					{
						Effects.NextFocusMode();
					}
				}
				break;
			case "dofq":
				if (Active && a.Length >= 2)
				{
					PhotoEffects.DofQuality qualityTo = new PhotoEffects.DofQuality
					{
						Game = (a[1] == "game"),
						BlurScale = 1f
					};
					if (!qualityTo.Game)
					{
						qualityTo.Res = (DepthOfFieldResolution)((a[1] == "half") ? 2 : ((!(a[1] == "quarter")) ? 1 : 4));
						qualityTo.Near = (int)F(2, 8f);
						qualityTo.Far = (int)F(3, 16f);
						qualityTo.Hq = F(4, 1f) > 0f;
						qualityTo.BlurScale = F(5, 1f);
					}
					Effects.SetQualityTo(qualityTo);
				}
				break;
			case "focus":
				if (Active)
				{
					if (a.Length > 1 && a[1] == "near")
					{
						Effects.MoveFocus(-0.5f);
					}
					else if (a.Length > 1 && a[1] == "far")
					{
						Effects.MoveFocus(0.5f);
					}
					else
					{
						Effects.SetFocusDistance(F(1, Effects.FocusDistance));
					}
				}
				break;
			case "aperture":
				if (Active)
				{
					if (a.Length > 1 && a[1] == "wider")
					{
						Effects.NextAperture(-1, wrap: false);
					}
					else if (a.Length > 1 && a[1] == "narrower")
					{
						Effects.NextAperture(1, wrap: false);
					}
					else if (a.Length > 1 && a[1] == "pad")
					{
						Effects.NextAperture((a.Length > 2) ? 1 : (-1), wrap: true);
					}
					else
					{
						Effects.NextAperture((int)F(1, Effects.ApertureIndex) - Effects.ApertureIndex, wrap: false);
					}
				}
				break;
			case "filter":
				if (Active)
				{
					if (a.Length > 1)
					{
						Effects.NextFilter((int)F(1) - Effects.FilterIndex);
					}
					else
					{
						Effects.NextFilter();
					}
				}
				break;
			case "bright":
				if (Active)
				{
					Effects.AddBrightness(F(1) - Effects.Brightness);
				}
				break;
			case "character":
				if (Active)
				{
					ToggleCharacter();
				}
				break;
			case "time":
				if (Active)
				{
					CycleTime();
				}
				break;
			case "hints":
				ToggleHints();
				break;
			case "reset":
				ResetView();
				break;
			case "look":
				_pitch = F(1, _pitch);
				_yaw = F(2, _yaw);
				break;
			case "fov":
				_fov = U.Clamp(F(1, _fov), 10f, 100f);
				break;
			case "roll":
				_roll = U.Clamp(F(1), -90f, 90f);
				break;
			case "move":
				if (Active)
				{
					_pos += Quaternion.Euler(_pitch, _yaw, 0f) * new Vector3(F(1), F(2), F(3));
				}
				break;
			case "renderers":
				return Renderers(F(1, 3f));
			case "anims":
				return Anims();
			case "cloth":
				if (a.Length > 1 && (a[1] == "on" || a[1] == "off"))
				{
					PhotoConfig.LiveCloth.Value = a[1] == "on";
					UpdateCloth();
				}
				return Describe() + " " + ClothState();
			case "pose":
				return PoseCommand(a, (int i, float d) => F(i, d));
			case "clip":
				return ClipCommand((int)F(1, -1f), F(2, 0.5f));
			case "aim":
				return Aim(F(1, 2.5f), F(2, 1.3f), F(3), F(4, 1f));
			}
			return Describe();
			float F(int i, float d = 0f)
			{
				if (a.Length <= i || !float.TryParse(a[i], NumberStyles.Float, inv, out var result2))
				{
					return d;
				}
				return result2;
			}
		}

		private string Renderers(float within)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = GameView.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return "no player";
			}
			Vector3 val = GameView.Position(localPlayer);
			Transform transform = ((CustomMonoBehaviour)localPlayer).transform;
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			foreach (Object item in U.Each<Object>((Il2CppArrayBase<Object>)(object)Object.FindObjectsOfType(Il2CppType.Of<Renderer>())))
			{
				Renderer val2 = ((item != null) ? ((Il2CppObjectBase)item).TryCast<Renderer>() : null);
				if (!U.Alive((Object)(object)val2) || !val2.enabled || !((Component)val2).gameObject.activeInHierarchy)
				{
					continue;
				}
				Bounds bounds = val2.bounds;
				Vector3 val3 = ((Bounds)(ref bounds)).center - val;
				if (!(((Vector3)(ref val3)).magnitude > within))
				{
					Transform transform2 = ((Component)val2).transform;
					bool value = transform2.IsChildOf(transform);
					string value2 = (((Object)(object)transform2.root != (Object)null) ? ((Object)transform2.root).name : "?");
					string value3 = (((Object)(object)transform2.parent != (Object)null) ? ((Object)transform2.parent).name : "-");
					StringBuilder stringBuilder2 = stringBuilder;
					StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(48, 7, stringBuilder2);
					handler.AppendLiteral(" | ");
					handler.AppendFormatted(((MemberInfo)((Object)val2).GetIl2CppType()).Name);
					handler.AppendLiteral(" '");
					handler.AppendFormatted(((Object)val2).name);
					handler.AppendLiteral("' parent='");
					handler.AppendFormatted(value3);
					handler.AppendLiteral("' top='");
					handler.AppendFormatted(value2);
					handler.AppendLiteral("' underPlayer=");
					handler.AppendFormatted(value);
					handler.AppendLiteral(" off=");
					handler.AppendFormatted(val2.forceRenderingOff);
					handler.AppendLiteral(" layer=");
					handler.AppendFormatted(((Component)val2).gameObject.layer);
					stringBuilder2.Append(ref handler);
					if (++num >= 40)
					{
						break;
					}
				}
			}
			string text = "";
			try
			{
				Weapon currentWeapon = localPlayer.CurrentWeapon;
				text = $" weaponRoot='{(U.Alive((Object)(object)((currentWeapon != null) ? currentWeapon.Root : null)) ? ((Object)currentWeapon.Root).name : "none")}' rootTop='{(U.Alive((Object)(object)((currentWeapon != null) ? currentWeapon.Root : null)) ? ((Object)currentWeapon.Root.transform.root).name : "-")}'";
			}
			catch (Exception ex)
			{
				text = " weapon: " + ex.Message;
			}
			return $"RENDERERS {num} within {within:0.#} m of '{((Object)transform).name}'{text}{stringBuilder}";
		}

		public string Describe()
		{
			return $"photo mode={Plugin.Mode} ms={FrameMs():0.0} active={Active} time={Time} timeScale={Time.timeScale:0.##} faded={_faded.Count} hints={HintsShown} fov={_fov:0} roll={_roll:0} characterHidden={_hidden.Count} photos={Photos} {QuickPhoto.State()} {PoseState()} cloth={_cloth.Count} {Effects.Describe()} last='{LastResult}'";
		}

		public void CycleWeapons()
		{
			Weapons = ((Weapons == WeaponMode.Auto) ? WeaponMode.InHand : ((Weapons == WeaponMode.InHand) ? WeaponMode.PutAway : ((Weapons == WeaponMode.PutAway) ? WeaponMode.Hidden : WeaponMode.Auto)));
			ApplyWeapons();
			PhotoOverlay.Toast(T.Get("Weapon") + ": " + WeaponText(), 2f);
		}

		public string WeaponText()
		{
			return T.Get((Weapons == WeaponMode.Auto) ? "by pose" : ((Weapons == WeaponMode.InHand) ? "in hand" : ((Weapons == WeaponMode.PutAway) ? "put away" : "hidden")));
		}

		private void ShowWeapons()
		{
			foreach (Renderer item in _weaponHidden)
			{
				try
				{
					if (U.Alive((Object)(object)item))
					{
						item.forceRenderingOff = false;
					}
				}
				catch
				{
				}
			}
			_weaponHidden.Clear();
		}

		private static bool WeaponDrawn(Player p)
		{
			try
			{
				return (Object)(object)p != (Object)null && p.IsHoldWeapon();
			}
			catch
			{
				return false;
			}
		}

		private static void DrawWeapon(Player p, bool drawn)
		{
			try
			{
				if ((Object)(object)p != (Object)null && p.IsHoldWeapon() != drawn)
				{
					p.HoldWeapon(drawn, true);
				}
			}
			catch (Exception ex)
			{
				Log.Warn("[Photo mode] weapon: " + ex.Message);
			}
		}

		private void ApplyWeapons()
		{
			Player localPlayer = GameView.LocalPlayer;
			if (!PoseHeld)
			{
				ShowWeapons();
				if (_weaponWasDrawn.HasValue)
				{
					DrawWeapon(localPlayer, _weaponWasDrawn.Value);
					_weaponWasDrawn = null;
				}
				return;
			}
			bool valueOrDefault = _weaponWasDrawn == true;
			if (!_weaponWasDrawn.HasValue)
			{
				valueOrDefault = WeaponDrawn(localPlayer);
				_weaponWasDrawn = valueOrDefault;
			}
			bool flag = ((PoseIndex >= 0) ? PhotoPoses.All[PoseIndex].Armed : _weaponWasDrawn.Value);
			bool drawn = Weapons == WeaponMode.InHand || (Weapons == WeaponMode.Auto && flag) || (Weapons == WeaponMode.Hidden && _weaponWasDrawn.Value);
			DrawWeapon(localPlayer, drawn);
			if (Weapons != WeaponMode.Hidden)
			{
				ShowWeapons();
			}
			else if (_weaponHidden.Count == 0)
			{
				HideWeapons(localPlayer, _weaponHidden);
			}
		}

		internal static void HideWeapons(Player player, List<Renderer> into)
		{
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			try
			{
				HideWeapon(player.CurrentWeapon, into);
			}
			catch (Exception ex)
			{
				Log.Warn("[Photo mode] hiding the weapon: " + ex.Message);
			}
			try
			{
				HideWeapon(player.ReserveWeapon, into);
			}
			catch
			{
			}
		}

		private static void HideWeapon(Weapon weapon, List<Renderer> into)
		{
			if (weapon == null)
			{
				return;
			}
			WeaponAttachments weaponAttachments = weapon.WeaponAttachments;
			if (!U.Alive((Object)(object)weaponAttachments))
			{
				if (U.Alive((Object)(object)weapon.Root))
				{
					HidePart(weapon.Root.transform, into);
				}
				return;
			}
			HideList(weaponAttachments.HandWeaponMeshes, into);
			HideList(weaponAttachments.BackWeaponMeshes, into);
			HideList(weaponAttachments.SheathMeshes, into);
			HidePart(weaponAttachments.RightWeapon, into);
			HidePart(weaponAttachments.LeftWeapon, into);
			HidePart(weaponAttachments.BackWeapon, into);
			HidePart(weaponAttachments.Sheath, into);
		}

		private static void HideList(List<Renderer> list, List<Renderer> into)
		{
			if (list != null)
			{
				for (int i = 0; i < list.Count; i++)
				{
					HideOne(list[i], into);
				}
			}
		}

		private static void HidePart(Transform part, List<Renderer> into)
		{
			if (!U.Alive((Object)(object)part))
			{
				return;
			}
			foreach (Renderer item in U.Each<Renderer>(((Component)part).GetComponentsInChildren<Renderer>(true)))
			{
				HideOne(item, into);
			}
		}

		private static void HideOne(Renderer r, List<Renderer> into)
		{
			if (U.Alive((Object)(object)r) && !r.forceRenderingOff)
			{
				r.forceRenderingOff = true;
				into.Add(r);
			}
		}

		private static Animator PlayerAnimator()
		{
			Player localPlayer = GameView.LocalPlayer;
			try
			{
				return (localPlayer != null) ? localPlayer._Animator : null;
			}
			catch
			{
				return null;
			}
		}

		private static bool InCombat()
		{
			try
			{
				Player localPlayer = GameView.LocalPlayer;
				return localPlayer != null && localPlayer.IsInCombat();
			}
			catch
			{
				return false;
			}
		}

		private string PoseBlocker()
		{
			if (!Active)
			{
				return "";
			}
			if (SessionActive && InCombat())
			{
				return T.Get("Not while in combat.");
			}
			if (!U.Alive((Object)(object)PlayerAnimator()))
			{
				return T.Get("The character can't pose right now.");
			}
			return null;
		}

		public void NextPose(int step = 1)
		{
			int num = PhotoPoses.All.Length;
			int num2 = ((PoseIndex >= 0) ? PoseIndex : ((step > 0) ? (-1) : num)) + step;
			if (num2 < 0 || num2 >= num)
			{
				DropPose(null);
				PhotoOverlay.Toast(T.Get("Pose") + ": " + T.Get("none"));
			}
			else
			{
				SetPose(num2);
			}
		}

		public bool SetPose(int i, float moment = -1f)
		{
			if (i < 0 || i >= PhotoPoses.All.Length)
			{
				DropPose(null);
				return false;
			}
			string text = PoseBlocker();
			if (text != null)
			{
				if (text.Length > 0)
				{
					PhotoOverlay.Toast(text);
				}
				return false;
			}
			PhotoPoses.Pose pose = PhotoPoses.All[i];
			Animator anim = PlayerAnimator();
			AnimationClip val = FindClip(anim, pose.Clip);
			if (!U.Alive((Object)(object)val))
			{
				Log.Warn($"[Photo mode] pose '{pose.Name}': no '{pose.Clip}' animation");
				PhotoOverlay.Toast(T.Get("The character can't pose right now."));
				return false;
			}
			PoseIndex = i;
			PoseMoment = ((moment >= 0f) ? U.Clamp(moment, 0f, 1f) : pose.Moment);
			Hold(anim, val, PoseMoment);
			PhotoOverlay.Toast(T.Get("Pose") + ": " + PhotoPoses.NameOf(i), 2f);
			return true;
		}

		public void MovePose(float by)
		{
			if (PoseHeld && by != 0f)
			{
				float num = PoseMoment + by;
				num -= (float)Math.Floor(num);
				PoseMoment = num;
				Sample();
				_settleAt = Time.realtimeSinceStartup + 0.2f;
			}
		}

		internal static AnimationClip FindClip(Animator anim, string name)
		{
			if (!U.Alive((Object)(object)anim))
			{
				return null;
			}
			RuntimeAnimatorController runtimeAnimatorController = anim.runtimeAnimatorController;
			if ((Object)(object)runtimeAnimatorController == (Object)null)
			{
				return null;
			}
			try
			{
				AnimatorOverrideController val = ((Il2CppObjectBase)runtimeAnimatorController).TryCast<AnimatorOverrideController>();
				if ((Object)(object)val != (Object)null)
				{
					AnimationClip val2 = val[name];
					if (U.Alive((Object)(object)val2))
					{
						return val2;
					}
				}
			}
			catch
			{
			}
			foreach (AnimationClip item in U.Each<AnimationClip>((Il2CppArrayBase<AnimationClip>)(object)runtimeAnimatorController.animationClips))
			{
				if (U.Alive((Object)(object)item) && ((Object)item).name == name)
				{
					return item;
				}
			}
			return null;
		}

		private void Hold(Animator anim, AnimationClip clip, float moment)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_holdAnim == (Object)null || ((Il2CppObjectBase)_holdAnim).Pointer != ((Il2CppObjectBase)anim).Pointer)
			{
				ReleaseHold();
				_holdAnim = anim;
				_holdKeep = anim.keepAnimatorStateOnDisable;
				_holdEnabled = ((Behaviour)anim).enabled;
				_holdRootPos = ((Component)anim).transform.localPosition;
				_holdRootRot = ((Component)anim).transform.localRotation;
				_holdBase = null;
				try
				{
					Il2CppStructArray<AnimatorClipInfo> currentAnimatorClipInfo = anim.GetCurrentAnimatorClipInfo(0);
					if (currentAnimatorClipInfo != null && ((Il2CppArrayBase<AnimatorClipInfo>)(object)currentAnimatorClipInfo).Length > 0)
					{
						AnimatorClipInfo val = ((Il2CppArrayBase<AnimatorClipInfo>)(object)currentAnimatorClipInfo)[0];
						_holdBase = ((AnimatorClipInfo)(ref val)).clip;
					}
				}
				catch
				{
				}
				_holdHp = GameView.Hp(GameView.LocalPlayer);
				anim.keepAnimatorStateOnDisable = true;
				((Behaviour)anim).enabled = false;
				Log.Info("[Photo mode] pose held");
			}
			_holdClip = clip;
			PoseMoment = moment;
			Sample();
			ApplyWeapons();
			_settleAt = Time.realtimeSinceStartup + 0.2f;
		}

		private void Sample()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			Animator holdAnim = _holdAnim;
			if (!U.Alive((Object)(object)holdAnim) || !U.Alive((Object)(object)_holdClip))
			{
				return;
			}
			try
			{
				if (((Behaviour)holdAnim).enabled)
				{
					((Behaviour)holdAnim).enabled = false;
				}
				if (U.Alive((Object)(object)_holdBase))
				{
					_holdBase.SampleAnimation(((Component)holdAnim).gameObject, 0f);
				}
				_holdClip.SampleAnimation(((Component)holdAnim).gameObject, PoseMoment * _holdClip.length);
			}
			finally
			{
				((Component)holdAnim).transform.localPosition = _holdRootPos;
				((Component)holdAnim).transform.localRotation = _holdRootRot;
			}
		}

		private void TickPose()
		{
			if (!PoseHeld)
			{
				return;
			}
			if (!U.Alive((Object)(object)_holdAnim))
			{
				_holdAnim = null;
				PoseIndex = -1;
				return;
			}
			if (GameView.Hp(GameView.LocalPlayer) < _holdHp - 0.01f)
			{
				DropPose(T.Get("The pose was dropped: you were hit."));
				return;
			}
			if (SessionActive && InCombat())
			{
				DropPose(T.Get("The pose was dropped: in combat."));
				return;
			}
			Sample();
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (_settleAt > 0f && ClothLive)
			{
				_settleAt = -1f;
			}
			if (_settleAt > 0f && realtimeSinceStartup >= _settleAt && Time == TimeMode.Stopped && _setTime == 0f && Time.timeScale == 0f)
			{
				_settleAt = -1f;
				_settleScale = ((_timeBefore > 0f) ? _timeBefore : 1f);
				Time.timeScale = _settleScale;
				_settleUntil = realtimeSinceStartup + 0.5f;
			}
			if (_settleUntil > 0f && realtimeSinceStartup >= _settleUntil)
			{
				EndSettle();
			}
		}

		private void EndSettle()
		{
			if (!(_settleUntil < 0f))
			{
				_settleUntil = -1f;
				if (_settleScale >= 0f && Time.timeScale == _settleScale && _setTime >= 0f)
				{
					Time.timeScale = _setTime;
				}
				_settleScale = -1f;
			}
		}

		public void DropPose(string why)
		{
			bool poseHeld = PoseHeld;
			ReleaseHold();
			PoseIndex = -1;
			if (poseHeld && why != null)
			{
				PhotoOverlay.Toast(why);
				Log.Info("[Photo mode] pose dropped: " + why);
			}
		}

		private void ReleaseHold()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			EndSettle();
			_settleAt = -1f;
			Animator holdAnim = _holdAnim;
			_holdAnim = null;
			_holdClip = null;
			ApplyWeapons();
			if (!U.Alive((Object)(object)holdAnim))
			{
				return;
			}
			try
			{
				((Component)holdAnim).transform.localPosition = _holdRootPos;
				((Component)holdAnim).transform.localRotation = _holdRootRot;
				((Behaviour)holdAnim).enabled = _holdEnabled;
				holdAnim.keepAnimatorStateOnDisable = _holdKeep;
				Log.Info("[Photo mode] pose released");
			}
			catch (Exception ex)
			{
				Log.Warn("[Photo mode] pose release: " + ex.Message);
			}
		}

		private string PoseCommand(string[] a, Func<int, float, float> f)
		{
			if (a.Length < 2)
			{
				return Describe();
			}
			string text = a[1];
			switch (text)
			{
			case "off":
			case "none":
				DropPose(null);
				break;
			case "next":
				NextPose();
				break;
			case "prev":
				NextPose(-1);
				break;
			case "weapon":
			{
				if (a.Length > 2 && Enum.TryParse<WeaponMode>(a[2], ignoreCase: true, out var result2))
				{
					Weapons = result2;
					ApplyWeapons();
				}
				else
				{
					CycleWeapons();
				}
				break;
			}
			case "moment":
				if (PoseHeld)
				{
					MovePose(f(2, PoseMoment) - PoseMoment);
				}
				break;
			default:
			{
				if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
				{
					SetPose(result, f(2, -1f));
				}
				break;
			}
			}
			return Describe();
		}

		private string Anims()
		{
			Animator val = PlayerAnimator();
			if (!U.Alive((Object)(object)val))
			{
				return "ANIMS no animator";
			}
			RuntimeAnimatorController runtimeAnimatorController = val.runtimeAnimatorController;
			if ((Object)(object)runtimeAnimatorController == (Object)null)
			{
				return "ANIMS no controller";
			}
			LoadClips(runtimeAnimatorController);
			StringBuilder stringBuilder = new StringBuilder();
			bool value = false;
			try
			{
				value = val.isHuman;
			}
			catch
			{
			}
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(38, 5, stringBuilder2);
			handler.AppendLiteral("controller '");
			handler.AppendFormatted(((Object)runtimeAnimatorController).name);
			handler.AppendLiteral("' (");
			handler.AppendFormatted(((MemberInfo)((Object)runtimeAnimatorController).GetIl2CppType()).Name);
			handler.AppendLiteral(") human=");
			handler.AppendFormatted(value);
			handler.AppendLiteral(" layers=");
			handler.AppendFormatted(val.layerCount);
			handler.AppendLiteral(" clips=");
			handler.AppendFormatted(_clips.Count);
			stringBuilder2.AppendLine(ref handler);
			for (int i = 0; i < _clips.Count; i++)
			{
				stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}\t{1}\t{2:0.00}s\tloop={3}", i, ((Object)_clips[i]).name, _clips[i].length, ((Motion)_clips[i]).isLooping));
			}
			File.WriteAllText(Path.Combine(Paths.BepInExRootPath, "photomode-anims.txt"), stringBuilder.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			int num = 0;
			PhotoPoses.Pose[] all = PhotoPoses.All;
			for (int j = 0; j < all.Length; j++)
			{
				PhotoPoses.Pose pose = all[j];
				if (!U.Alive((Object)(object)FindClip(val, pose.Clip)))
				{
					num++;
				}
			}
			return $"ANIMS {_clips.Count} clips, human={value}, poses missing={num}, written to photomode-anims.txt";
		}

		private void LoadClips(RuntimeAnimatorController ctrl)
		{
			_clips.Clear();
			HashSet<string> hashSet = new HashSet<string>();
			foreach (AnimationClip item in U.Each<AnimationClip>((Il2CppArrayBase<AnimationClip>)(object)ctrl.animationClips))
			{
				if (U.Alive((Object)(object)item) && hashSet.Add(((Object)item).name))
				{
					_clips.Add(item);
				}
			}
		}

		private string ClipCommand(int i, float t)
		{
			Animator val = PlayerAnimator();
			if (!Active || !U.Alive((Object)(object)val))
			{
				return "CLIP photo mode is off";
			}
			if (_clips.Count == 0 && (Object)(object)val.runtimeAnimatorController != (Object)null)
			{
				LoadClips(val.runtimeAnimatorController);
			}
			if (i < 0 || i >= _clips.Count)
			{
				return $"CLIP index 0..{_clips.Count - 1}";
			}
			PoseIndex = -2;
			_holdLabel = ((Object)_clips[i]).name;
			Hold(val, _clips[i], U.Clamp(t, 0f, 1f));
			return Describe();
		}

		private string Aim(float dist, float height, float angle, float lookHeight)
		{
			//IL_001e: 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_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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_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_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = GameView.LocalPlayer;
			if (!Active || (Object)(object)localPlayer == (Object)null)
			{
				return "AIM photo mode is off";
			}
			Vector3 val = GameView.Position(localPlayer);
			Vector3 forward = ((CustomMonoBehaviour)localPlayer).transform.forward;
			forward.y = 0f;
			if (((Vector3)(ref forward)).sqrMagnitude < 0.01f)
			{
				forward = Vector3.forward;
			}
			((Vector3)(ref forward)).Normalize();
			_pos = val + Quaternion.Euler(0f, angle, 0f) * forward * dist + Vector3.up * height;
			Quaternion val2 = Quaternion.LookRotation(val + Vector3.up * lookHeight - _pos);
			Vector3 eulerAngles = ((Quaternion)(ref val2)).eulerAngles;
			_yaw = eulerAngles.y;
			_pitch = ((eulerAngles.x > 180f) ? (eulerAngles.x - 360f) : eulerAngles.x);
			_roll = 0f;
			return $"AIM at {dist:0.0} m, {angle:0}°";
		}

		private string PoseState()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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)
			Animator val = PlayerAnimator();
			Vector3 val2 = GameView.Position(GameView.LocalPlayer);
			string text = (U.Alive((Object)(object)val) ? ((Behaviour)val).enabled.ToString() : "-");
			return string.Format(CultureInfo.InvariantCulture, "pose={0} poseName='{1}' label='{9}' moment={2:0.00} held={3} animOn={4} settling={5} at={6:0.00},{7:0.00},{8:0.00} weapons={10} weaponsHidden={11} weaponPartsOff={12} weaponDrawn={13}", PoseIndex, PoseName, PoseMoment, PoseHeld, text, _settleUntil > 0f, val2.x, val2.y, val2.z, PhotoPoses.LabelOf(PoseIndex), Weapons, WeaponsHidden, _weaponHidden.Count, WeaponDrawn(GameView.LocalPlayer));
		}
	}
	internal enum TimeMode
	{
		Running,
		Stopped,
		Slow
	}
	public interface IPhotoHost
	{
		bool SessionActive { get; }

		bool Busy { get; }

		string BackKey { get; }

		string Blocker();

		string MustExit();
	}
	public static class PhotoModeApi
	{
		public static int ApiVersion => 3;

		public static string PluginVersion => "1.0.2";

		public static bool Hosted => Plugin.Mode == PluginMode.Hosted;

		public static IPhotoHost Host { get; private set; }

		public static bool Active => PhotoMode.Instance.Active;

		public static bool ViewUsed => QuickPhoto.ViewUsed;

		public static bool PanelShown
		{
			get
			{
				PhotoMode instance = PhotoMode.Instance;
				if (instance.Active && instance.HintsShown)
				{
					if (instance.PhotoFrame >= 0)
					{
						return Time.frameCount > instance.PhotoFrame + 1;
					}
					return true;
				}
				return false;
			}
		}

		public static string PoseClip => PhotoMode.Instance.PoseClip;

		public static float PoseMoment => PhotoMode.Instance.PoseMoment;

		public static bool PoseWeaponsHidden => PhotoMode.Instance.WeaponsHidden;

		public static void Attach(IPhotoHost host)
		{
			Host = host;
			Log.Info("[Photo mode] run by another mod from now on");
		}

		public static bool Enter()
		{
			return PhotoMode.Instance.Enter();
		}

		public static void Exit(string why)
		{
			PhotoMode.Instance.Exit(why);
		}

		public static void Tick()
		{
			PhotoMode.Instance.Tick();
		}

		public static void OnGUI()
		{
			PhotoOverlay.OnGUI();
		}

		public static string Command(string arg)
		{
			return PhotoMode.Instance.Command(arg);
		}

		public static string Describe()
		{
			return PhotoMode.Instance.Describe();
		}
	}
	internal static class PhotoOverlay
	{
		private const uint PanelColor = 921620u;

		private const uint TextColor = 15262420u;

		private const uint MutedColor = 10393482u;

		private const uint AccentColor = 13215850u;

		private static readonly Dictionary<(int Size, uint Color, int Align, bool Serif), GUIStyle> Styles = new Dictionary<(int, uint, int, bool), GUIStyle>();

		private static Font _serif;

		private static bool _serifTried;

		private static string _toast;

		private static float _toastUntil;

		private static int _toastFrom;

		private static bool _usingPad;

		private static float _s = 1f;

		private const string Sep = "     /     ";

		private static Texture2D _white;

		private static bool PlayStation
		{
			get
			{
				try
				{
					Gamepad current = Gamepad.current;
					string text = ((current != null) ? ((InputControl)current).layout : null) ?? "";
					return text.IndexOf("DualShock", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("DualSense", StringComparison.OrdinalIgnoreCase) >= 0;
				}
				catch
				{
					return false;
				}
			}
		}

		public static void Toast(string text, float seconds = 3f, int fromFrame = 0)
		{
			_toast = text;
			_toastUntil = Time.realtimeSinceStartup + seconds;
			_toastFrom = fromFrame;
		}

		public static void OnGUI()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Event current = Event.current;
				if (current == null || (int)current.type != 7)
				{
					return;
				}
				PhotoMode instance = PhotoMode.Instance;
				_s = Math.Max(0.5f, (float)Screen.height / 1080f);
				GUI.color = U.Color(1f, 1f, 1f, 1f);
				bool flag = instance.PhotoFrame >= 0 && Time.frameCount <= instance.PhotoFrame + 1;
				if (instance.Active && !flag && instance.HintsShown)
				{
					if (instance.Effects.Dof)
					{
						Vector2? focusOnScreen = instance.Effects.FocusOnScreen;
						if (focusOnScreen.HasValue)
						{
							Vector2 valueOrDefault = focusOnScreen.GetValueOrDefault();
							DrawFocusMarker(valueOrDefault);
						}
					}
					TrackDevice();
					DrawPanel(instance);
				}
				if (!flag && _toast != null && Time.realtimeSinceStartup < _toastUntil && Time.frameCount >= _toastFrom)
				{
					DrawToast(instance);
				}
			}
			catch (Exception ex)
			{
				Log.Debug("[Photo mode] overlay: " + ex.Message);
			}
		}

		private static void TrackDevice()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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)
			Gamepad current = Gamepad.current;
			Vector2 val;
			if (current != null)
			{
				val = ((InputControl<Vector2>)(object)current.leftStick).ReadValue();
				if (!(((Vector2)(ref val)).sqrMagnitude > 0.04f))
				{
					val = ((InputControl<Vector2>)(object)current.rightStick).ReadValue();
					if (!(((Vector2)(ref val)).sqrMagnitude > 0.04f) && !current.buttonSouth.isPressed && !current.buttonEast.isPressed && !current.buttonNorth.isPressed && !current.buttonWest.isPressed)
					{
						val = ((InputControl<Vector2>)(object)current.dpad).ReadValue();
						if (!(((Vector2)(ref val)).sqrMagnitude > 0.1f) && !current.leftShoulder.isPressed && !current.rightShoulder.isPressed)
						{
							goto IL_00b2;
						}
					}
				}
				_usingPad = true;
				return;
			}
			goto IL_00b2;
			IL_00b2:
			if (!_usingPad)
			{
				return;
			}
			Keyboard current2 = Keyboard.current;
			if (current2 == null || !((ButtonControl)current2.anyKey).isPressed)
			{
				Mouse current3 = Mouse.current;
				float num;
				if (current3 == null)
				{
					num = 0f;
				}
				else
				{
					val = ((InputControl<Vector2>)(object)((Pointer)current3).delta).ReadValue();
					num = ((Vector2)(ref val)).sqrMagnitude;
				}
				if (!(num > 4f))
				{
					return;
				}
			}
			_usingPad = false;
		}

		private static void DrawFocusMarker(Vector2 at)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			float num = 22f * _s;
			float num2 = 9f * _s;
			float num3 = Math.Max(1f, 2f * _s);
			float item = at.x - num;
			float item2 = at.x + num - num3;
			float item3 = at.y - num;
			float item4 = at.y + num - num3;
			(float, float, int, int)[] array = new(float, float, int, int)[4]
			{
				(item, item3, 1, 1),
				(item2, item3, -1, 1),
				(item, item4, 1, -1),
				(item2, item4, -1, -1)
			};
			for (int i = 0; i < array.Length; i++)
			{
				var (num4, num5, num6, num7) = array[i];
				Fill((num6 > 0) ? num4 : (num4 - num2 + num3), num5, num2, num3, 13215850u, 0.9f);
				Fill(num4, (num7 > 0) ? num5 : (num5 - num2 + num3), num3, num2, 13215850u, 0.9f);
			}
			Fill(at.x - num3 / 2f, at.y - num3 / 2f, num3, num3, 13215850u, 0.9f);
		}

		private static void DrawToast(PhotoMode photo)
		{
			float num = 640f * _s;
			float h = 40f * _s;
			float num2 = ((float)Screen.width - num) / 2f;
			float y = (float)Screen.height - (float)((photo.Active && photo.HintsShown) ? 228 : 90) * _s;
			Fill(num2, y, num, h, 921620u, 0.9f);
			Fill(num2, y, 3f * _s, h, 13215850u, 1f);
			Text(num2 + 16f * _s, y, num - 32f * _s, h, _toast, 13, 15262420u, (TextAnchor)4);
		}

		private static void DrawPanel(PhotoMode photo)
		{
			float num = Math.Min((float)Screen.width - 32f, 1040f * _s);
			float num2 = 158f * _s;
			float num3 = ((float)Screen.width - num) / 2f;
			float num4 = (float)Screen.height - num2 - 20f * _s;
			Fill(num3, num4, num, num2, 921620u, 0.92f);
			Fill(num3, num4, num, 2f * _s, 13215850u, 0.9f);
			float num5 = 20f * _s;
			Text(num3 + num5, num4 + 8f * _s, 300f * _s, 28f * _s, T.Get("PHOTO MODE"), 17, 15262420u, (TextAnchor)3, serif: true);
			Text(num3 + 260f * _s, num4 + 10f * _s, num - 280f * _s, 24f * _s, Status(photo), 11, 10393482u, (TextAnchor)5);
			string[] array = (_usingPad ? PadLines(photo) : KeyLines(photo));
			for (int i = 0; i < array.Length; i++)
			{
				Text(num3 + num5, num4 + (float)(44 + i * 26) * _s, num - 2f * num5, 22f * _s, array[i], 12, (i == array.Length - 1) ? 10393482u : 15262420u, (TextAnchor)3);
			}
		}

		private static string Status(PhotoMode photo)
		{
			PhotoEffects effects = photo.Effects;
			List<string> list = new List<string>();
			IPhotoHost host = PhotoModeApi.Host;
			list.Add((host != null && host.SessionActive) ? T.Get("Time keeps running in a session") : ((photo.Time == TimeMode.Stopped) ? T.Get("Time stopped") : ((photo.Time == TimeMode.Slow) ? T.Get("Slow motion") : T.Get("Time running"))));
			list.Add($"FOV {photo.Fov:0}°");
			if (Math.Abs(photo.Roll) >= 0.5f)
			{
				list.Add($"{T.Get("Tilt")} {photo.Roll:0}°");
			}
			if (effects.Dof)
			{
				string en = ((effects.FocusMode == FocusMode.Auto) ? "Auto focus" : ((effects.FocusMode == FocusMode.Character) ? "Character focus" : "Manual focus"));
				list.Add($"{T.Get(en)} {effects.FocusDistance.ToString((effects.FocusDistance < 10f) ? "0.00" : "0.0")} m  {effects.CurrentAperture.Name}");
			}
			if (effects.FilterIndex != 0)
			{
				list.Add(T.Get("Filter") + ": " + (GameView.Chinese ? effects.Current.Chinese : effects.Current.Name));
			}
			if (Math.Abs(effects.Brightness) >= 0.05f)
			{
				list.Add($"{T.Get("Brightness")} {effects.Brightness:+0.0;-0.0}");
			}
			if (photo.CharacterHidden)
			{
				list.Add(T.Get("Character") + ": " + T.Get("hidden"));
			}
			return string.Join("   ·   ", list);
		}

		private static string K(string key, string what)
		{
			return key + "  " + T.Get(what);
		}

		private static string PoseText(PhotoMode photo)
		{
			if (!photo.PoseHeld)
			{
				return T.Get("pose");
			}
			return $"{T.Get("pose")}: {photo.PoseName} {photo.PoseMoment:0.00}";
		}

		private static string WeaponText(PhotoMode photo)
		{
			return T.Get("weapon") + ": " + photo.WeaponText();
		}

		private static string[] KeyLines(PhotoMode photo)
		{
			//IL_000a: 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)
			string? text = ((object)PhotoConfig.OpenKey.Value/*cast due to .constrained prefix*/).ToString();
			string text2 = PhotoModeApi.Host?.BackKey;
			string key = "Esc / " + text + ((text2 != null && text2.Length > 0) ? (" / " + text2) : "");
			return new string[4]
			{
				string.Join("     /     ", K("WASD", "move"), K(T.Get("Mouse"), "look"), K("Q / E", "down / up"), K("Shift", "faster"), K("Ctrl", "slower")),
				string.Join("     /     ", K(T.Get("Wheel"), "zoom"), K("Z / X", "tilt"), K("- / =", "brightness"), K("R", "reset view"), K("Backspace", "reset effects")),
				string.Join("     /     ", K("P", "take photo"), K("F", "depth of field"), K("[ / ]", "focus"), K("; / '", "aperture"), K("V", "filter"), K("C", "character"), K("T", "time")),
				string.Join("     /     ", K("N", PoseText(photo)), K(", / .", "moment"), K("G", WeaponText(photo)), K("H", "hide this panel"), K(key, "back to your character"))
			};
		}

		private static string[] PadLines(PhotoMode photo)
		{
			bool playStation = PlayStation;
			string key = (playStation ? "Cross" : "A");
			string text = (playStation ? "Circle" : "B");
			string text2 = (playStation ? "Square" : "X");
			string key2 = (playStation ? "Triangle" : "Y");
			string text3 = (playStation ? "L1" : "LB");
			string text4 = (playStation ? "R1" : "RB");
			string text5 = (playStation ? "L2" : "LT");
			string text6 = (playStation ? "R2" : "RT");
			string text7 = (playStation ? "Create" : "View");
			string key3 = (playStation ? "Options" : "Menu");
			return new string[4]
			{
				string.Join("     /     ", K(T.Get("Left stick"), "move"), K(T.Get("Right stick"), "look"), K(text3 + " / " + text4, "down / up"), K(text6, "faster"), K(text5, "slower")),
				string.Join("     /     ", K(T.Get("D-pad") + " ↑↓", "zoom"), K(T.Get("D-pad") + " ←→", "tilt"), K(text5 + " + " + T.Get("D-pad") + " ↑↓", "brightness"), K(text6 + " + " + T.Get("D-pad") + " ↑↓", "focus")),
				string.Join("     /     ", K(key, "take photo"), K("L3", "depth of field"), K(text7 + " (" + text5 + " + " + text7 + ")", "aperture"), K("R3", "filter"), K(text2, "character"), K(key3, "time")),
				string.Join("     /     ", K(text5 + " + " + T.Get("D-pad") + " ←→", PoseText(photo)), K(text6 + " + " + T.Get("D-pad") + " ←→", "moment"), K(text5 + " + " + text2, WeaponText(photo)), K(key2, "hide this panel"), K(text + " / " + T.Get("hold") + " " + text7, "back to your character"))
			};
		}

		private static void Fill(float x, float y, float w, float h, uint rgb, float a)
		{
			//IL_002b: 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)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			if (!(w <= 0f) && !(h <= 0f))
			{
				if (!U.Alive((Object)(object)_white))
				{
					_white = Texture2D.whiteTexture;
				}
				GUI.color = U.Rgb(rgb, a);
				GUI.DrawTexture(U.Rect(x, y, w, h), (Texture)(object)_white);
				GUI.color = U.Color(1f, 1f, 1f, 1f);
			}
		}

		private static void Text(float x, float y, float w, float h, string text, int size, uint rgb, TextAnchor align, bool serif = false)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected I4, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			int num = Math.Max(8, (int)Math.Round((float)size * _s * 1.25f));
			(int, uint, int, bool) key = (num, rgb, (int)align, serif);
			if (!Styles.TryGetValue(key, out var value) || value == null)
			{
				value = new GUIStyle();
				value.fontSize = num;
				value.alignment = align;
				value.wordWrap = false;
				value.clipping = (TextClipping)1;
				value.normal.textColor = U.Rgb(rgb);
				if (serif)
				{
					value.font = SerifFont();
				}
				Styles[key] = value;
			}
			GUI.Label(U.Rect(x, y, w, h), text, value);
		}

		private static Font SerifFont()
		{
			if ((Object)(object)_serif != (Object)null || _serifTried)
			{
				return _serif;
			}
			_serifTried = true;
			try
			{
				_serif = Font.CreateDynamicFontFromOSFont("Times New Roman", 20);
				if ((Object)(object)_serif != (Object)null)
				{
					((Object)_serif).hideFlags = (HideFlags)61;
				}
			}
			catch
			{
			}
			return _serif;
		}
	}
	internal static class PhotoPoses
	{
		public readonly struct Pose
		{
			public readonly string Name;

			public readonly string Chinese;

			public readonly string Clip;

			public readonly float Moment;

			public readonly bool Armed;

			public Pose(string name, string chinese, string clip, float moment, bool armed = false)
			{
				Name = name;
				Chinese = chinese;
				Clip = clip;
				Moment = moment;
				Armed = armed;
			}
		}

		public static readonly Pose[] All = new Pose[31]
		{
			new Pose("Stand", "站立", "Idle", 0.3f, armed: true),
			new Pose("Stand, no weapon", "空手站立", "UnarmedIdle", 0.3f),
			new Pose("Look round", "环顾", "SpecialIdle2", 0.3f, armed: true),
			new Pose("Hand to head", "扶额", "SpecialIdle3", 0.65f, armed: true),
			new Pose("Arms crossed", "抱臂", "StoryAlert", 0.3f),
			new Pose("Look out", "远眺", "Survey", 0.5f),
			new Pose("Hand raised", "举手", "CallStone", 0.6f),
			new Pose("Offer", "递出", "GiveItem", 0.5f),
			new Pose("Hand on heart", "抚胸", "Trade", 0.5f),
			new Pose("Show", "展示", "ShowItem", 0.5f),
			new Pose("Embrace", "拥抱", "Hug", 0.6f),
			new Pose("Press", "按压", "PressButton", 0.5f),
			new Pose("Enchant", "附魔", "Enchantment", 0.5f, armed: true),
			new Pose("Empower", "强化", "MagicBuff", 0.5f, armed: true),
			new Pose("Kneel", "跪下", "RestOn", 0.9f),
			new Pose("Pray", "祈祷", "Blessed_Idle", 0.5f),
			new Pose("Bow in prayer", "俯首祈祷", "Blessed", 0.4f),
			new Pose("Kneel, cupped hands", "跪地捧手", "Branch_Breed", 0.35f),
			new Pose("Kneel, hand down", "跪地按手", "Branch_Link", 0.5f),
			new Pose("Crouch", "蹲下", "Branch_Rest", 0.5f),
			new Pose("Bound", "被缚", "BeTied", 0.5f),
			new Pose("Weary", "疲惫", "Weak", 0.8f, armed: true),
			new Pose("Fall to the knees", "跪倒", "Death", 0.4f),
			new Pose("Rising", "升起", "Reborn", 0.3f),
			new Pose("Sword stance", "持剑架势", "SwordHeavyHoldAttack1Ready", 0.9f, armed: true),
			new Pose("Katana stance", "太刀架势", "TachiSkillAttack3_Idle", 0.5f, armed: true),
			new Pose("Strike", "斩击", "SwordSkillAttack1", 0.35f, armed: true),
			new Pose("Lunge", "突刺", "SwordLightAttack3", 0.4f, armed: true),
			new Pose("Leap strike", "跃斩", "SwordFallAttack", 0.5f, armed: true),
			new Pose("Dodge", "闪避", "DodgeForward", 0.4f, armed: true),
			new Pose("Lightning", "雷击", "MagicLightning", 0.45f, armed: true)
		};

		public static string NameOf(int i)
		{
			if (i >= 0 && i < All.Length)
			{
				return $"{i + 1}/{All.Length}";
			}
			return "";
		}

		public static string LabelOf(int i)
		{
			if (i >= 0 && i < All.Length)
			{
				return All[i].Name;
			}
			return "";
		}
	}
	internal static class T
	{
		private static readonly Dictionary<string, string> Zh = new Dictionary<string, string>
		{
			["PHOTO MODE"] = "拍照模式",
			["Time stopped"] = "时间已停止",
			["Slow motion"] = "慢动作",
			["Time running"] = "时间流动中",
			["Time keeps running in a session"] = "联机中时间不会停止",
			["Time keeps running in a session."] = "联机中时间不会停止。",
			["Time can't be stopped with this input setting."] = "此输入设置下无法停止时间。",
			["Load a save first."] = "请先读取存档。",
			["Not while down."] = "倒地时无法使用。",
			["Controls capture unavailable; see the log."] = "无法接管操作,请查看日志。",
			["The game's camera isn't ready."] = "游戏镜头尚未就绪。",
			["Photo mode is off: update AI LIMIT Together."] = "拍照模式已关闭:请更新 AI LIMIT Together。",
			["Photo saved: "] = "照片已保存:",
			["The photo could not be saved; see the log."] = "照片保存失败,请查看日志。",
			["move"] = "移动",
			["look"] = "视角",
			["down / up"] = "下降 / 上升",
			["faster"] = "加速",
			["slower"] = "减速",
			["zoom"] = "缩放",
			["tilt"] = "倾斜",
			["brightness"] = "亮度",
			["take photo"] = "拍照",
			["depth of field"] = "景深",
			["filter"] = "滤镜",
			["focus"] = "对焦距离",
			["aperture"] = "光圈",
			["Auto focus"] = "自动对焦",
			["Character focus"] = "对焦角色",
			["Manual focus"] = "手动对焦",
			["character"] = "角色",
			["time"] = "时间",
			["reset view"] = "重置视角",
			["r