Decompiled source of Orbit Coop v0.1.0

BepInEx/plugins/GraveyardOrbit.Coop/GraveyardOrbit.Coop.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GraveyardOrbit.Audio;
using GraveyardOrbit.UI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Steamworks;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.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 GraveyardOrbit.Coop
{
	public sealed class CoopConfig
	{
		public readonly ConfigEntry<bool> Enabled;

		public readonly ConfigEntry<int> DebugSlot;

		public readonly ConfigEntry<int> DebugCount;

		public readonly ConfigEntry<float> SpawnSeparationDeg;

		public readonly ConfigEntry<int> TcpPort;

		public readonly ConfigEntry<string> SteamLobbyId;

		public readonly ConfigEntry<bool> UseSteam;

		public readonly ConfigEntry<int> SyncHz;

		public readonly ConfigEntry<string> HostKey;

		public readonly ConfigEntry<string> JoinKey;

		public readonly ConfigEntry<string> LeaveKey;

		public readonly ConfigEntry<bool> Verbose;

		public readonly ConfigEntry<bool> DebugOpenLobbyOnMenu;

		public CoopConfig(ConfigFile cfg)
		{
			Enabled = cfg.Bind<bool>("General", "Enabled", true, "Master switch for the co-op mod.");
			DebugSlot = cfg.Bind<int>("Spawn", "DebugSlot", -1, "Offline testing only: force a slot index (-1 = use session/vanilla).");
			DebugCount = cfg.Bind<int>("Spawn", "DebugPlayerCount", 1, "Offline testing only: simulate this many players when no session is active.");
			SpawnSeparationDeg = cfg.Bind<float>("Spawn", "SeparationDegrees", 15f, "Angular separation between players when exiting the base (degrees).");
			UseSteam = cfg.Bind<bool>("Network", "UseSteam", true, "true = Steam P2P lobbies (shipping path); false = direct TCP (dev testing).");
			TcpPort = cfg.Bind<int>("Network", "TcpPort", 27015, "TCP port for direct-connect dev testing.");
			SteamLobbyId = cfg.Bind<string>("Network", "SteamLobbyId", "", "Optional: lobby id to join directly (hex/uint64 string).");
			SyncHz = cfg.Bind<int>("Network", "ShipStateHz", 20, "Ship transform updates per second.");
			HostKey = cfg.Bind<string>("Hotkeys", "Host", "F8", "Host a session (creates a Steam lobby, or listens on TcpPort).");
			JoinKey = cfg.Bind<string>("Hotkeys", "Join", "F9", "Join a session (Steam invite overlay, or 127.0.0.1:TcpPort).");
			LeaveKey = cfg.Bind<string>("Hotkeys", "Leave", "F10", "Leave the current session.");
			Verbose = cfg.Bind<bool>("General", "VerboseLogging", false, "Log every network message.");
			DebugOpenLobbyOnMenu = cfg.Bind<bool>("Debug", "OpenLobbyOnMenu", false, "TESTING ONLY: auto-open the multiplayer lobby when the title menu builds.");
		}

		public static bool TryParseKey(string s, out Key key)
		{
			return Enum.TryParse<Key>(s, ignoreCase: true, out key);
		}
	}
	[BepInPlugin("agentbox.graveyardorbit.coop", "Graveyard Orbit Co-op", "0.1.0")]
	public sealed class CoopPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "agentbox.graveyardorbit.coop";

		public const string PluginVersion = "0.1.0";

		public const string BuildTag = "20";

		public const string BuildLabel = "MP BUILD 20";

		internal static CoopPlugin Instance;

		internal static ManualLogSource Log;

		internal static CoopConfig Cfg;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Cfg = new CoopConfig(((BaseUnityPlugin)this).Config);
			CoopSession.Configure(Cfg);
			_harmony = new Harmony("agentbox.graveyardorbit.coop");
			int num = 0;
			int num2 = 0;
			Type[] types = typeof(CoopPlugin).Assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Length != 0)
				{
					try
					{
						_harmony.PatchAll(type);
						num++;
					}
					catch (Exception ex)
					{
						num2++;
						Log.LogError((object)("Harmony patch " + type.Name + " failed (other hooks continue):\n" + ex));
					}
				}
			}
			Log.LogInfo((object)($"Harmony patches applied ({num} classes" + ((num2 > 0) ? $", {num2} FAILED)" : ")")));
			Log.LogInfo((object)"Graveyard Orbit Co-op 0.1.0 loaded.");
			LogSpawnAngles();
		}

		private static void LogSpawnAngles()
		{
			float value = Cfg.SpawnSeparationDeg.Value;
			for (int i = 1; i <= 4; i++)
			{
				List<string> list = new List<string>();
				for (int j = 0; j < i; j++)
				{
					list.Add($"{SlotMath.AngleDeg(j, i, value):0.##}°");
				}
				Log.LogInfo((object)string.Format("[spawnfan] {0} player(s) → [{1}]", i, string.Join(", ", list)));
			}
		}

		private void Update()
		{
			try
			{
				CoopSession.Tick(Time.deltaTime);
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Coop tick failed: " + ex));
			}
		}

		private void OnDestroy()
		{
			try
			{
				CoopSession.Shutdown();
			}
			catch
			{
			}
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
		}
	}
	public enum SessionMode
	{
		Off,
		Host,
		Client
	}
	public static class CoopSession
	{
		public static readonly List<PlayerEntry> Players = new List<PlayerEntry>();

		private static CoopConfig _cfg;

		private static float _sendT;

		private static uint _tick;

		private static float _lastHelloSent;

		private static bool _rosterReceived;

		private static bool _localDead;

		private static bool _returnSent;

		private static bool _returnApplied;

		private static bool _clearedSent;

		private static readonly ConditionalWeakTable<ShipController, object> _deathHooked = new ConditionalWeakTable<ShipController, object>();

		private static readonly Dictionary<ulong, string> _peerBuilds = new Dictionary<ulong, string>();

		private static Key _hostKey;

		private static Key _joinKey;

		private static Key _leaveKey;

		private static bool _keysParsed;

		private static readonly Dictionary<ulong, RemoteShipView> _views = new Dictionary<ulong, RemoteShipView>();

		private static readonly Dictionary<ulong, (Vector3 pos, float yaw, string name)> _pending = new Dictionary<ulong, (Vector3, float, string)>();

		private static readonly Dictionary<ulong, List<LoadoutPart>> _loadouts = new Dictionary<ulong, List<LoadoutPart>>();

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

		private static string _saveId;

		private static int _saveChunks;

		private static bool _startPending;

		private static string _startContract;

		private static string _startScene;

		private static int _startLevelSeed;

		private static int _startAnomalySeed;

		public static SessionMode Mode { get; private set; } = SessionMode.Off;

		public static NetTransport Transport { get; private set; }

		public static MiningSortie Sortie { get; private set; }

		public static string SelectedContractId { get; private set; }

		public static ulong ActiveLobbyId { get; private set; }

		public static PeerId LocalPeer { get; private set; }

		public static bool IsHost => Mode == SessionMode.Host;

		public static string HostBuild { get; private set; }

		public static bool HasVersionMismatch
		{
			get
			{
				if (IsHost)
				{
					foreach (string value in _peerBuilds.Values)
					{
						if (value != "20")
						{
							return true;
						}
					}
					return false;
				}
				if (!string.IsNullOrEmpty(HostBuild))
				{
					return HostBuild != "20";
				}
				return false;
			}
		}

		public static bool IsLocalDead => _localDead;

		public static Color SlotColor => (Color)(Mathf.Clamp(SpawnSlotIndex, 0, 3) switch
		{
			0 => new Color(1f, 0.62f, 0.16f), 
			1 => new Color(0.32f, 0.95f, 0.8f), 
			2 => new Color(0.72f, 0.45f, 1f), 
			_ => new Color(0.55f, 1f, 0.45f), 
		});

		public static int SpawnPlayerCount
		{
			get
			{
				if (Mode != SessionMode.Off)
				{
					return Mathf.Max(1, Players.Count);
				}
				return Mathf.Max(1, _cfg.DebugCount.Value);
			}
		}

		public static int SpawnSlotIndex
		{
			get
			{
				if (Mode != SessionMode.Off)
				{
					return LocalSlot();
				}
				return Mathf.Max(0, _cfg.DebugSlot.Value);
			}
		}

		public static float LocalSpawnAngle => SlotMath.AngleDeg(SpawnSlotIndex, SpawnPlayerCount, _cfg.SpawnSeparationDeg.Value);

		public static event Action SessionChanged;

		public static event Action RosterChanged;

		public static event Action<string> ContractChanged;

		public static bool MarkRemoteReturn()
		{
			if (_returnApplied)
			{
				return false;
			}
			_returnApplied = true;
			return true;
		}

		public static void Configure(CoopConfig cfg)
		{
			_cfg = cfg;
			_keysParsed = false;
		}

		public static int LocalSlot()
		{
			for (int i = 0; i < Players.Count; i++)
			{
				if (Players[i].id == LocalPeer.Value)
				{
					return Players[i].slot;
				}
			}
			return 0;
		}

		public static void SetContract(string id, bool broadcast)
		{
			if (!string.IsNullOrEmpty(id))
			{
				SelectedContractId = id;
				CoopSession.ContractChanged?.Invoke(id);
				if (broadcast && IsHost)
				{
					SendContract();
				}
				CoopPlugin.Log.LogInfo((object)("[coop] contract = " + id));
			}
		}

		private static void SendContract()
		{
			if (Transport != null && IsHost)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.Contract.ToString(),
					contract = SelectedContractId
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		public static void NotifyHostStarted(string contractId, string saveJson, string scene, int levelSeed, int anomalySeed)
		{
			SelectedContractId = contractId;
			CoopSession.ContractChanged?.Invoke(contractId);
			TileSync.Reset();
			if (Transport == null || !IsHost)
			{
				return;
			}
			SendContract();
			if (!string.IsNullOrEmpty(saveJson))
			{
				string text = Compress(saveJson);
				int num = (text.Length + 24000 - 1) / 24000;
				string saveId = Guid.NewGuid().ToString("N");
				Transport.Broadcast(Protocol.Encode(new NetMessage
				{
					kind = MessageKind.SaveBegin.ToString(),
					saveId = saveId,
					chunks = num,
					contract = contractId
				}), Delivery.Reliable);
				for (int i = 0; i < num; i++)
				{
					int num2 = i * 24000;
					int length = Math.Min(24000, text.Length - num2);
					Transport.Broadcast(Protocol.Encode(new NetMessage
					{
						kind = MessageKind.SaveChunk.ToString(),
						saveId = saveId,
						chunk = i,
						chunks = num,
						data = text.Substring(num2, length)
					}), Delivery.Reliable);
				}
				CoopPlugin.Log.LogInfo((object)$"[coop] sending host save: {saveJson.Length:N0} chars → {num} chunk(s)");
			}
			Transport.Broadcast(Protocol.Encode(new NetMessage
			{
				kind = MessageKind.Phase.ToString(),
				phase = "start",
				contract = contractId,
				count = Players.Count,
				scene = scene,
				levelSeed = levelSeed,
				anomalySeed = anomalySeed
			}), Delivery.Reliable);
		}

		public static List<LoadoutPart> GetLoadout(ulong peer)
		{
			if (!_loadouts.TryGetValue(peer, out var value))
			{
				return null;
			}
			return value;
		}

		public static void SendEnemyDamage(int q, int r, int dmg)
		{
			if (Mode == SessionMode.Client && Transport != null)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.EnemyDamage.ToString(),
					dq = q,
					dr = r,
					dmg = dmg
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		public static void NotifyLocalShipDeath()
		{
			if (Mode != SessionMode.Off && !_localDead)
			{
				_localDead = true;
				CoopPlugin.Log.LogInfo((object)"[coop] local ship destroyed — notifying peers");
				if (Transport != null)
				{
					NetMessage msg = new NetMessage
					{
						kind = MessageKind.PlayerDead.ToString()
					};
					Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
				}
			}
		}

		public static void NotifyHostReturn()
		{
			if (IsHost && Transport != null && !_returnSent)
			{
				_returnSent = true;
				CoopPlugin.Log.LogInfo((object)"[coop] host returning to base — peers notified");
				Transport.Broadcast(Protocol.Encode(new NetMessage
				{
					kind = MessageKind.Phase.ToString(),
					phase = "return",
					count = Players.Count
				}), Delivery.Reliable);
			}
		}

		public static void NotifyStructureCleared()
		{
			if (IsHost && Transport != null && !_clearedSent)
			{
				_clearedSent = true;
				CoopPlugin.Log.LogInfo((object)"[coop] structure cleared — notifying peers");
				Transport.Broadcast(Protocol.Encode(new NetMessage
				{
					kind = MessageKind.Phase.ToString(),
					phase = "cleared",
					count = Players.Count
				}), Delivery.Reliable);
			}
		}

		public static void SendTileDestroyed(int q, int r)
		{
			if (Mode == SessionMode.Client && Transport != null)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.TileDestroyed.ToString(),
					dq = q,
					dr = r
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		public static void BroadcastTileDestroyed(int q, int r)
		{
			if (IsHost && Transport != null)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.TileDestroyed.ToString(),
					dq = q,
					dr = r
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		public static List<Vector3> RemotePositions()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>(_views.Count);
			foreach (RemoteShipView value in _views.Values)
			{
				if ((Object)(object)value != (Object)null)
				{
					list.Add(((Component)value).transform.position);
				}
			}
			return list;
		}

		private static void HookShipDeath(MiningSortie sortie)
		{
			ShipController val = (((Object)(object)sortie != (Object)null) ? sortie.Ship : null);
			if (!((Object)(object)val == (Object)null) && !_deathHooked.TryGetValue(val, out var _))
			{
				_deathHooked.Add(val, null);
				val.OnDied = (Action)Delegate.Combine(val.OnDied, new Action(NotifyLocalShipDeath));
			}
		}

		private static void OnSaveBegin(NetMessage msg)
		{
			_saveParts.Clear();
			_saveId = msg.saveId;
			_saveChunks = Math.Max(0, msg.chunks);
			CoopPlugin.Log.LogInfo((object)$"[coop] receiving host save: {_saveChunks} chunk(s)");
		}

		private static void OnSaveChunk(NetMessage msg)
		{
			if (!(msg.saveId != _saveId))
			{
				_saveParts[msg.chunk] = msg.data;
			}
		}

		private static void OnPhaseStart(NetMessage msg)
		{
			_startPending = true;
			_startContract = msg.contract;
			_startScene = msg.scene;
			_startLevelSeed = msg.levelSeed;
			_startAnomalySeed = msg.anomalySeed;
			TryApplyStart();
		}

		private static void TryApplyStart()
		{
			if (!_startPending || (_saveChunks > 0 && _saveParts.Count < _saveChunks))
			{
				return;
			}
			string saveJson = null;
			if (_saveChunks > 0)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int i = 0; i < _saveChunks; i++)
				{
					if (!_saveParts.TryGetValue(i, out var value))
					{
						return;
					}
					stringBuilder.Append(value);
				}
				try
				{
					saveJson = Decompress(stringBuilder.ToString());
				}
				catch (Exception ex)
				{
					CoopPlugin.Log.LogError((object)("[coop] save decompress failed: " + ex));
				}
			}
			_startPending = false;
			_saveParts.Clear();
			_saveChunks = 0;
			_saveId = null;
			TileSync.Reset();
			CoopPlugin.Log.LogInfo((object)"[coop] host started — entering the session");
			ClientJoin.Enter(_startScene, _startContract, saveJson, _startLevelSeed, _startAnomalySeed);
		}

		private static string Compress(string text)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			using MemoryStream memoryStream = new MemoryStream();
			using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true))
			{
				gZipStream.Write(bytes, 0, bytes.Length);
			}
			return Convert.ToBase64String(memoryStream.ToArray());
		}

		private static string Decompress(string base64)
		{
			using MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64));
			using GZipStream stream2 = new GZipStream(stream, CompressionMode.Decompress);
			using StreamReader streamReader = new StreamReader(stream2, Encoding.UTF8);
			return streamReader.ReadToEnd();
		}

		public static void Shutdown()
		{
			try
			{
				Transport?.Dispose();
			}
			catch
			{
			}
			Transport = null;
			Mode = SessionMode.Off;
			Players.Clear();
			_pending.Clear();
			_loadouts.Clear();
			_peerBuilds.Clear();
			HostBuild = null;
			DestroyAllViews();
			Sortie = null;
			TileSync.Reset();
			WeaponFxSync.Reset();
			SelectedContractId = null;
			ActiveLobbyId = 0uL;
			_saveParts.Clear();
			_saveChunks = 0;
			_saveId = null;
			_startPending = false;
			_rosterReceived = false;
			_lastHelloSent = 0f;
			CoopSession.SessionChanged?.Invoke();
		}

		public static void StartHostTcp(int port)
		{
			Shutdown();
			Transport = TcpTransport.Host(port);
			Transport.PeerJoined += OnPeerJoined;
			Transport.PeerLeft += OnPeerLeft;
			Transport.PayloadReceived += OnPayload;
			Mode = SessionMode.Host;
			LocalPeer = Transport.LocalId;
			Players.Add(new PlayerEntry
			{
				id = LocalPeer.Value,
				slot = 0,
				name = LocalName()
			});
			CoopPlugin.Log.LogInfo((object)$"[coop] hosting on tcp:{port} as {LocalName()}");
			CoopSession.SessionChanged?.Invoke();
		}

		public static void StartClientTcp(string host, int port)
		{
			Shutdown();
			Transport = TcpTransport.Connect(host, port);
			Transport.PeerJoined += OnPeerJoined;
			Transport.PeerLeft += OnPeerLeft;
			Transport.PayloadReceived += OnPayload;
			Mode = SessionMode.Client;
			LocalPeer = Transport.LocalId;
			SendHello();
			CoopPlugin.Log.LogInfo((object)$"[coop] connecting to tcp {host}:{port} as {LocalName()}");
			CoopSession.SessionChanged?.Invoke();
		}

		public static void HostSteam()
		{
			if (SteamLobby.EnsureSteam())
			{
				Shutdown();
				SteamLobby.CreateLobby();
			}
		}

		public static void JoinSteam(ulong lobbyId)
		{
			if (SteamLobby.EnsureSteam())
			{
				Shutdown();
				SteamLobby.JoinLobby(lobbyId);
			}
		}

		public static void OnLobbyEntered(CSteamID lobby, bool isHost)
		{
			//IL_003d: 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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (Transport != null && ActiveLobbyId == lobby.m_SteamID)
				{
					CoopPlugin.Log.LogInfo((object)$"[coop] already in lobby {lobby.m_SteamID} — ignoring duplicate enter");
					return;
				}
				Shutdown();
				ActiveLobbyId = lobby.m_SteamID;
				_rosterReceived = false;
				_lastHelloSent = 0f;
				SteamTransport steamTransport = new SteamTransport(lobby);
				steamTransport.PeerJoined += OnPeerJoined;
				steamTransport.PeerLeft += OnPeerLeft;
				steamTransport.PayloadReceived += OnPayload;
				Transport = steamTransport;
				Mode = (isHost ? SessionMode.Host : SessionMode.Client);
				LocalPeer = steamTransport.LocalId;
				if (isHost)
				{
					Players.Add(new PlayerEntry
					{
						id = LocalPeer.Value,
						slot = 0,
						name = LocalName()
					});
					CoopPlugin.Log.LogInfo((object)$"[coop] hosting steam lobby {lobby.m_SteamID}");
					BroadcastRoster();
				}
				else
				{
					CoopPlugin.Log.LogInfo((object)$"[coop] joined steam lobby {lobby.m_SteamID}, saying hello");
					SendHello();
				}
				CoopSession.SessionChanged?.Invoke();
				MultiplayerLobby.TryAutoOpen();
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogError((object)("[coop] lobby enter failed: " + ex));
			}
		}

		public static void Leave()
		{
			if (Mode != SessionMode.Off)
			{
				CoopPlugin.Log.LogInfo((object)"[coop] leaving session");
				Shutdown();
			}
		}

		public static void Tick(float dt)
		{
			if (_cfg != null && _cfg.Enabled.Value)
			{
				try
				{
					SteamLobby.TickAutoInit();
				}
				catch
				{
				}
				HandleHotkeys();
				try
				{
					Transport?.Poll();
				}
				catch (Exception ex)
				{
					CoopPlugin.Log.LogError((object)("[coop] poll failed: " + ex));
				}
				try
				{
					WeaponFxSync.Tick();
				}
				catch (Exception ex2)
				{
					CoopPlugin.Log.LogError((object)("[fx] tick failed: " + ex2));
				}
				if ((Object)(object)Sortie == (Object)null)
				{
					Sortie = Object.FindAnyObjectByType<MiningSortie>();
				}
				FlushPendingViews();
				if (Mode != SessionMode.Off)
				{
					SendShipState(dt);
				}
				if (IsHost && (Object)(object)Sortie != (Object)null)
				{
					EnemySync.TickHost();
				}
				if (Mode == SessionMode.Client && Transport != null && !_rosterReceived && Time.unscaledTime - _lastHelloSent > 2f)
				{
					SendHello();
				}
			}
		}

		private static void HandleHotkeys()
		{
			//IL_0096: 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_00ae: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (!_keysParsed)
			{
				_keysParsed = true;
				if (!CoopConfig.TryParseKey(_cfg.HostKey.Value, out _hostKey) || (int)_hostKey == 0)
				{
					_hostKey = (Key)101;
				}
				if (!CoopConfig.TryParseKey(_cfg.JoinKey.Value, out _joinKey) || (int)_joinKey == 0)
				{
					_joinKey = (Key)102;
				}
				if (!CoopConfig.TryParseKey(_cfg.LeaveKey.Value, out _leaveKey) || (int)_leaveKey == 0)
				{
					_leaveKey = (Key)103;
				}
			}
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return;
			}
			KeyControl val = current[_hostKey];
			KeyControl val2 = current[_joinKey];
			KeyControl val3 = current[_leaveKey];
			bool num = val != null && ((ButtonControl)val).wasPressedThisFrame;
			bool flag = val2 != null && ((ButtonControl)val2).wasPressedThisFrame;
			bool flag2 = val3 != null && ((ButtonControl)val3).wasPressedThisFrame;
			if (num)
			{
				if (_cfg.UseSteam.Value)
				{
					HostSteam();
				}
				else
				{
					StartHostTcp(_cfg.TcpPort.Value);
				}
			}
			else if (flag)
			{
				if (_cfg.UseSteam.Value)
				{
					if (ulong.TryParse(_cfg.SteamLobbyId.Value, out var result) && result != 0L)
					{
						JoinSteam(result);
					}
					else
					{
						SteamLobby.OpenInviteDialog();
					}
				}
				else
				{
					StartClientTcp("127.0.0.1", _cfg.TcpPort.Value);
				}
			}
			else if (flag2)
			{
				Leave();
			}
		}

		private static void SendShipState(float dt)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			if (Transport == null || (Object)(object)Sortie == (Object)null || _localDead)
			{
				return;
			}
			ShipController ship = Sortie.Ship;
			if ((Object)(object)ship == (Object)null || !((Component)ship).gameObject.activeInHierarchy)
			{
				return;
			}
			float num = Mathf.Clamp(_cfg.SyncHz.Value, 5, 60);
			if (!(Time.unscaledTime - _sendT < 1f / num))
			{
				_sendT = Time.unscaledTime;
				Vector3 position = ((Component)ship).transform.position;
				byte[] data = Protocol.Encode(new NetMessage
				{
					kind = MessageKind.ShipState.ToString(),
					x = position.x,
					y = position.y,
					z = position.z,
					yaw = ((Component)ship).transform.eulerAngles.y,
					tick = ++_tick
				});
				if (Mode == SessionMode.Client)
				{
					Transport.Broadcast(data, Delivery.Unreliable);
				}
				else
				{
					Transport.Broadcast(data, Delivery.Unreliable);
				}
			}
		}

		private static void OnPeerJoined(PeerId peer)
		{
			CoopPlugin.Log.LogInfo((object)$"[coop] peer joined: {peer}");
			if (Mode == SessionMode.Client)
			{
				SendHello();
			}
			else if (IsHost)
			{
				BroadcastRoster();
				if (!string.IsNullOrEmpty(SelectedContractId))
				{
					SendContract();
				}
			}
		}

		private static void OnPeerLeft(PeerId peer)
		{
			CoopPlugin.Log.LogInfo((object)$"[coop] peer left: {peer}");
			Players.RemoveAll((PlayerEntry p) => p.id == peer.Value);
			_peerBuilds.Remove(peer.Value);
			_loadouts.Remove(peer.Value);
			_pending.Remove(peer.Value);
			RemoveView(peer.Value);
			if (IsHost)
			{
				BroadcastRoster();
			}
			CoopSession.RosterChanged?.Invoke();
		}

		private static void OnPayload(PeerId from, byte[] data)
		{
			if (!Protocol.TryDecode(data, out var msg))
			{
				CoopPlugin.Log.LogWarning((object)$"[coop] undecodable packet from {from} ({data.Length} bytes)");
				return;
			}
			if (_cfg.Verbose.Value)
			{
				CoopPlugin.Log.LogDebug((object)$"[coop] <- {msg.kind} from {from}");
			}
			string kind = msg.kind;
			if (kind == null)
			{
				return;
			}
			switch (kind.Length)
			{
			case 5:
				switch (kind[0])
				{
				case 'H':
					if (kind == "Hello" && IsHost)
					{
						HandleHello(from, msg);
					}
					break;
				case 'P':
					if (!(kind == "Phase"))
					{
						break;
					}
					CoopPlugin.Log.LogInfo((object)$"[coop] phase from host: {msg.phase} (players={msg.count})");
					if (!IsHost)
					{
						if (msg.phase == "start")
						{
							OnPhaseStart(msg);
						}
						else if (msg.phase == "cleared")
						{
							ClientJoin.HandleCleared();
						}
					}
					break;
				}
				break;
			case 6:
				switch (kind[0])
				{
				case 'R':
					if (kind == "Roster" && !IsHost)
					{
						ApplyRoster(msg);
					}
					break;
				case 'F':
					if (kind == "FxShot")
					{
						WeaponFxSync.EnqueueRemote(msg);
						if (IsHost)
						{
							Relay(from, data);
						}
					}
					break;
				}
				break;
			case 9:
				switch (kind[5])
				{
				case 't':
					if (kind == "ShipState")
					{
						HandleShipState(from, msg);
						if (IsHost)
						{
							Relay(from, data);
						}
					}
					break;
				case 'e':
					if (kind == "SaveBegin" && !IsHost)
					{
						OnSaveBegin(msg);
					}
					break;
				case 'h':
					if (kind == "SaveChunk" && !IsHost)
					{
						OnSaveChunk(msg);
					}
					break;
				case 'p':
					if (kind == "LootSpawn")
					{
						LootSync.Apply(msg);
						if (IsHost)
						{
							Relay(from, data, Delivery.Reliable);
						}
					}
					break;
				}
				break;
			case 13:
				switch (kind[0])
				{
				case 'E':
					if (kind == "EnemySnapshot" && !IsHost)
					{
						EnemySync.Apply(msg);
					}
					break;
				case 'T':
					if (kind == "TileDestroyed")
					{
						try
						{
							TileSync.Apply(msg.dq, msg.dr);
						}
						catch (Exception ex2)
						{
							CoopPlugin.Log.LogDebug((object)("[tile] apply failed: " + ex2.Message));
						}
						if (IsHost)
						{
							Relay(from, data, Delivery.Reliable);
						}
					}
					break;
				}
				break;
			case 11:
				switch (kind[5])
				{
				case 'D':
					if (kind == "EnemyDamage" && IsHost)
					{
						EnemySync.ApplyDamage(msg.dq, msg.dr, msg.dmg);
					}
					break;
				case 'K':
					if (kind == "EnemyKilled")
					{
						try
						{
							EnemySync.ApplyKill(msg.dq, msg.dr);
						}
						catch (Exception ex)
						{
							CoopPlugin.Log.LogDebug((object)("[enemy] kill apply failed: " + ex.Message));
						}
						if (IsHost)
						{
							Relay(from, data, Delivery.Reliable);
						}
					}
					break;
				}
				break;
			case 7:
				if (kind == "Loadout")
				{
					if (msg.loadout != null)
					{
						_loadouts[from.Value] = msg.loadout;
					}
					if (_views.TryGetValue(from.Value, out var value))
					{
						value?.DestroyView();
						_views.Remove(from.Value);
					}
					CoopPlugin.Log.LogInfo((object)$"[coop] loadout from {from}: {msg.loadout?.Count ?? 0} parts");
				}
				break;
			case 8:
				if (kind == "Contract" && !string.IsNullOrEmpty(msg.contract) && msg.contract != SelectedContractId)
				{
					SelectedContractId = msg.contract;
					CoopSession.ContractChanged?.Invoke(msg.contract);
				}
				break;
			case 10:
				if (kind == "PlayerDead")
				{
					RemoveView(from.Value);
					_pending.Remove(from.Value);
					CoopPlugin.Log.LogInfo((object)$"[coop] peer died: {from}");
					if (IsHost)
					{
						Relay(from, data, Delivery.Reliable);
					}
				}
				break;
			case 12:
				break;
			}
		}

		private static void HandleHello(PeerId from, NetMessage msg)
		{
			PlayerEntry playerEntry = Players.FirstOrDefault((PlayerEntry p) => p.id == from.Value);
			if (playerEntry == null)
			{
				playerEntry = new PlayerEntry
				{
					id = from.Value,
					name = (string.IsNullOrEmpty(msg.name) ? from.ToString() : msg.name)
				};
				Players.Add(playerEntry);
				CoopPlugin.Log.LogInfo((object)$"[coop] hello from {playerEntry.name} ({from}) — roster={Players.Count}");
				string text = msg.coopBuild ?? "";
				_peerBuilds[from.Value] = text;
				if (!string.IsNullOrEmpty(text) && text != "20")
				{
					CoopPlugin.Log.LogWarning((object)("[coop] BUILD MISMATCH: " + playerEntry.name + " runs " + text + ", host runs 20"));
				}
			}
			for (int num = 0; num < Players.Count; num++)
			{
				Players[num].slot = num;
			}
			BroadcastRoster();
			if (!string.IsNullOrEmpty(SelectedContractId))
			{
				SendContract();
			}
			CoopSession.RosterChanged?.Invoke();
		}

		private static void ApplyRoster(NetMessage msg)
		{
			if (msg.players == null)
			{
				return;
			}
			_rosterReceived = true;
			HostBuild = msg.coopBuild;
			if (!string.IsNullOrEmpty(HostBuild) && HostBuild != "20")
			{
				CoopPlugin.Log.LogWarning((object)("[coop] BUILD MISMATCH: host runs " + HostBuild + ", you run 20"));
			}
			Players.Clear();
			foreach (PlayerEntry player in msg.players)
			{
				Players.Add(new PlayerEntry
				{
					id = player.id,
					slot = player.slot,
					name = player.name
				});
			}
			Players.Sort((PlayerEntry a, PlayerEntry b) => a.slot.CompareTo(b.slot));
			CoopPlugin.Log.LogInfo((object)("[coop] roster: " + string.Join(", ", Players.Select((PlayerEntry p) => $"slot{p.slot}={p.name}")) + " " + $"(local slot {LocalSlot()})"));
			CoopSession.RosterChanged?.Invoke();
		}

		private static void HandleShipState(PeerId from, NetMessage msg)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(msg.x, msg.y, msg.z);
			string item = Players.FirstOrDefault((PlayerEntry p) => p.id == from.Value)?.name ?? from.ToString();
			if (_views.TryGetValue(from.Value, out var value) && (Object)(object)value != (Object)null)
			{
				value.SetTarget(val, msg.yaw);
			}
			else
			{
				_pending[from.Value] = (val, msg.yaw, item);
			}
		}

		private static void Relay(PeerId from, byte[] data)
		{
			Relay(from, data, Delivery.Unreliable);
		}

		private static void Relay(PeerId from, byte[] data, Delivery delivery)
		{
			foreach (PeerId peer in Transport.Peers)
			{
				if (peer != from && peer != LocalPeer)
				{
					Transport.Send(peer, data, delivery);
				}
			}
		}

		private static void FlushPendingViews()
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			if (_pending.Count == 0 || (Object)(object)Sortie == (Object)null || (Object)(object)Sortie.Ship == (Object)null)
			{
				return;
			}
			ulong[] array = _pending.Keys.ToArray();
			foreach (ulong num in array)
			{
				if (_views.TryGetValue(num, out var value) && (Object)(object)value != (Object)null)
				{
					_pending.Remove(num);
					continue;
				}
				(Vector3, float, string) tuple = _pending[num];
				RemoteShipView remoteShipView = RemoteShipView.Spawn(Sortie, num, tuple.Item3);
				if ((Object)(object)remoteShipView != (Object)null)
				{
					remoteShipView.SetTarget(tuple.Item1, tuple.Item2);
					_views[num] = remoteShipView;
					_pending.Remove(num);
				}
			}
		}

		private static void RemoveView(ulong peer)
		{
			if (_views.TryGetValue(peer, out var value))
			{
				value?.DestroyView();
				_views.Remove(peer);
			}
		}

		private static void DestroyAllViews()
		{
			foreach (RemoteShipView value in _views.Values)
			{
				value?.DestroyView();
			}
			_views.Clear();
		}

		private static void BroadcastRoster()
		{
			if (Transport != null && IsHost)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.Roster.ToString(),
					coopBuild = "20",
					count = Players.Count,
					players = Players.Select((PlayerEntry p) => new PlayerEntry
					{
						id = p.id,
						slot = p.slot,
						name = p.name
					}).ToList()
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		private static void SendHello()
		{
			if (Transport != null)
			{
				_lastHelloSent = Time.unscaledTime;
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.Hello.ToString(),
					version = "0.1.0",
					build = ApplicationVersion(),
					coopBuild = "20",
					name = LocalName()
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
				CoopPlugin.Log.LogInfo((object)$"[coop] hello sent to {Transport.Peers.Count} peer(s) as {LocalName()}");
				SendLoadout();
			}
		}

		private static void SendLoadout()
		{
			if (Transport != null)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.Loadout.ToString(),
					loadout = CaptureLoadout()
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		private static List<LoadoutPart> CaptureLoadout()
		{
			List<LoadoutPart> list = new List<LoadoutPart>();
			try
			{
				AccretionShip val = ((GameState.I != null) ? GameState.I.Ship : null);
				if (val == null)
				{
					return list;
				}
				foreach (PlacedPart item in val.placed)
				{
					list.Add(new LoadoutPart
					{
						uid = item.uid,
						type = item.type,
						level = item.level,
						tier = item.tier,
						cells = ((item.cells != null) ? item.cells.Select((Vector2Int c) => ((Vector2Int)(ref c)).x + "," + ((Vector2Int)(ref c)).y).ToArray() : null),
						mods = item.mods?.ToArray(),
						powerups = item.powerups?.ToArray()
					});
				}
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogWarning((object)("[coop] loadout capture failed: " + ex.Message));
			}
			return list;
		}

		public static void NotifySortieStarted(MiningSortie sortie)
		{
			Sortie = sortie;
			_localDead = false;
			_returnSent = false;
			_returnApplied = false;
			_clearedSent = false;
			WeaponFxSync.Reset();
			DestroyAllViews();
			_pending.Clear();
			EnemySync.Reset();
			SendLoadout();
			if ((Object)(object)sortie != (Object)null)
			{
				TileSync.Hook(sortie.Field);
				HookShipDeath(sortie);
			}
			if (IsHost && Transit() != null)
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.Phase.ToString(),
					phase = "sortie",
					count = SpawnPlayerCount
				};
				Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		private static NetTransport Transit()
		{
			return Transport;
		}

		private static string LocalName()
		{
			try
			{
				if (Mode == SessionMode.Off)
				{
					return "Player";
				}
				if (_cfg.UseSteam.Value && SteamLobby.EnsureSteam())
				{
					string personaName = SteamFriends.GetPersonaName();
					if (!string.IsNullOrEmpty(personaName))
					{
						return personaName;
					}
				}
			}
			catch
			{
			}
			if (!IsHost)
			{
				return "Client";
			}
			return "Host";
		}

		private static string ApplicationVersion()
		{
			try
			{
				return Application.version ?? "?";
			}
			catch
			{
				return "?";
			}
		}
	}
	internal static class ClientJoin
	{
		public static void Enter(string scene, string contractId, string saveJson, int levelSeed, int anomalySeed)
		{
			try
			{
				SaveSlots.Switch((SaveSlot)0);
				if (!string.IsNullOrEmpty(saveJson))
				{
					string text = SaveSlots.SavePathFor((SaveSlot)0);
					Backup(text);
					if (!SaveFile.Write(text, saveJson))
					{
						CoopPlugin.Log.LogError((object)("[join] could not write host save to " + text));
						return;
					}
					GameState.Load();
					CoopPlugin.Log.LogInfo((object)$"[join] applied host save ({saveJson.Length:N0} chars) and reloaded GameState");
					try
					{
						GameState i = GameState.I;
						JObject val = ((i != null) ? i.Root : null);
						JToken obj = ((val != null) ? val["profile"] : null);
						JObject val2 = (JObject)(object)((obj is JObject) ? obj : null);
						CoopPlugin.Log.LogInfo((object)string.Format("[join] seeds — level={0}, anomaly={1}", (val != null) ? val["level_seed"] : null, (val2 != null) ? val2["anomaly_seed"] : null));
					}
					catch
					{
					}
				}
				else
				{
					if (GameState.I == null)
					{
						GameState.Load();
					}
					StructureDef val3 = StructureCatalog.Resolve(contractId);
					if ((Object)(object)val3 != (Object)null && GameState.I != null)
					{
						GameState.I.NewContract(val3.id, val3.startingMoney);
						CoopPlugin.Log.LogWarning((object)"[join] no host save received — started contract on local save");
					}
				}
				ForceSeeds(levelSeed, anomalySeed);
				string text2 = (string.IsNullOrEmpty(scene) ? "MiningScene" : scene);
				MultiplayerLobby.Close();
				CoopPlugin.Log.LogInfo((object)("[join] loading scene '" + text2 + "'"));
				if ((Object)(object)CoopPlugin.Instance != (Object)null)
				{
					((MonoBehaviour)CoopPlugin.Instance).StartCoroutine(Load(text2));
				}
				else
				{
					SceneManager.LoadScene(text2);
				}
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogError((object)("[join] client enter failed: " + ex));
			}
		}

		private static void ForceSeeds(int levelSeed, int anomalySeed)
		{
			try
			{
				GameState i = GameState.I;
				if (i == null)
				{
					return;
				}
				if (levelSeed != 0)
				{
					i.Root["level_seed"] = JToken.op_Implicit(levelSeed);
				}
				if (anomalySeed != 0)
				{
					JToken obj = i.Root["profile"];
					JObject val = (JObject)(object)((obj is JObject) ? obj : null);
					if (val != null)
					{
						val["anomaly_seed"] = JToken.op_Implicit(anomalySeed);
					}
				}
				i.Save(false);
				ManualLogSource log = CoopPlugin.Log;
				string text = $"[join] forced seeds — level={levelSeed}, anomaly={anomalySeed} ";
				JToken arg = i.Root["level_seed"];
				JToken obj2 = i.Root["profile"];
				JToken obj3 = ((obj2 is JObject) ? obj2 : null);
				log.LogInfo((object)(text + string.Format("(now level={0}, anomaly={1})", arg, (obj3 != null) ? ((JObject)obj3)["anomaly_seed"] : null)));
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogError((object)("[join] forcing seeds failed: " + ex));
			}
		}

		private static IEnumerator Load(string scene)
		{
			yield return (object)new WaitForSeconds(0.3f);
			CoopPlugin.Log.LogInfo((object)("[join] loading scene '" + scene + "'"));
			SceneManager.LoadScene(scene);
		}

		public static void HandleCleared()
		{
			MiningSortie sortie = CoopSession.Sortie;
			if ((Object)(object)sortie == (Object)null)
			{
				return;
			}
			try
			{
				TileField field = sortie.Field;
				if (field != null)
				{
					field.DevClearAll();
				}
			}
			catch
			{
			}
			try
			{
				AccessTools.Method(typeof(MiningSortie), "StructureCleared", (Type[])null, (Type[])null)?.Invoke(sortie, null);
				CoopPlugin.Log.LogInfo((object)"[join] host cleared the structure - mirroring win");
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogWarning((object)("[join] mirror win failed: " + ex.Message));
			}
		}

		public static void ReturnHome()
		{
			if (CoopSession.Mode != SessionMode.Client || !CoopSession.MarkRemoteReturn())
			{
				return;
			}
			MiningSortie sortie = CoopSession.Sortie;
			if ((Object)(object)sortie == (Object)null)
			{
				return;
			}
			try
			{
				sortie.BeginReturnHome(1f, 0f);
				CoopPlugin.Log.LogInfo((object)"[join] host returned - mirroring return home");
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogWarning((object)("[join] return home failed: " + ex.Message));
			}
		}

		private static IEnumerator LaunchRoutine()
		{
			for (int i = 0; i < 24; i++)
			{
				GameRoot val = Object.FindAnyObjectByType<GameRoot>();
				if ((Object)(object)val != (Object)null)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(GameRoot), "TryLaunch", (Type[])null, (Type[])null);
					if (methodInfo != null)
					{
						object obj = Refs.GameRootState?.GetValue(val);
						string text = ((obj != null) ? obj.ToString() : "?");
						if (text != "Planet" && text != "Build" && text != "Process")
						{
							CoopPlugin.Log.LogInfo((object)("[join] ignoring launch request while in state '" + text + "' (prevents mid-sortie relaunch)"));
							yield break;
						}
						try
						{
							methodInfo.Invoke(val, null);
							CoopPlugin.Log.LogInfo((object)"[join] host launched - mirrored TryLaunch on client");
							yield break;
						}
						catch (Exception ex)
						{
							CoopPlugin.Log.LogWarning((object)("[join] TryLaunch failed: " + ex.Message));
							yield break;
						}
					}
				}
				yield return (object)new WaitForSeconds(0.5f);
			}
			CoopPlugin.Log.LogInfo((object)"[join] launch request timed out - launch manually when ready");
		}

		private static void Backup(string path)
		{
			try
			{
				if (File.Exists(path))
				{
					string text = path + ".coop-backup";
					if (!File.Exists(text))
					{
						File.Copy(path, text);
					}
				}
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogWarning((object)("[join] save backup failed: " + ex.Message));
			}
		}
	}
	internal static class EnemySync
	{
		private const float SnapshotInterval = 1f / 15f;

		private const float StaleAfter = 0.6f;

		private const float AuthorityTimeout = 3f;

		private static float _lastSnapshot;

		private static float _lastApply;

		private static bool _gotFirst;

		private static bool _applyingKill;

		private static readonly Dictionary<long, float> _lastSeen = new Dictionary<long, float>();

		private static readonly HashSet<long> _hidden = new HashSet<long>();

		private static FieldInfo _activeField;

		private static Type _enemyType;

		private static FieldInfo _cellF;

		private static FieldInfo _worldF;

		private static FieldInfo _hpF;

		private static FieldInfo _maxHpF;

		private static FieldInfo _visF;

		private static FieldInfo _ringF;

		private static FieldInfo _barF;

		private static FieldInfo _barFracF;

		private static FieldInfo _rotorF;

		private static FieldInfo _hexF;

		private static FieldInfo _dormantF;

		private static FieldInfo _dormantCellF;

		private static MethodInfo _tickBars;

		private static MethodInfo _killEnemy;

		private static bool _refsTried;

		private static bool _refsOk;

		internal static bool HostAuthority
		{
			get
			{
				if (CoopSession.Mode == SessionMode.Client && (Object)(object)CoopSession.Sortie != (Object)null && _gotFirst)
				{
					return Time.unscaledTime - _lastApply < 3f;
				}
				return false;
			}
		}

		internal static void Reset()
		{
			_gotFirst = false;
			_lastSnapshot = 0f;
			_lastApply = 0f;
			_applyingKill = false;
			_lastSeen.Clear();
			_hidden.Clear();
		}

		internal static bool AllowAttack(object enemy)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!HostAuthority || enemy == null)
				{
					return true;
				}
				EnsureRefs();
				if (((!(_hpF != null) || (int)_hpF.GetValue(enemy) != 0) ? 1 : 0) <= (false ? 1 : 0))
				{
					return false;
				}
				if (_cellF == null)
				{
					return true;
				}
				Vector2Int val = (Vector2Int)_cellF.GetValue(enemy);
				return !_hidden.Contains(Key(((Vector2Int)(ref val)).x, ((Vector2Int)(ref val)).y));
			}
			catch
			{
				return true;
			}
		}

		internal static void TickHost()
		{
			//IL_00b0: 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_00c3: 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_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			if (!CoopSession.IsHost || CoopSession.Transport == null || Time.unscaledTime - _lastSnapshot < 1f / 15f)
			{
				return;
			}
			_lastSnapshot = Time.unscaledTime;
			EnemyManager val = Manager();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			IList list = Active(val);
			if (list == null)
			{
				return;
			}
			List<int> list2 = new List<int>();
			List<int> list3 = new List<int>();
			List<int> list4 = new List<int>();
			List<int> list5 = new List<int>();
			List<float> list6 = new List<float>();
			List<float> list7 = new List<float>();
			foreach (object item in list)
			{
				if (item != null)
				{
					int num = (int)_hpF.GetValue(item);
					if (num > 0)
					{
						Vector2Int val2 = (Vector2Int)_cellF.GetValue(item);
						Vector3 val3 = (Vector3)_worldF.GetValue(item);
						list2.Add(((Vector2Int)(ref val2)).x);
						list3.Add(((Vector2Int)(ref val2)).y);
						list4.Add(num);
						list5.Add((int)_maxHpF.GetValue(item));
						list6.Add(val3.x);
						list7.Add(val3.z);
					}
				}
			}
			NetMessage msg = new NetMessage
			{
				kind = MessageKind.EnemySnapshot.ToString(),
				eq = list2.ToArray(),
				er = list3.ToArray(),
				ehp = list4.ToArray(),
				emax = list5.ToArray(),
				ex = list6.ToArray(),
				ez = list7.ToArray()
			};
			CoopSession.Transport.Broadcast(Protocol.Encode(msg), Delivery.Unreliable);
		}

		internal static void Apply(NetMessage msg)
		{
			//IL_0057: 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)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			if (msg == null || msg.eq == null || CoopSession.IsHost)
			{
				return;
			}
			EnemyManager val = Manager();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			IList list = Active(val);
			if (list == null)
			{
				return;
			}
			Dictionary<long, object> dictionary = new Dictionary<long, object>();
			foreach (object item in list)
			{
				if (item != null)
				{
					Vector2Int val2 = (Vector2Int)_cellF.GetValue(item);
					dictionary[Key(((Vector2Int)(ref val2)).x, ((Vector2Int)(ref val2)).y)] = item;
				}
			}
			float unscaledTime = Time.unscaledTime;
			HashSet<long> hashSet = new HashSet<long>();
			float hex = ((_hexF != null) ? ((float)_hexF.GetValue(val)) : 1f);
			int num = msg.eq.Length;
			for (int i = 0; i < num; i++)
			{
				long num2 = Key(msg.eq[i], msg.er[i]);
				hashSet.Add(num2);
				if (dictionary.TryGetValue(num2, out var value) && value != null)
				{
					Vector3 val3 = (Vector3)_worldF.GetValue(value);
					val3.x = ((msg.ex != null && i < msg.ex.Length) ? msg.ex[i] : val3.x);
					val3.z = ((msg.ez != null && i < msg.ez.Length) ? msg.ez[i] : val3.z);
					_worldF.SetValue(value, val3);
					_hpF.SetValue(value, (msg.ehp == null || i >= msg.ehp.Length) ? 1 : msg.ehp[i]);
					if (msg.emax != null && i < msg.emax.Length)
					{
						_maxHpF.SetValue(value, msg.emax[i]);
					}
					_lastSeen[num2] = unscaledTime;
					Show(value, val3, hex);
					_hidden.Remove(num2);
				}
			}
			if (_gotFirst)
			{
				foreach (KeyValuePair<long, object> item2 in dictionary)
				{
					if (!hashSet.Contains(item2.Key) && (!_lastSeen.TryGetValue(item2.Key, out var value2) || !(unscaledTime - value2 <= 0.6f)))
					{
						if (_lastSeen.Remove(item2.Key))
						{
							ApplyKillCell(item2.Key);
							continue;
						}
						Hide(item2.Value);
						_hidden.Add(item2.Key);
					}
				}
			}
			_gotFirst = true;
			_lastApply = Time.unscaledTime;
			try
			{
				_tickBars?.Invoke(val, new object[1] { 0f });
			}
			catch
			{
			}
		}

		internal static void ApplyDamage(int q, int r, int dmg)
		{
			//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)
			if (!CoopSession.IsHost || dmg <= 0)
			{
				return;
			}
			EnemyManager val = Manager();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			IList list = Active(val);
			if (list == null)
			{
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				object obj = list[i];
				if (obj == null)
				{
					continue;
				}
				Vector2Int val2 = (Vector2Int)_cellF.GetValue(obj);
				if (((Vector2Int)(ref val2)).x != q || ((Vector2Int)(ref val2)).y != r)
				{
					continue;
				}
				int num = (int)_hpF.GetValue(obj) - dmg;
				_hpF.SetValue(obj, num);
				if (num <= 0)
				{
					try
					{
						_killEnemy?.Invoke(val, new object[1] { i });
						break;
					}
					catch
					{
						break;
					}
				}
				try
				{
					_tickBars?.Invoke(val, new object[1] { 0f });
					break;
				}
				catch
				{
					break;
				}
			}
		}

		internal static void OnLocalKill(EnemyManager mgr, int idx)
		{
			//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)
			if (_applyingKill || CoopSession.Mode == SessionMode.Off || CoopSession.Transport == null || (Object)(object)CoopSession.Sortie == (Object)null || (Object)(object)mgr == (Object)null)
			{
				return;
			}
			EnsureRefs();
			if (!_refsOk)
			{
				return;
			}
			IList list = Active(mgr);
			if (list != null && idx >= 0 && idx < list.Count)
			{
				object obj = list[idx];
				if (obj != null)
				{
					Vector2Int val = (Vector2Int)_cellF.GetValue(obj);
					NetMessage msg = new NetMessage
					{
						kind = MessageKind.EnemyKilled.ToString(),
						dq = ((Vector2Int)(ref val)).x,
						dr = ((Vector2Int)(ref val)).y
					};
					CoopSession.Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
					CoopPlugin.Log.LogDebug((object)$"[enemy] kill broadcast at ({((Vector2Int)(ref val)).x},{((Vector2Int)(ref val)).y})");
				}
			}
		}

		internal static void ApplyKill(int q, int r)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)CoopSession.Sortie == (Object)null)
			{
				return;
			}
			EnemyManager val = Manager();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			EnsureRefs();
			if (!_refsOk)
			{
				return;
			}
			RemoveDormant(val, q, r);
			IList list = Active(val);
			if (list == null)
			{
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				object obj = list[i];
				if (obj == null)
				{
					continue;
				}
				Vector2Int val2 = (Vector2Int)_cellF.GetValue(obj);
				if (((Vector2Int)(ref val2)).x != q || ((Vector2Int)(ref val2)).y != r)
				{
					continue;
				}
				long num = Key(q, r);
				_applyingKill = true;
				Action<Vector3, Dictionary<string, int>> onBehaviorLoot = val.OnBehaviorLoot;
				val.OnBehaviorLoot = null;
				try
				{
					_killEnemy?.Invoke(val, new object[1] { i });
				}
				catch (Exception ex)
				{
					CoopPlugin.Log.LogWarning((object)("[enemy] remote kill failed: " + ex.Message));
				}
				finally
				{
					val.OnBehaviorLoot = onBehaviorLoot;
					_applyingKill = false;
				}
				_hidden.Remove(num);
				_lastSeen.Remove(num);
				CoopPlugin.Log.LogDebug((object)$"[enemy] remote kill applied at ({q},{r})");
				break;
			}
		}

		private static void ApplyKillCell(long key)
		{
			ApplyKill((int)(key >> 32), (int)(key & 0xFFFFFFFFu));
		}

		private static void RemoveDormant(EnemyManager mgr, int q, int r)
		{
			//IL_0068: 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)
			try
			{
				if (_dormantF == null || _dormantCellF == null || !(_dormantF.GetValue(mgr) is IList { Count: not 0 } list))
				{
					return;
				}
				for (int num = list.Count - 1; num >= 0; num--)
				{
					object obj = list[num];
					if (obj != null && _dormantCellF.GetValue(obj) is Vector2Int val && ((Vector2Int)(ref val)).x == q && ((Vector2Int)(ref val)).y == r)
					{
						list.RemoveAt(num);
					}
				}
			}
			catch
			{
			}
		}

		internal static bool InterceptClientDamage(EnemyManager mgr, int kind, int idx, int dmg)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (!HostAuthority || kind != 1 || dmg <= 0)
			{
				return false;
			}
			if ((Object)(object)mgr == (Object)null)
			{
				return false;
			}
			IList list = Active(mgr);
			if (list == null || idx < 0 || idx >= list.Count)
			{
				return false;
			}
			object obj = list[idx];
			if (obj == null)
			{
				return false;
			}
			Vector2Int val = (Vector2Int)_cellF.GetValue(obj);
			CoopSession.SendEnemyDamage(((Vector2Int)(ref val)).x, ((Vector2Int)(ref val)).y, dmg);
			return true;
		}

		private static EnemyManager Manager()
		{
			return Object.FindAnyObjectByType<EnemyManager>();
		}

		internal static float ShotHitRadius(EnemyManager mgr)
		{
			EnsureRefs();
			float num = 1f;
			try
			{
				if (_hexF != null && (Object)(object)mgr != (Object)null)
				{
					num = (float)_hexF.GetValue(mgr);
				}
			}
			catch
			{
			}
			return num * 30f / 32f;
		}

		private static IList Active(EnemyManager mgr)
		{
			EnsureRefs();
			if (!_refsOk)
			{
				return null;
			}
			return _activeField?.GetValue(mgr) as IList;
		}

		private static void EnsureRefs()
		{
			if (_refsTried)
			{
				return;
			}
			_refsTried = true;
			_activeField = AccessTools.Field(typeof(EnemyManager), "_active");
			_hexF = AccessTools.Field(typeof(EnemyManager), "_hexSize");
			if (_activeField == null)
			{
				CoopPlugin.Log.LogError((object)"[enemy] _active not found - enemy sync disabled");
				return;
			}
			_dormantF = AccessTools.Field(typeof(EnemyManager), "_dormant");
			try
			{
				Type type = _dormantF?.FieldType;
				Type type2 = ((type != null && type.IsGenericType) ? type.GetGenericArguments()[0] : null);
				_dormantCellF = ((type2 != null) ? AccessTools.Field(type2, "Item1") : null);
			}
			catch
			{
			}
			_enemyType = _activeField.FieldType.GetGenericArguments()[0];
			_cellF = AccessTools.Field(_enemyType, "cell");
			_worldF = AccessTools.Field(_enemyType, "world");
			_hpF = AccessTools.Field(_enemyType, "hp");
			_maxHpF = AccessTools.Field(_enemyType, "maxHp");
			_visF = AccessTools.Field(_enemyType, "vis");
			_ringF = AccessTools.Field(_enemyType, "ring");
			_barF = AccessTools.Field(_enemyType, "bar");
			_barFracF = AccessTools.Field(_enemyType, "barFrac");
			_rotorF = AccessTools.Field(_enemyType, "rotor");
			_tickBars = AccessTools.Method(typeof(EnemyManager), "TickHealthBars", (Type[])null, (Type[])null);
			_killEnemy = AccessTools.Method(typeof(EnemyManager), "KillEnemy", (Type[])null, (Type[])null);
			_refsOk = _cellF != null && _worldF != null && _hpF != null && _maxHpF != null && _visF != null && _tickBars != null && _killEnemy != null;
			if (!_refsOk)
			{
				CoopPlugin.Log.LogError((object)($"[enemy] reflection incomplete - sync disabled (cell={_cellF != null}, world={_worldF != null}, " + $"hp={_hpF != null}, max={_maxHpF != null}, vis={_visF != null}, bars={_tickBars != null}, kill={_killEnemy != null})"));
			}
			else
			{
				CoopPlugin.Log.LogInfo((object)"[enemy] sync hooks ready");
			}
		}

		private static void Show(object e, Vector3 world, float hex)
		{
			//IL_002e: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			object? obj = _visF?.GetValue(e);
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				val.SetActive(true);
				val.transform.position = world + Vector3.up * (hex * 0.3f);
			}
			object? obj2 = _ringF?.GetValue(e);
			GameObject val2 = (GameObject)((obj2 is GameObject) ? obj2 : null);
			if ((Object)(object)val2 != (Object)null)
			{
				val2.SetActive(true);
				val2.transform.position = world;
			}
			object? obj3 = _barF?.GetValue(e);
			GameObject val3 = (GameObject)((obj3 is GameObject) ? obj3 : null);
			if ((Object)(object)val3 != (Object)null)
			{
				val3.SetActive(true);
			}
			object? obj4 = _rotorF?.GetValue(e);
			Component val4 = (Component)((obj4 is Component) ? obj4 : null);
			if (val4 != null && (Object)(object)val4 != (Object)null)
			{
				val4.gameObject.SetActive(true);
			}
		}

		private static void Hide(object e)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (_worldF != null)
				{
					Vector3 val = (Vector3)_worldF.GetValue(e);
					val.x = 1000000f;
					val.z = 1000000f;
					_worldF.SetValue(e, val);
				}
			}
			catch
			{
			}
			object? obj2 = _visF?.GetValue(e);
			GameObject val2 = (GameObject)((obj2 is GameObject) ? obj2 : null);
			if ((Object)(object)val2 != (Object)null)
			{
				val2.SetActive(false);
			}
			object? obj3 = _ringF?.GetValue(e);
			GameObject val3 = (GameObject)((obj3 is GameObject) ? obj3 : null);
			if ((Object)(object)val3 != (Object)null)
			{
				val3.SetActive(false);
			}
			object? obj4 = _barF?.GetValue(e);
			GameObject val4 = (GameObject)((obj4 is GameObject) ? obj4 : null);
			if ((Object)(object)val4 != (Object)null)
			{
				val4.SetActive(false);
			}
			object? obj5 = _rotorF?.GetValue(e);
			Component val5 = (Component)((obj5 is Component) ? obj5 : null);
			if (val5 != null && (Object)(object)val5 != (Object)null)
			{
				val5.gameObject.SetActive(false);
			}
		}

		private static long Key(int q, int r)
		{
			return ((long)q << 32) ^ (uint)r;
		}
	}
	[HarmonyPatch(typeof(SweeperSystem), "ShowStream")]
	internal static class SweeperStreamFxPatch
	{
		private static void Postfix(SweeperSystem __instance, int i, Vector3 from, Vector3 to)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				WeaponFxSync.BroadcastDynamoStream(__instance, i, from, to);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(SweeperSystem), "PlayBlast")]
	internal static class SweeperBlastFxPatch
	{
		private static void Postfix(Vector3 at, float radius, float mul)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				WeaponFxSync.BroadcastVfx("WeaponFX/DomeNukeBlue", at, radius / 7.2f * 1.6f * Mathf.Max(0.01f, mul), 2.6f, "dynamo");
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(SweeperSystem), "TickEmit")]
	internal static class SweeperOrbFxPatch
	{
		private static int _before;

		private static FieldInfo _orbs;

		private static Type _orbType;

		private static FieldInfo _pos;

		private static FieldInfo _dir;

		private static FieldInfo _speed;

		private static FieldInfo _life;

		private static FieldInfo _surge;

		private static FieldInfo _partUid;

		private static void Prefix(SweeperSystem __instance)
		{
			_before = Count(__instance);
		}

		private static void Postfix(SweeperSystem __instance)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				IList list = Orbs(__instance);
				if (list == null)
				{
					return;
				}
				for (int i = Mathf.Max(0, _before); i < list.Count; i++)
				{
					object obj = list[i];
					if (obj != null)
					{
						Vector3 origin = (Vector3)_pos.GetValue(obj);
						Vector3 dir = (Vector3)_dir.GetValue(obj);
						float num = (float)_speed.GetValue(obj);
						float num2 = (float)_life.GetValue(obj);
						bool flag = _surge != null && (bool)_surge.GetValue(obj);
						WeaponFxSync.BroadcastOrb(mods: WeaponFxSync.ModsForUid((_partUid != null) ? ((int)_partUid.GetValue(obj)) : (-1)), origin: origin, dir: dir, speed: num, dist: num * num2, fxName: "WeaponFX/ProtonMissileBlue", scale: 0.9f * (flag ? 1.9f : 1f), color: new Color(0.35f, 0.75f, 1f));
					}
				}
			}
			catch
			{
			}
		}

		private static void EnsureRefs()
		{
			if (!(_orbs != null))
			{
				_orbs = AccessTools.Field(typeof(SweeperSystem), "_orbs");
				if (!(_orbs == null))
				{
					_orbType = _orbs.FieldType.GetGenericArguments()[0];
					_pos = AccessTools.Field(_orbType, "pos");
					_dir = AccessTools.Field(_orbType, "dir");
					_speed = AccessTools.Field(_orbType, "speed");
					_life = AccessTools.Field(_orbType, "life");
					_surge = AccessTools.Field(_orbType, "surge");
					_partUid = AccessTools.Field(_orbType, "partUid");
				}
			}
		}

		private static int Count(SweeperSystem s)
		{
			return Orbs(s)?.Count ?? 0;
		}

		private static IList Orbs(SweeperSystem s)
		{
			EnsureRefs();
			return _orbs?.GetValue(s) as IList;
		}
	}
	[HarmonyPatch(typeof(ResonatorWave), "Step")]
	internal static class ResonatorWaveFxPatch
	{
		private static readonly HashSet<ResonatorWave> _seen = new HashSet<ResonatorWave>();

		private static void Prefix(ResonatorWave __instance)
		{
			if (CoopSession.Mode == SessionMode.Off || (Object)(object)CoopSession.Sortie == (Object)null)
			{
				return;
			}
			try
			{
				if (!((Object)(object)__instance == (Object)null) && !_seen.Contains(__instance))
				{
					if (_seen.Count > 1024)
					{
						_seen.Clear();
					}
					_seen.Add(__instance);
					WeaponFxSync.BroadcastWave(__instance);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(EnemyManager), "SpawnArc")]
	internal static class SpawnArcFxPatch
	{
		private static void Postfix(Vector3 a, Vector3 b)
		{
			//IL_0009: 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)
			if (CoopSession.Mode == SessionMode.Off)
			{
				return;
			}
			try
			{
				WeaponFxSync.QueueArc(a, b);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(ProjectileSystem), "SpawnStraight")]
	internal static class SpawnStraightFxPatch
	{
		private static void Prefix(Vector3 origin, Vector3 dir, float speed, float maxDist, Color color, string visualFx, float visualScale, string impactFx, float impactScale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			try
			{
				string weapon = (string.IsNullOrEmpty(ProjectileSystem.SpawnFamily) ? "bolt" : ProjectileSystem.SpawnFamily);
				string mods = WeaponFxSync.ModsForUid(ProjectileSystem.SpawnPartUid);
				WeaponFxSync.BroadcastBolt(origin, dir, speed, maxDist, color, visualFx, visualScale, weapon, mods, impactFx, impactScale);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(ProjectileSystem), "SpawnProbe")]
	internal static class SpawnProbeFxPatch
	{
		private static void Prefix(Vector3 origin, Vector3 dir, float speed, float maxDist, Color color, string visualFx, float visualScale, string impactFx, float impactScale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			try
			{
				string weapon = (string.IsNullOrEmpty(ProjectileSystem.SpawnFamily) ? "probe" : ProjectileSystem.SpawnFamily);
				string mods = WeaponFxSync.ModsForUid(ProjectileSystem.SpawnPartUid);
				WeaponFxSync.BroadcastBolt(origin, dir, speed, maxDist, color, visualFx, visualScale, weapon, mods, impactFx, impactScale);
			}
			catch
			{
			}
		}
	}
	internal static class GameFlow
	{
		internal static bool TryStartHostGame(out string error)
		{
			error = null;
			string selectedContractId = CoopSession.SelectedContractId;
			if (string.IsNullOrEmpty(selectedContractId))
			{
				error = "select a contract";
				return false;
			}
			StructureDef val = Resolve(selectedContractId);
			if ((Object)(object)val == (Object)null)
			{
				error = "unknown contract " + selectedContractId;
				return false;
			}
			MainMenuBoot val2 = Object.FindAnyObjectByType<MainMenuBoot>();
			if ((Object)(object)val2 == (Object)null)
			{
				error = "menu not found";
				return false;
			}
			try
			{
				SaveSlots.Switch((SaveSlot)0);
				MethodInfo methodInfo = AccessTools.Method(typeof(MainMenuBoot), "StartContract", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					error = "StartContract hook missing";
					return false;
				}
				string gameplayScene = val2.gameplayScene;
				methodInfo.Invoke(val2, new object[2] { val, false });
				EnsureSessionSeeds();
				int levelSeed = 0;
				int anomalySeed = 0;
				try
				{
					levelSeed = ((GameState.I != null) ? GameState.I.LevelSeed : 0);
					anomalySeed = ((GameState.I != null) ? AnomalyState.Seed(GameState.I) : 0);
				}
				catch (Exception ex)
				{
					CoopPlugin.Log.LogWarning((object)("[flow] seed read failed: " + ex.Message));
				}
				string saveJson = null;
				try
				{
					GameState i = GameState.I;
					object obj;
					if (i == null)
					{
						obj = null;
					}
					else
					{
						JObject root = i.Root;
						obj = ((root != null) ? ((JToken)root).ToString((Formatting)0, Array.Empty<JsonConverter>()) : null);
					}
					saveJson = (string)obj;
				}
				catch (Exception ex2)
				{
					CoopPlugin.Log.LogWarning((object)("[flow] save capture failed: " + ex2.Message));
				}
				CoopSession.NotifyHostStarted(val.id, saveJson, gameplayScene, levelSeed, anomalySeed);
				CoopPlugin.Log.LogInfo((object)("[flow] host started contract '" + val.id + "' — peers notified"));
				return true;
			}
			catch (Exception ex3)
			{
				CoopPlugin.Log.LogError((object)("[flow] start failed: " + ex3));
				error = ex3.Message;
				return false;
			}
		}

		private static void EnsureSessionSeeds()
		{
			try
			{
				GameState i = GameState.I;
				if (i != null)
				{
					if (((int?)i.Root["level_seed"]).GetValueOrDefault() == 0)
					{
						i.Root["level_seed"] = JToken.op_Implicit(new Random().Next(1, int.MaxValue));
					}
					int num = AnomalyState.Seed(i);
					i.Save(false);
					CoopPlugin.Log.LogInfo((object)string.Format("[flow] session seeds — level={0}, anomaly={1}", i.Root["level_seed"], num));
				}
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogWarning((object)("[flow] seed setup failed: " + ex.Message));
			}
		}

		private static StructureDef Resolve(string id)
		{
			StructureDef val = StructureCatalog.Resolve(id);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			StructureCatalog i = StructureCatalog.I;
			StructureDef[] array = (((Object)(object)i != (Object)null) ? i.Contracts : null);
			if (array != null)
			{
				StructureDef[] array2 = array;
				foreach (StructureDef val2 in array2)
				{
					if ((Object)(object)val2 != (Object)null && val2.id == id)
					{
						return val2;
					}
				}
			}
			return null;
		}
	}
	internal static class LootSync
	{
		private static bool _applyingRemote;

		internal static void OnLocalSpawn(Vector3 pos, int value, string mat)
		{
			//IL_0040: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			if (!_applyingRemote && CoopSession.Mode != SessionMode.Off && CoopSession.Transport != null && !((Object)(object)CoopSession.Sortie == (Object)null))
			{
				NetMessage msg = new NetMessage
				{
					kind = MessageKind.LootSpawn.ToString(),
					lx = pos.x,
					ly = pos.y,
					lz = pos.z,
					lv = Mathf.Max(1, value),
					lmat = mat
				};
				CoopSession.Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
			}
		}

		internal static void Apply(NetMessage msg)
		{
			//IL_0060: 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)
			try
			{
				MiningSortie sortie = CoopSession.Sortie;
				if (!((Object)(object)sortie == (Object)null) && !((Object)(object)sortie.Ship == (Object)null))
				{
					ResourceSystem component = ((Component)sortie.Ship).GetComponent<ResourceSystem>();
					if (!((Object)(object)component == (Object)null))
					{
						Vector3 val = default(Vector3);
						((Vector3)(ref val))..ctor(msg.lx, msg.ly, msg.lz);
						int num = ((sortie.Field != null) ? sortie.Field.WorldToTileIndex(val) : (-1));
						_applyingRemote = true;
						component.Spawn(num, val, msg.lv, msg.lmat);
					}
				}
			}
			catch
			{
			}
			finally
			{
				_applyingRemote = false;
			}
		}
	}
	[HarmonyPatch(typeof(ResourceSystem), "Spawn")]
	internal static class ResourceSpawnLootPatch
	{
		private static void Prefix(Vector3 pos, int value, string mat)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				LootSync.OnLocalSpawn(pos, value, mat);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MiningSortie), "BeginSortie")]
	internal static class MiningSortieBeginSortiePatch
	{
		private static void Postfix(MiningSortie __instance)
		{
			try
			{
				CoopSession.NotifySortieStarted(__instance);
				SpawnFan.Apply(__instance);
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogError((object)("[patch] BeginSortie postfix failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(GameRoot), "TryLaunch")]
	internal static class GameRootTryLaunchPatch
	{
		private static void Postfix(GameRoot __instance)
		{
			try
			{
				if (CoopSession.IsHost && CoopSession.Transport != null)
				{
					object obj = Refs.GameRootState?.GetValue(__instance);
					if (obj != null && !(obj.ToString() != "TakingOff"))
					{
						NetMessage msg = new NetMessage
						{
							kind = MessageKind.Phase.ToString(),
							phase = "launch",
							count = CoopSession.SpawnPlayerCount
						};
						CoopSession.Transport.Broadcast(Protocol.Encode(msg), Delivery.Reliable);
						CoopPlugin.Log.LogInfo((object)"[coop] host launched — peers notified (auto-launch arrives in phase 3)");
					}
				}
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogError((object)("[patch] TryLaunch postfix failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(MiningSortie), "OpenJumpPortal")]
	internal static class PortalAlignPatch
	{
		private static void Postfix(MiningSortie __instance)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0059: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				float localSpawnAngle = CoopSession.LocalSpawnAngle;
				if (!(Mathf.Abs(localSpawnAngle) < 0.01f) && !(Refs.PortalPos == null) && !(Refs.PlanetCenter == null))
				{
					Vector3 center = (Vector3)Refs.PlanetCenter.GetValue(__instance);
					Vector3 point = (Vector3)Refs.PortalPos.GetValue(__instance);
					point = SlotMath.RotateAroundY(point, center, localSpawnAngle);
					Refs.PortalPos.SetValue(__instance, point);
					object? obj = Refs.PortalGo?.GetValue(__instance);
					GameObject val = (GameObject)((obj is GameObject) ? obj : null);
					if ((Object)(object)val != (Object)null)
					{
						val.transform.position = point;
					}
					Refs.AnimatePortal?.Invoke(__instance, new object[1] { 0f });
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MiningSortie), "AnimatePortal")]
	internal static class PortalColourPatch
	{
		private static void Postfix(MiningSortie __instance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0052: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Color slotColor = CoopSession.SlotColor;
				object? obj = Refs.PortalOuter?.GetValue(__instance);
				LineRenderer val = (LineRenderer)((obj is LineRenderer) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					val.startColor = slotColor;
					val.endColor = slotColor;
				}
				if (!(Refs.PortalArcs?.GetValue(__instance) is LineRenderer[] array))
				{
					return;
				}
				Color val2 = default(Color);
				((Color)(ref val2))..ctor(slotColor.r, slotColor.g, slotColor.b, 0.8f);
				LineRenderer[] array2 = array;
				foreach (LineRenderer val3 in array2)
				{
					if (!((Object)(object)val3 == (Object)null))
					{
						val3.startColor = val2;
						val3.endColor = val2;
					}
				}
			}
			catch
			{
			}
		}
	}
	internal static class Refs
	{
		internal static readonly FieldInfo LaunchStart = AccessTools.Field(typeof(MiningSortie), "_launchStart");

		internal static readonly FieldInfo SpawnPos = AccessTools.Field(typeof(MiningSortie), "_spawnPos");

		internal static readonly FieldInfo PlanetCenter = AccessTools.Field(typeof(MiningSortie), "_planetCenter");

		internal static readonly FieldInfo CamTarget = AccessTools.Field(typeof(MiningSortie), "_camTarget");

		internal static readonly MethodInfo TryLaunch = AccessTools.Method(typeof(GameRoot), "TryLaunch", (Type[])null, (Type[])null);

		internal static readonly FieldInfo GameRootState = AccessTools.Field(typeof(GameRoot), "_state");

		internal static readonly FieldInfo PortalPos = AccessTools.Field(typeof(MiningSortie), "_portalPos");

		internal static readonly FieldInfo PortalGo = AccessTools.Field(typeof(MiningSortie), "_portal");

		internal static readonly FieldInfo PortalOuter = AccessTools.Field(typeof(MiningSortie), "_portalOuter");

		internal static readonly FieldInfo PortalArcs = AccessTools.Field(typeof(MiningSortie), "_portalArcs");

		internal static readonly MethodInfo AnimatePortal = AccessTools.Method(typeof(MiningSortie), "AnimatePortal", (Type[])null, (Type[])null);

		internal static readonly FieldInfo Radar = AccessTools.Field(typeof(GameRoot), "_radar");

		internal static readonly MethodInfo RadarTileDestroyed = AccessTools.Method(typeof(RadarController), "OnTileDestroyed", (Type[])null, (Type[])null);

		internal static bool Valid
		{
			get
			{
				if (LaunchStart != null && SpawnPos != null && PlanetCenter != null)
				{
					return CamTarget != null;
				}
				return false;
			}
		}
	}
	internal static class RemoteShipBuilder
	{
		private static FieldInfo _gsShip;

		internal static GameObject Build(MiningSortie sortie, ulong peer)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			try
			{
				List<LoadoutPart> loadout = CoopSession.GetLoadout(peer);
				if (loadout == null || loadout.Count == 0 || (Object)(object)sortie == (Object)null || GameState.I == null)
				{
					return null;
				}
				AccretionShip val = new AccretionShip();
				int num = 0;
				foreach (LoadoutPart item2 in loadout)
				{
					if (item2 != null && !string.IsNullOrEmpty(item2.type))
					{
						PlacedPart item = new PlacedPart
						{
							uid = item2.uid,
							type = item2.type,
							level = item2.level,
							tier = item2.tier,
							cells = ParseCells(item2.cells),
							mods = ((item2.mods != null) ? new List<string>(item2.mods) : new List<string>()),
							powerups = ((item2.powerups != null) ? new List<string>(item2.powerups) : new List<string>())
						};
						val.placed.Add(item);
						num = Math.Max(num, item2.uid);
					}
				}
				val.nextUid = num + 1;
				if (val.placed.Count == 0)
				{
					return null;
				}
				if ((object)_gsShip == null)
				{
					_gsShip = AccessTools.Field(typeof(GameState), "_ship");
				}
				object value = _gsShip.GetValue(GameState.I);
				GameObject val2 = null;
				try
				{
					_gsShip.SetValue(GameState.I, val);
					val2 = new GameObject("CoopRemoteShip");
					val2.transform.SetParent(((Component)sortie).transform, false);
					WeaponSystem val3 = val2.AddComponent<WeaponSystem>();
					ShipController obj = val2.AddComponent<ShipController>();
					Shader shader = Shader.Find("Universal Render Pipeline/Lit");
					Material val4 = MakeMat(shader, new Color(0.72f, 0.74f, 0.8f));
					Material val5 = MakeMat(shader, new Color(1f, 0.55f, 0.2f));
					Camera val6 = (((Object)(object)Camera.main != (Object)null) ? Camera.main : Object.FindAnyObjectByType<Camera>());
					float hexSize = sortie.hexSize;
					obj.Init(val6, val3, hexSize * 0.32f * 0.75f, hexSize, val4, val5, sortie.Field);
					Object.DestroyImmediate((Object)(object)obj);
					Object.DestroyImmediate((Object)(object)val3);
				}
				finally
				{
					_gsShip.SetValue(GameState.I, value);
				}
				if ((Object)(object)val2 == (Object)null)
				{
					return null;
				}
				Collider[] componentsInChildren = val2.GetComponentsInChildren<Collider>(true);
				foreach (Collider val7 in componentsInChildren)
				{
					if ((Object)(object)val7 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)val7);
					}
				}
				return val2;
			}
			catch (Exception ex)
			{
				CoopPlugin.Log.LogWarning((object)("[ship] remote build failed, using clone: " + ex.Message));
				return null;
			}
		}

		private static List<Vector2Int> ParseCells(string[] cells)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			List<Vector2Int> list = new List<Vector2Int>();
			if (cells == null)
			{
				return list;
			}
			foreach (string text in cells)
			{
				if (!string.IsNullOrEmpty(text))
				{
					string[] array = text.Split(',');
					if (array.Length == 2 && int.TryParse(array[0], out var result) && int.TryParse(array[1], out var result2))
					{
						list.Add(new Vector2Int(result, result2));
					}
				}
			}
			return list;
		}

		private static Material MakeMat(Shader shader, Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			Material val = new Material(shader);
			if (val.HasProperty("_BaseColor"))
			{
				val.SetColor("_BaseColor", color);
			}
			val.color = color;
			return val;
		}
	}
	public sealed class RemoteShipView : MonoBehaviour
	{
		private Vector3 _targetPos;

		private float _targetYaw;

		private float _lastPacket;

		private string _peerName = "?";

		public ulong Peer;

		public static RemoteShipView Spawn(MiningSortie sortie, ulong peer, string name)
		{
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			ShipController val = (((Object)(object)sortie != (Object)null) ? sortie.Ship : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			GameObject val2 = RemoteShipBuilder.Build(sortie, peer);
			if ((Object)(object)val2 != (Object)null)
			{
				try
				{
					val2.transform.position = ((Component)val).transform.position;
					val2.transform.rotation = ((Component)val).transform.rotation;
					RemoteShipView remoteShipView = val2.AddComponent<RemoteShipView>();
					remoteShipView.Peer = peer;
					remoteShipView._peerName = name;
					remoteShipView._targetPos = val2.transform.position;
					remoteShipView._targetYaw = val2.transform.eulerAngles.y;
					remoteShipView._lastPacket = Time.time;
					CoopPlugin.Log.LogInfo((object)$"[view] built remote ship for {name} ({peer}) from loadout");
					return remoteShipView;
				}
				catch (Exception ex)
				{
					CoopPlugin.Log.LogWarning((object)("[view] built ship setup failed: " + ex.Message));
					Object.Destroy((Object)(object)val2);
				}
			}
			GameObject val3 = null;
			try
			{
				val3 = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)val).transform.parent, true);
				((Object)val3).name = "CoopRemote_" + peer;
				MonoBehaviour[] componentsInChildren = val3.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val4 in componentsInChildren)
				{
					if (!((Object)(object)val4 == (Object)null))
					{
						Object.DestroyImmediate((Object)(object)val4);
					}
				}
				Collider[] componentsInChildren2 = val3.GetComponentsInChildren<Collider>(true);
				foreach (Collider val5 in componentsInChildren2)
				{
					if ((Object)(object)val5 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)val5);
					}
				}
				Rigidbody[] componentsInChildren3 = val3.GetComponentsInChildren<Rigidbody>(true);
				foreach (Rigidbody val6 in componentsInChildren3)
				{
					if ((Object)(object)val6 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)val6);
					}
				}
				val3.transform.position = ((Component)val).transform.position;
				val3.transform.rotation = ((Component)val).transform.rotation;
				RemoteShipView remoteShipView2 = val3.AddComponent<RemoteShipView>();
				remoteShipView2.Peer = peer;
				remoteShipView2._peerName = name;
				remoteShipView2._targetPos = val3.transform.position;
				remoteShipView2._targetYaw = val3.transform.eulerAngles.y;
				remoteShipView2._lastPacket = Time.time;
				CoopPlugin.Log.LogInfo((object)$"[view] spawned remote ship for {name} ({peer})");
				return remoteShipView2;
			}
			catch (Exception ex2)
			{
				CoopPlugin.Log.LogError((object)("[view] clone failed, using fallback marker: " + ex2));
				if ((Object)(object)val3 != (Object)null)
				{
					Object.Destroy((Object)(object)val3);
				}
				GameObject obj = GameObject.CreatePrimitive((PrimitiveType)1);
				((Object)obj).name = "CoopRemote_" + peer;
				obj.transform.position = ((Component)val).transform.position;
				RemoteShipView remoteShipView3 = obj.AddComponent<RemoteShipView>();
				remoteShipView3.Peer = peer;
				remoteShipView3._peerName = name;
				remoteShipView3._lastPacket = Time.time;
				return remoteShipView3;
			}
		}

		public void SetTarget(Vector3 pos, float yawDeg)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			_targetPos = pos;
			_targetYaw = yawDeg;
			_lastPacket = Time.time;
		}

		private void Update()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			float num = 1f - Mathf.Exp(-12f * Time.deltaTime);
			((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, _targetPos, num);
			float num2 = Mathf.LerpAngle(((Component)this).transform.eulerAngles.y, _targetYaw, num);
			((Component)this).transform.rotation = Quaternion.Euler(0f, num2, 0f);
		}

		public void DestroyView()
		{
			try
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MiningSortie), "BeginReturnHome")]
	internal static class ReturnHomeDiagnosticsPatch
	{
		private static void Postfix(MiningSortie __instance, float speed, float accel)
		{
			//IL_001d: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ShipController ship = __instance.Ship;
				Vector3 val = (((Object)(object)ship != (Object)null) ? ((Component)ship).transform.position : Vector3.zero);
				CoopPlugin.Log.LogInfo((object)($"[return] BeginReturnHome mode={CoopSession.Mode} dead={CoopSession.IsLocalDead} " + $"speed={speed:0.##} accel={accel:0.##} pos=({val.x:0.0},{val.z:0.0})"));
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MiningSortie), "OnShipDied")]
	internal static class ShipDiedDiagnosticsPatch
	{
		private static void Postfix(MiningSortie __instance)
		{
			//IL_001d: 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_0022: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ShipController ship = __instance.Ship;
				Vector3 val = (((Object)(object)ship != (Object)null) ? ((Component)ship).transform.position : Vector3.zero);
				CoopPlugin.Log.LogInfo((object)$"[return] OnShipDied mode={CoopSession.Mode} pos=({val.x:0.0},{val.z:0.0})");
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MiningSortie), "StructureCleared")]
	internal static class StructureClearedWinPatch
	{
		private static void Postfix()
		{
			try
			{
				if (CoopSession.IsHost)
				{
					CoopSession.NotifyStructureCleared();
				}
			}
			catch
			{
			}
		}
	}
	internal static class DeathDiagnostics
	{
		internal static void LogPeerDeath(ulong peer)
		{
			CoopPlugin.Log.LogInfo((object)$"[return] peer death received for {peer}");
		}
	}
	public static class SlotMath
	{
		public static float AngleDeg(int slot, int count, float separationDeg)
		{
			if (count <= 1)
			{
				return 0f;
			}
			slot = Mathf.Clamp(slot, 0, count - 1);
			return ((float)slot - (float)(count - 1) * 0.5f) * separationDeg;
		}

		public static Vector3 RotateAroundY(Vector3 point, Vector3 center, float angleDeg)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = point - center;
			float num = angleDeg * (MathF.PI / 180f);
			float num2 = Mathf.Sin(num);
			float num3 = Mathf.Cos(num);
			return center + new Vector3(val.x * num3 + val.z * num2, val.y, (0f - val.x) * num2 + val.z * num3);
		}
	}
	internal static class SpawnFan
	{
		internal static void Apply(MiningSortie sortie)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)sortie == (Object)null || !Refs.Valid)
			{
				return;
			}
			ShipController ship = sortie.Ship;
			if (!((Object)(object)ship == (Object)null))
			{
				int spawnPlayerCount = CoopSession.SpawnPlayerCount;
				int spawnSlotIndex = CoopSession.SpawnSlotIndex;
				if (spawnPlayerCount > 1)
				{
					float separationDeg = Mathf.Max(0f, CoopPlugin.Cfg.SpawnSeparationDeg.Value);
					float num = SlotMath.AngleDeg(spawnSlotIndex, spawnPlayerCount, separationDeg);
					Vector3 center = (Vector3)Refs.PlanetCenter.GetValue(sortie);
					Vector3 val = SlotMath.RotateAroundY((Vector3)Refs.LaunchStart.GetValue(sortie), center, num);
					Vector3 val2 = SlotMath.RotateAroundY((Vector3)Refs.SpawnPos.GetValue(sortie), center, num);
					Refs.LaunchStart.SetValue(sortie, val);
					Refs.SpawnPos.SetValue(sortie, val2);
					Refs.CamTarget.SetValue(sortie, val2);
					((Component)ship).transform.position = val;
					ship.ResetOrientation(num);
					CoopPlugin.Log.LogInfo((object)($"[spawnfan] slot {spawnSlotIndex + 1}/{spawnPlayerCount} → exit angle {num:0.##}° " + "(launch " + Fmt(val) + ", spawn " + Fmt(val2) + ")"));
				}
			}
		}

		private static string Fmt(Vector3 v)
		{
			//IL_0005: 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)
			return $"({v.x:0.0}, {v.z:0.0})";
		}
	}
	[HarmonyPatch(typeof(EnemyManager), "DoAttack")]
	internal static class EnemyDoAttackGuardPatch
	{
		private static bool Prefix(object __0)
		{
			try
			{
				return EnemySync.AllowAttack(__0);
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(EnemyManager), "DamageTarget")]
	internal static class EnemyDamageInterceptPatch
	{
		private static bool Prefix(EnemyManager __instance, int kind, int idx, int dmg)
		{
			try
			{
				return !EnemySync.InterceptClientDamage(__instance, kind, idx, dmg);
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(EnemyManager), "KillEnemy")]
	internal static class EnemyKillSyncPatch
	{
		private static void Prefix(EnemyManager __instance, int idx)
		{
			try
			{
				EnemySync.OnLocalKill(__instance, idx);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(EnemyManager), "SpawnShot")]
	internal static class EnemySpawnShotFxPatch
	{
		private static void Prefix(EnemyManager __instance, Vector3 from, Vector3 dir, float speed, int dmg, float maxDist, float scale)
		{
			//IL_0009: 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)
			if (!CoopSession.IsHost)
			{
				return;
			}
			try
			{
				WeaponFxSync.BroadcastEnemyShot(from, dir, speed, maxDist, dmg, scale, EnemySync.ShotHitRadius(__instance));
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(WeaponSystem), "DrawBeam")]
	internal static class DrawBeamFxPatch
	{
		private static void Postfix(WeaponSystem __instance, int i, Vector3 to, int slot, bool showImpact)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				WeaponFxSync.BroadcastBeam(__instance, i, to, slot, showImpact);
			}
			catch
			{
			}
		}
	}
	internal static class TileSync
	{
		private static readonly ConditionalWeakTable<TileField, object> Hooked = new ConditionalWeakTable<TileField, object>();

		private static readonly HashSet<long> Pending = new HashSet<long>();

		private static bool _applyingRemote;

		public static void Reset()
		{
			Pending.Clear();
		}

		public static void Hook(TileField field)
		{
			if (field != null && !Hooked.TryGetValue(field, out var _))
			{
				Hooked.Add(field, null);
				TileField obj = field;
				obj.OnTileDestroyed = (Action<int, Vector3>)Delegate.Combine(obj.OnTileDestroyed, (Action<int, Vector3>)delegate(int idx, Vector3 world)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					OnLocalDestroyed(field, world);
				});
				CoopPlugin.Log.LogInfo((object)"[tile] destruction sync hooked");
				ReplayPending(field);
			}
		}

		private static void OnLocalDestroyed(TileField field, Vector3 world)
		{
			//IL_0010: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			if (_applyingRemote || CoopSession.Mode == SessionMode.Off)
			{
				return;
			}
			try
			{
				Vector2Int val = HexLayout.WorldToAxial(world, field.HexSize);
				if (CoopSession.IsHost)
				{
					CoopSession.BroadcastTileDestroyed(((Vector2Int)(ref val)).x, ((Vector2Int)(ref val)).y);
				}
				else
				{
					CoopSession.SendTileDestroyed(((Vector2Int)(ref val)).x, ((Vector2Int)(ref val)).y);
				}
			}
			catch
			{
			}
		}

		public static void Apply(int q, int r)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameState i = GameState.I;
				if (i != null)
				{
					i.RecordDestroyed(q, r);
				}
			}
			catch
			{
			}
			TileField val = (((Object)(object)CoopSession.Sortie != (Object)null) ? CoopSession.Sortie.Field : null);
			if (val == null)
			{
				Pending.Add(Key(q, r));
				return;
			}
			int num = val.IndexOfAxial(q, r);
			if (num < 0)
			{
				Pending.Add(Key(q, r));
				return;
			}
			Strip(val, num);
			try
			{
				EnemyManager val2 = Object.FindAnyObjectByType<EnemyManager>();
				if ((Object)(object)val2 != (Object)null)
				{
					val2.OnTileDestroyed(val.TileWorld(num));
				}
			}
			catch
			{
			}
			try
			{
				GameRoot obj3 = Object.FindAnyObjectByType<GameRoot>();
				object obj4 = Refs.Radar?.GetValue(obj3);
				if (obj4 != null)
				{
					Refs.RadarTileDestroyed?.Invoke(obj4, new object[2] { q, r });
				}
			}
			catch
			{
			}
		}

		private static void Strip(TileField field, int idx)
		{
			_applyingRemote = true;
			try
			{
				field.StripCamouflage(idx);
			}
			finally
			{
				_applyingRemote = false;
			}
		}

		private static void ReplayPending(TileField field)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			if (Pending.Count == 0)
			{
				return;
			}
			int num = 0;
			foreach (long item in Pending)
			{
				int num2 = (int)(item >> 32);
				int num3 = (int)(item & 0xFFFFFFFFu);
				int num4 = field.IndexOfAxial(num2, num3);
				if (num4 < 0 || !field.IsAlive(num4))
				{
					continue;
				}
				Strip(field, num4);
				try
				{
					EnemyManager val = Object.FindAnyOb