Decompiled source of GMMapLoader v0.1.0

plugins/ArceDev.GMMapLoader.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using FishNet;
using FishNet.Broadcast;
using FishNet.Connection;
using FishNet.Object;
using FishNet.Serializing;
using FishNet.Transporting;
using GameModeCore;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ArceDev.GMMapLoader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+88daf4ed8dcceedc844605187851957e63c447e7")]
[assembly: AssemblyProduct("ArceDev.GMMapLoader")]
[assembly: AssemblyTitle("GM Map Loader")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	[Embedded]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	[Embedded]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace GMMapLoader
{
	public sealed class GMMapDefinition
	{
		public string Id { get; }

		public string GameModeId { get; }

		public string DisplayName { get; }

		public string BundlePath { get; }

		public string SceneName { get; }

		public int NetworkVersion { get; }

		public GMMapDefinition(string id, string gameModeId, string displayName, string bundlePath, string sceneName, int networkVersion = 1)
		{
			Id = Required(id, "id");
			GameModeId = Required(gameModeId, "gameModeId");
			DisplayName = Required(displayName, "displayName");
			BundlePath = Path.GetFullPath(Required(bundlePath, "bundlePath"));
			SceneName = Required(sceneName, "sceneName");
			if (networkVersion < 1)
			{
				throw new ArgumentOutOfRangeException("networkVersion");
			}
			NetworkVersion = networkVersion;
		}

		private static string Required(string value, string parameter)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				throw new ArgumentException("A non-empty value is required.", parameter);
			}
			return value;
		}
	}
	public static class GMMapApi
	{
		private static readonly List<GMMapDefinition> Ordered = new List<GMMapDefinition>();

		private static readonly Dictionary<string, GMMapDefinition> Definitions = new Dictionary<string, GMMapDefinition>(StringComparer.Ordinal);

		public static GMMapCatalog Catalog { get; } = new GMMapCatalog(Ordered, Definitions);

		public static GMMapDefinition? ActiveMap => GMMapRuntime.ActiveMap;

		public static bool IsLoading
		{
			get
			{
				if (!GMMapRuntime.IsLoading)
				{
					return GMMapNetwork.IsWaitingForClients;
				}
				return true;
			}
		}

		public static event Action<GMMapDefinition>? LocalMapLoaded;

		public static event Action<GMMapDefinition>? AllClientsLoaded;

		public static event Action<string, string>? MapLoadFailed;

		public static event Action? MapUnloaded;

		public static void Register(GMMapDefinition definition)
		{
			if (definition == null)
			{
				throw new ArgumentNullException("definition");
			}
			if (!Definitions.TryAdd(definition.Id, definition))
			{
				throw new InvalidOperationException("Map '" + definition.Id + "' is already registered.");
			}
			Ordered.Add(definition);
		}

		public static IReadOnlyList<GMMapDefinition> SessionMaps(string gameModeId)
		{
			return GMMapNetwork.SessionMaps(gameModeId);
		}

		public static bool TryLoadForAll(string mapId, out string error)
		{
			return GMMapNetwork.TryLoadForAll(mapId, out error);
		}

		public static bool TryUnloadForAll(out string error)
		{
			return GMMapNetwork.TryUnloadForAll(out error);
		}

		internal static void NotifyLocalLoaded(GMMapDefinition definition)
		{
			GMMapApi.LocalMapLoaded?.Invoke(definition);
		}

		internal static void NotifyAllLoaded(GMMapDefinition definition)
		{
			GMMapApi.AllClientsLoaded?.Invoke(definition);
		}

		internal static void NotifyFailed(string mapId, string error)
		{
			GMMapApi.MapLoadFailed?.Invoke(mapId, error);
		}

		internal static void NotifyUnloaded()
		{
			GMMapApi.MapUnloaded?.Invoke();
		}

		internal static void Validate()
		{
			string bundlePath = Path.Combine(Path.GetTempPath(), "gmmaploader-validation");
			GMMapDefinition gMMapDefinition = new GMMapDefinition("test.map", "test.mode", "Test", bundlePath, "Arena", 2);
			List<GMMapDefinition> ordered = new List<GMMapDefinition> { gMMapDefinition };
			Dictionary<string, GMMapDefinition> definitions = new Dictionary<string, GMMapDefinition>(StringComparer.Ordinal) { [gMMapDefinition.Id] = gMMapDefinition };
			GMMapCatalog gMMapCatalog = new GMMapCatalog(ordered, definitions);
			if (gMMapCatalog.ForMode("test.mode").Single().NetworkVersion != 2 || gMMapCatalog.ForMode("other.mode").Count != 0)
			{
				throw new InvalidOperationException("GM Map Loader catalog validation failed.");
			}
		}
	}
	public sealed class GMMapCatalog
	{
		private readonly List<GMMapDefinition> _ordered;

		private readonly Dictionary<string, GMMapDefinition> _definitions;

		private readonly ReadOnlyCollection<GMMapDefinition> _readOnly;

		public IReadOnlyList<GMMapDefinition> All => _readOnly;

		internal GMMapCatalog(List<GMMapDefinition> ordered, Dictionary<string, GMMapDefinition> definitions)
		{
			_ordered = ordered;
			_definitions = definitions;
			_readOnly = ordered.AsReadOnly();
		}

		public bool TryGet(string id, out GMMapDefinition definition)
		{
			return _definitions.TryGetValue(id, out definition);
		}

		public IReadOnlyList<GMMapDefinition> ForMode(string gameModeId)
		{
			return _ordered.Where((GMMapDefinition map) => string.Equals(map.GameModeId, gameModeId, StringComparison.Ordinal)).ToArray();
		}
	}
	internal sealed class GMMapManifest
	{
		public int SchemaVersion { get; set; }

		public string Id { get; set; } = "";

		public string GameModeId { get; set; } = "";

		public string DisplayName { get; set; } = "";

		public string Bundle { get; set; } = "";

		public string Scene { get; set; } = "";

		public int NetworkVersion { get; set; } = 1;
	}
	internal static class GMMapManifestDiscovery
	{
		internal static void Discover()
		{
			if (!Directory.Exists(Paths.PluginPath))
			{
				return;
			}
			try
			{
				foreach (string item in Directory.EnumerateFiles(Paths.PluginPath, "*.gmmap.json", SearchOption.AllDirectories))
				{
					TryRegister(item);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not scan map manifests: " + ex.Message));
			}
		}

		private static void TryRegister(string manifestPath)
		{
			try
			{
				GMMapManifest gMMapManifest = JsonConvert.DeserializeObject<GMMapManifest>(File.ReadAllText(manifestPath)) ?? throw new InvalidDataException("The manifest is empty.");
				if (gMMapManifest.SchemaVersion != 1)
				{
					throw new InvalidDataException($"Unsupported schemaVersion {gMMapManifest.SchemaVersion}; expected 1.");
				}
				if (Path.IsPathRooted(gMMapManifest.Bundle))
				{
					throw new InvalidDataException("Manifest bundle paths must be relative to the manifest.");
				}
				string text = Path.GetDirectoryName(manifestPath) ?? Paths.PluginPath;
				string fullPath = Path.GetFullPath(Path.Combine(text, gMMapManifest.Bundle));
				string value = Path.GetFullPath(text).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
				if (!fullPath.StartsWith(value, StringComparison.OrdinalIgnoreCase))
				{
					throw new InvalidDataException("The bundle path escapes the manifest directory.");
				}
				GMMapApi.Register(new GMMapDefinition(gMMapManifest.Id, gMMapManifest.GameModeId, gMMapManifest.DisplayName, fullPath, gMMapManifest.Scene, gMMapManifest.NetworkVersion));
				Plugin.Log.LogInfo((object)("Registered map '" + gMMapManifest.Id + "' from " + Path.GetFileName(manifestPath) + "."));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Invalid map manifest '" + manifestPath + "': " + ex.Message));
			}
		}
	}
	internal readonly record struct MapCatalogHello(string[] MapIds, int[] NetworkVersions) : IBroadcast;
	internal readonly record struct MapLoadRequest(int RequestId, string MapId, int NetworkVersion) : IBroadcast;
	internal readonly record struct MapLoadResult(int RequestId, string MapId, bool Success, string Error) : IBroadcast;
	internal readonly record struct MapAbortRequest(int RequestId, string MapId, string Error) : IBroadcast;
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal readonly record struct MapUnloadRequest : IBroadcast;
	internal static class GMMapNetwork
	{
		private const int MaximumMaps = 128;

		private const float LoadTimeoutSeconds = 45f;

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

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

		private static readonly Action<NetworkConnection, MapCatalogHello, Channel> ServerCatalogHandler = OnServerCatalog;

		private static readonly Action<MapLoadRequest, Channel> ClientLoadHandler = OnClientLoad;

		private static readonly Action<NetworkConnection, MapLoadResult, Channel> ServerResultHandler = OnServerResult;

		private static readonly Action<MapAbortRequest, Channel> ClientAbortHandler = OnClientAbort;

		private static readonly Action<MapUnloadRequest, Channel> ClientUnloadHandler = OnClientUnload;

		private static bool _clientRegistered;

		private static bool _serverRegistered;

		private static int _requestId;

		private static GMMapDefinition? _pendingMap;

		private static float _deadline;

		internal static bool IsWaitingForClients => _pendingMap != null;

		internal static void Initialize()
		{
			GenericWriter<MapCatalogHello>.SetWrite((Action<Writer, MapCatalogHello>)WriteCatalog);
			GenericReader<MapCatalogHello>.SetRead((Func<Reader, MapCatalogHello>)ReadCatalog);
			GenericWriter<MapLoadRequest>.SetWrite((Action<Writer, MapLoadRequest>)delegate(Writer writer, MapLoadRequest message)
			{
				writer.WriteInt32(message.RequestId);
				writer.WriteString(message.MapId);
				writer.WriteInt32(message.NetworkVersion);
			});
			GenericReader<MapLoadRequest>.SetRead((Func<Reader, MapLoadRequest>)((Reader reader) => new MapLoadRequest(reader.ReadInt32(), reader.ReadStringAllocated(), reader.ReadInt32())));
			GenericWriter<MapLoadResult>.SetWrite((Action<Writer, MapLoadResult>)delegate(Writer writer, MapLoadResult message)
			{
				writer.WriteInt32(message.RequestId);
				writer.WriteString(message.MapId);
				writer.WriteBoolean(message.Success);
				writer.WriteString(message.Error);
			});
			GenericReader<MapLoadResult>.SetRead((Func<Reader, MapLoadResult>)((Reader reader) => new MapLoadResult(reader.ReadInt32(), reader.ReadStringAllocated(), reader.ReadBoolean(), reader.ReadStringAllocated())));
			GenericWriter<MapAbortRequest>.SetWrite((Action<Writer, MapAbortRequest>)delegate(Writer writer, MapAbortRequest message)
			{
				writer.WriteInt32(message.RequestId);
				writer.WriteString(message.MapId);
				writer.WriteString(message.Error);
			});
			GenericReader<MapAbortRequest>.SetRead((Func<Reader, MapAbortRequest>)((Reader reader) => new MapAbortRequest(reader.ReadInt32(), reader.ReadStringAllocated(), reader.ReadStringAllocated())));
			GenericWriter<MapUnloadRequest>.SetWrite((Action<Writer, MapUnloadRequest>)delegate
			{
			});
			GenericReader<MapUnloadRequest>.SetRead((Func<Reader, MapUnloadRequest>)((Reader _) => default(MapUnloadRequest)));
		}

		internal static void Register()
		{
			if (!_clientRegistered && Object.op_Implicit((Object)(object)InstanceFinder.ClientManager))
			{
				InstanceFinder.ClientManager.RegisterBroadcast<MapLoadRequest>(ClientLoadHandler);
				InstanceFinder.ClientManager.RegisterBroadcast<MapAbortRequest>(ClientAbortHandler);
				InstanceFinder.ClientManager.RegisterBroadcast<MapUnloadRequest>(ClientUnloadHandler);
				_clientRegistered = true;
			}
			if (!_serverRegistered && Object.op_Implicit((Object)(object)InstanceFinder.ServerManager))
			{
				InstanceFinder.ServerManager.RegisterBroadcast<MapCatalogHello>(ServerCatalogHandler, true);
				InstanceFinder.ServerManager.RegisterBroadcast<MapLoadResult>(ServerResultHandler, true);
				InstanceFinder.ServerManager.OnRemoteConnectionState += OnRemoteConnectionState;
				_serverRegistered = true;
			}
		}

		internal static void SendCatalog()
		{
			Register();
			if (Object.op_Implicit((Object)(object)InstanceFinder.ClientManager))
			{
				GMMapDefinition[] source = GMMapApi.Catalog.All.Take(128).ToArray();
				InstanceFinder.ClientManager.Broadcast<MapCatalogHello>(new MapCatalogHello(source.Select((GMMapDefinition map) => map.Id).ToArray(), source.Select((GMMapDefinition map) => map.NetworkVersion).ToArray()), (Channel)0);
			}
		}

		internal static IReadOnlyList<GMMapDefinition> SessionMaps(string gameModeId)
		{
			GMMapDefinition[] array = GMMapApi.Catalog.ForMode(gameModeId).ToArray();
			if (!IsServer())
			{
				return array;
			}
			NetworkConnection[] clients = AuthenticatedClients();
			Dictionary<string, int> value;
			int value2;
			return array.Where((GMMapDefinition map) => clients.All((NetworkConnection connection) => ClientMaps.TryGetValue(connection.ClientId, out value) && value.TryGetValue(map.Id, out value2) && value2 == map.NetworkVersion)).ToArray();
		}

		internal static bool TryLoadForAll(string mapId, out string error)
		{
			Register();
			if (!TryPrepareLoad(mapId, out GMMapDefinition definition, out NetworkConnection[] clients, out error))
			{
				return false;
			}
			_requestId++;
			_pendingMap = definition;
			PendingClients.Clear();
			PendingClients.UnionWith(clients.Select((NetworkConnection connection) => connection.ClientId));
			_deadline = Time.unscaledTime + 45f;
			NetworkConnection[] array = clients;
			foreach (NetworkConnection val in array)
			{
				InstanceFinder.ServerManager.Broadcast<MapLoadRequest>(val, new MapLoadRequest(_requestId, definition.Id, definition.NetworkVersion), true, (Channel)0);
			}
			Plugin.Log.LogInfo((object)$"Requested synchronized load of '{definition.Id}' for {clients.Length} client(s).");
			error = "";
			return true;
		}

		private static bool TryPrepareLoad(string mapId, out GMMapDefinition definition, out NetworkConnection[] clients, out string error)
		{
			definition = null;
			clients = Array.Empty<NetworkConnection>();
			if (!IsServer())
			{
				return Fail("Only the host can request a synchronized map load.", out error);
			}
			if (_pendingMap != null || GMMapRuntime.IsLoading)
			{
				return Fail("Another map transition is already in progress.", out error);
			}
			if (!GMMapApi.Catalog.TryGet(mapId, out definition))
			{
				return Fail("Map '" + mapId + "' is not registered.", out error);
			}
			if (!GameModeApi.IsActive(definition.GameModeId))
			{
				return Fail("Map '" + mapId + "' belongs to inactive mode '" + definition.GameModeId + "'.", out error);
			}
			clients = AuthenticatedClients();
			if (clients.Length == 0)
			{
				return Fail("No authenticated clients are connected.", out error);
			}
			GMMapDefinition selected = definition;
			NetworkConnection val = ((IEnumerable<NetworkConnection>)clients).FirstOrDefault((Func<NetworkConnection, bool>)((NetworkConnection connection) => !HasCompatibleMap(connection, selected)));
			if (val != null)
			{
				return Fail($"Client {val.ClientId} does not have compatible map '{mapId}'.", out error);
			}
			return Pass(out error);
		}

		private static bool HasCompatibleMap(NetworkConnection connection, GMMapDefinition definition)
		{
			if (ClientMaps.TryGetValue(connection.ClientId, out Dictionary<string, int> value) && value.TryGetValue(definition.Id, out var value2))
			{
				return value2 == definition.NetworkVersion;
			}
			return false;
		}

		internal static bool TryUnloadForAll(out string error)
		{
			Register();
			if (!IsServer())
			{
				return Fail("Only the host can request a synchronized map unload.", out error);
			}
			if (_pendingMap != null || GMMapRuntime.IsLoading)
			{
				return Fail("A map transition is already in progress.", out error);
			}
			NetworkConnection[] array = AuthenticatedClients();
			foreach (NetworkConnection val in array)
			{
				InstanceFinder.ServerManager.Broadcast<MapUnloadRequest>(val, default(MapUnloadRequest), true, (Channel)0);
			}
			error = "";
			return true;
		}

		internal static void Update()
		{
			Register();
			if (_pendingMap != null && Time.unscaledTime >= _deadline)
			{
				Abort($"Timed out after {45f:0} seconds waiting for clients.");
			}
		}

		internal static void Reset()
		{
			if (_clientRegistered && Object.op_Implicit((Object)(object)InstanceFinder.ClientManager))
			{
				InstanceFinder.ClientManager.UnregisterBroadcast<MapLoadRequest>(ClientLoadHandler);
				InstanceFinder.ClientManager.UnregisterBroadcast<MapAbortRequest>(ClientAbortHandler);
				InstanceFinder.ClientManager.UnregisterBroadcast<MapUnloadRequest>(ClientUnloadHandler);
			}
			if (_serverRegistered && Object.op_Implicit((Object)(object)InstanceFinder.ServerManager))
			{
				InstanceFinder.ServerManager.UnregisterBroadcast<MapCatalogHello>(ServerCatalogHandler);
				InstanceFinder.ServerManager.UnregisterBroadcast<MapLoadResult>(ServerResultHandler);
				InstanceFinder.ServerManager.OnRemoteConnectionState -= OnRemoteConnectionState;
			}
			_clientRegistered = false;
			_serverRegistered = false;
			_pendingMap = null;
			PendingClients.Clear();
			ClientMaps.Clear();
			GMMapRuntime.Reset();
		}

		private static void OnServerCatalog(NetworkConnection connection, MapCatalogHello message, Channel _)
		{
			int num = Math.Min(Math.Min(message.MapIds.Length, message.NetworkVersions.Length), 128);
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			for (int i = 0; i < num; i++)
			{
				if (!string.IsNullOrWhiteSpace(message.MapIds[i]))
				{
					dictionary[message.MapIds[i]] = message.NetworkVersions[i];
				}
			}
			ClientMaps[connection.ClientId] = dictionary;
		}

		private static void OnClientLoad(MapLoadRequest message, Channel _)
		{
			if (!GMMapApi.Catalog.TryGet(message.MapId, out GMMapDefinition definition) || definition.NetworkVersion != message.NetworkVersion)
			{
				SendResult(message, success: false, "Compatible map '" + message.MapId + "' is not registered locally.");
				return;
			}
			GMMapRuntime.Load(definition, delegate(bool success, string error)
			{
				SendResult(message, success, error);
			});
		}

		private static void SendResult(MapLoadRequest request, bool success, string error)
		{
			if (Object.op_Implicit((Object)(object)InstanceFinder.ClientManager))
			{
				InstanceFinder.ClientManager.Broadcast<MapLoadResult>(new MapLoadResult(request.RequestId, request.MapId, success, error), (Channel)0);
			}
		}

		private static void OnServerResult(NetworkConnection connection, MapLoadResult message, Channel _)
		{
			if (_pendingMap == null || message.RequestId != _requestId || message.MapId != _pendingMap.Id || !PendingClients.Contains(connection.ClientId))
			{
				return;
			}
			if (!message.Success)
			{
				Abort($"Client {connection.ClientId} failed to load the map: {message.Error}");
				return;
			}
			PendingClients.Remove(connection.ClientId);
			if (PendingClients.Count == 0)
			{
				GMMapDefinition pendingMap = _pendingMap;
				_pendingMap = null;
				Plugin.Log.LogInfo((object)("All clients loaded '" + pendingMap.Id + "'."));
				GMMapApi.NotifyAllLoaded(pendingMap);
			}
		}

		private static void OnClientAbort(MapAbortRequest message, Channel _)
		{
			GMMapRuntime.Unload();
			GMMapApi.NotifyFailed(message.MapId, message.Error);
			Plugin.Log.LogError((object)("Map load '" + message.MapId + "' aborted: " + message.Error));
		}

		private static void OnClientUnload(MapUnloadRequest _, Channel __)
		{
			GMMapRuntime.Unload();
		}

		private static void OnRemoteConnectionState(NetworkConnection connection, RemoteConnectionStateArgs args)
		{
			//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)
			if ((int)args.ConnectionState == 0)
			{
				ClientMaps.Remove(connection.ClientId);
				if (_pendingMap != null && PendingClients.Contains(connection.ClientId))
				{
					Abort($"Client {connection.ClientId} disconnected during the map transition.");
				}
			}
		}

		private static void Abort(string error)
		{
			GMMapDefinition pendingMap = _pendingMap;
			if (pendingMap != null)
			{
				MapAbortRequest mapAbortRequest = new MapAbortRequest(_requestId, pendingMap.Id, error);
				NetworkConnection[] array = AuthenticatedClients();
				foreach (NetworkConnection val in array)
				{
					InstanceFinder.ServerManager.Broadcast<MapAbortRequest>(val, mapAbortRequest, true, (Channel)0);
				}
				_pendingMap = null;
				PendingClients.Clear();
			}
		}

		private static NetworkConnection[] AuthenticatedClients()
		{
			if (!Object.op_Implicit((Object)(object)InstanceFinder.ServerManager))
			{
				return Array.Empty<NetworkConnection>();
			}
			return InstanceFinder.ServerManager.Clients.Values.Where((NetworkConnection connection) => connection.IsAuthenticated).ToArray();
		}

		private static bool IsServer()
		{
			if (Object.op_Implicit((Object)(object)Server.Instance))
			{
				return ((NetworkBehaviour)Server.Instance).IsServerInitialized;
			}
			return false;
		}

		private static bool Fail(string message, out string error)
		{
			error = message;
			return false;
		}

		private static bool Pass(out string error)
		{
			error = "";
			return true;
		}

		private static void WriteCatalog(Writer writer, MapCatalogHello message)
		{
			int num = Math.Min(Math.Min(message.MapIds.Length, message.NetworkVersions.Length), 128);
			writer.WriteUInt8Unpacked((byte)num);
			for (int i = 0; i < num; i++)
			{
				writer.WriteString(message.MapIds[i]);
				writer.WriteInt32(message.NetworkVersions[i]);
			}
		}

		private static MapCatalogHello ReadCatalog(Reader reader)
		{
			int num = Math.Min((int)reader.ReadUInt8Unpacked(), 128);
			string[] array = new string[num];
			int[] array2 = new int[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = reader.ReadStringAllocated();
				array2[i] = reader.ReadInt32();
			}
			return new MapCatalogHello(array, array2);
		}
	}
	[HarmonyPatch(typeof(Client), "OnStartClient")]
	internal static class GMMapClientStartPatch
	{
		private static void Postfix(Client __instance)
		{
			if (((NetworkBehaviour)__instance).Owner.IsLocalClient)
			{
				GMMapNetwork.SendCatalog();
			}
		}
	}
	[HarmonyPatch(typeof(Server), "OnStartClient")]
	internal static class GMMapServerStartPatch
	{
		private static void Postfix()
		{
			GMMapNetwork.Register();
		}
	}
	[HarmonyPatch(typeof(Server), "OnStopClient")]
	internal static class GMMapServerStopPatch
	{
		private static void Prefix()
		{
			GMMapNetwork.Reset();
		}
	}
	internal static class GMMapRuntime
	{
		private static AssetBundle? _bundle;

		private static Scene _scene;

		private static bool _unloadRequested;

		internal static GMMapDefinition? ActiveMap { get; private set; }

		internal static bool IsLoading { get; private set; }

		internal static void Load(GMMapDefinition definition, Action<bool, string> completed)
		{
			if (IsLoading)
			{
				completed(arg1: false, "Another map transition is already in progress.");
				return;
			}
			_unloadRequested = false;
			((MonoBehaviour)Plugin.Instance).StartCoroutine(LoadRoutine(definition, completed));
		}

		internal static void Unload(Action? completed = null)
		{
			if (IsLoading)
			{
				_unloadRequested = true;
			}
			else
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(UnloadRoutine(completed));
			}
		}

		internal static void Reset()
		{
			//IL_0018: 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)
			if (((Scene)(ref _scene)).IsValid() && ((Scene)(ref _scene)).isLoaded)
			{
				SceneManager.UnloadSceneAsync(_scene);
			}
			AssetBundle? bundle = _bundle;
			if (bundle != null)
			{
				bundle.Unload(true);
			}
			_bundle = null;
			_scene = default(Scene);
			ActiveMap = null;
			IsLoading = false;
			_unloadRequested = false;
		}

		private static IEnumerator LoadRoutine(GMMapDefinition definition, Action<bool, string> completed)
		{
			IsLoading = true;
			yield return UnloadRoutine();
			if (!File.Exists(definition.BundlePath))
			{
				Finish(success: false, "AssetBundle not found: " + definition.BundlePath, completed);
				yield break;
			}
			_bundle = AssetBundle.LoadFromFile(definition.BundlePath);
			if (!Object.op_Implicit((Object)(object)_bundle))
			{
				Finish(success: false, "Unity could not load AssetBundle '" + definition.BundlePath + "'.", completed);
				yield break;
			}
			string scenePath = _bundle.GetAllScenePaths().FirstOrDefault((string path) => string.Equals(path, definition.SceneName, StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetFileNameWithoutExtension(path), definition.SceneName, StringComparison.OrdinalIgnoreCase));
			if (scenePath == null)
			{
				_bundle.Unload(true);
				_bundle = null;
				Finish(success: false, "Scene '" + definition.SceneName + "' is not present in the AssetBundle.", completed);
				yield break;
			}
			AsyncOperation val = SceneManager.LoadSceneAsync(scenePath, (LoadSceneMode)1);
			if (val == null)
			{
				_bundle.Unload(true);
				_bundle = null;
				Finish(success: false, "Unity refused to load scene '" + scenePath + "'.", completed);
				yield break;
			}
			yield return val;
			_scene = SceneManager.GetSceneByPath(scenePath);
			if (!((Scene)(ref _scene)).IsValid() || !((Scene)(ref _scene)).isLoaded)
			{
				_bundle.Unload(true);
				_bundle = null;
				_scene = default(Scene);
				Finish(success: false, "Scene '" + scenePath + "' did not finish loading.", completed);
				yield break;
			}
			ActiveMap = definition;
			IsLoading = false;
			if (_unloadRequested)
			{
				_unloadRequested = false;
				yield return UnloadRoutine();
				completed(arg1: false, "Map load was cancelled.");
			}
			else
			{
				GMMapApi.NotifyLocalLoaded(definition);
				completed(arg1: true, "");
			}
		}

		private static IEnumerator UnloadRoutine(Action? completed = null)
		{
			if (((Scene)(ref _scene)).IsValid() && ((Scene)(ref _scene)).isLoaded)
			{
				AsyncOperation val = SceneManager.UnloadSceneAsync(_scene);
				if (val != null)
				{
					yield return val;
				}
			}
			AssetBundle? bundle = _bundle;
			if (bundle != null)
			{
				bundle.Unload(true);
			}
			bool flag = ActiveMap != null;
			_bundle = null;
			_scene = default(Scene);
			ActiveMap = null;
			if (flag)
			{
				GMMapApi.NotifyUnloaded();
			}
			completed?.Invoke();
		}

		private static void Finish(bool success, string error, Action<bool, string> completed)
		{
			IsLoading = false;
			_unloadRequested = false;
			completed(success, error);
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("ArceDev.GMMapLoader", "GM Map Loader", "0.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Id = "ArceDev.GMMapLoader";

		internal static Plugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		public static string Name => "GM Map Loader";

		public static string Version => "0.1.0";

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			GMMapApi.Validate();
			GMMapNetwork.Initialize();
			GMMapManifestDiscovery.Discover();
			Harmony.CreateAndPatchAll(typeof(Plugin).Assembly, "ArceDev.GMMapLoader");
			Log.LogInfo((object)$"Plugin {Name} loaded {GMMapApi.Catalog.All.Count} map definition(s).");
		}

		private void Update()
		{
			GMMapNetwork.Update();
		}

		private void OnDestroy()
		{
			GMMapNetwork.Reset();
			Instance = null;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ConstantExpectedAttribute : Attribute
	{
		public object? Min { get; set; }

		public object? Max { get; set; }
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SetsRequiredMembersAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object?[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = new object[0];
		}

		public StringSyntaxAttribute(string syntax, params object?[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class UnscopedRefAttribute : Attribute
	{
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresPreviewFeaturesAttribute : Attribute
	{
		public string? Message { get; }

		public string? Url { get; set; }

		public RequiresPreviewFeaturesAttribute()
		{
		}

		public RequiresPreviewFeaturesAttribute(string? message)
		{
			Message = message;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CollectionBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public string MethodName { get; }

		public CollectionBuilderAttribute(Type builderType, string methodName)
		{
			BuilderType = builderType;
			MethodName = methodName;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CompilerFeatureRequiredAttribute : Attribute
	{
		public const string RefStructs = "RefStructs";

		public const string RequiredMembers = "RequiredMembers";

		public string FeatureName { get; }

		public bool IsOptional { get; set; }

		public CompilerFeatureRequiredAttribute(string featureName)
		{
			FeatureName = featureName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
	{
		public string[] Arguments { get; }

		public InterpolatedStringHandlerArgumentAttribute(string argument)
		{
			Arguments = new string[1] { argument };
		}

		public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
		{
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerAttribute : Attribute
	{
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ModuleInitializerAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class OverloadResolutionPriorityAttribute : Attribute
	{
		public int Priority { get; }

		public OverloadResolutionPriorityAttribute(int priority)
		{
			Priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiredMemberAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresLocationAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SkipLocalsInitAttribute : Attribute
	{
	}
}