Decompiled source of Map Loader v1.0.0

BepInEx/plugins/GraveyardOrbit.MapLoader/GraveyardOrbit.MapLoader.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace GraveyardOrbit.MapLoader
{
	internal static class MapInject
	{
		private static readonly HashSet<string> _errorLogged = new HashSet<string>();

		internal static void EnsureInjected()
		{
			StructureCatalog i = StructureCatalog.I;
			if ((Object)(object)i == (Object)null)
			{
				return;
			}
			string pluginPath = Paths.PluginPath;
			if (string.IsNullOrEmpty(pluginPath) || !Directory.Exists(pluginPath))
			{
				return;
			}
			foreach (string item in Directory.EnumerateDirectories(pluginPath, "maps", SearchOption.AllDirectories))
			{
				string directoryName = Path.GetDirectoryName(item);
				if (string.IsNullOrEmpty(directoryName))
				{
					continue;
				}
				string text = Path.Combine(directoryName, "contracts");
				if (!Directory.Exists(text))
				{
					continue;
				}
				foreach (string item2 in Directory.EnumerateFiles(item, "*.json"))
				{
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(item2);
					if (string.IsNullOrEmpty(fileNameWithoutExtension))
					{
						continue;
					}
					string text2 = Path.Combine(text, fileNameWithoutExtension + ".contract.json");
					if (!File.Exists(text2))
					{
						if (_errorLogged.Add(fileNameWithoutExtension))
						{
							MapLoaderPlugin.Log.LogError((object)("[maploader] missing contract for '" + fileNameWithoutExtension + "'. Expected:\n  " + text2));
						}
					}
					else
					{
						if (Has(i.campaign, fileNameWithoutExtension) || Has(i.ladder, fileNameWithoutExtension))
						{
							continue;
						}
						try
						{
							InjectOne(i, fileNameWithoutExtension, item2, text2);
						}
						catch (Exception ex)
						{
							if (_errorLogged.Add(fileNameWithoutExtension))
							{
								MapLoaderPlugin.Log.LogError((object)("[maploader] failed to inject '" + fileNameWithoutExtension + "': " + ex));
							}
						}
					}
				}
			}
		}

		private static void InjectOne(StructureCatalog catalog, string id, string mapPath, string contractPath)
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			string text = File.ReadAllText(mapPath);
			JObject val = JObject.Parse(File.ReadAllText(contractPath));
			MegastructureData val2 = MegastructureData.FromJson(text);
			StructureDef val3 = ScriptableObject.CreateInstance<StructureDef>();
			((Object)val3).name = (string)val["id"];
			val3.id = (string)val["id"];
			val3.displayName = (string)val["displayName"];
			val3.description = (string)val["description"];
			val3.cellCount = val2.count;
			val3.sealedLayers = (bool?)val["sealedLayers"] == true;
			val3.startingMoney = ((int?)val["startingMoney"]).GetValueOrDefault();
			val3.glyphCount = ((int?)val["glyphCount"]).GetValueOrDefault();
			val3.greenCount = ((int?)val["greenCount"]) ?? (-1);
			val3.cells = new TextAsset(text);
			JToken obj = val["bands"];
			JArray val4 = (JArray)(object)((obj is JArray) ? obj : null);
			val3.bands = (BandDef[])((val4 == null) ? ((Array)new BandDef[0]) : ((Array)((IEnumerable<JToken>)val4).Select((Func<JToken, BandDef>)((JToken b) => new BandDef
			{
				layer = (int)b[(object)"layer"],
				outerFrac = (((float?)b[(object)"outerFrac"]) ?? 1f),
				hpSealed = (((int?)b[(object)"hpSealed"]) ?? 75),
				special1 = ((int?)b[(object)"special1"]).GetValueOrDefault(),
				special2 = ((int?)b[(object)"special2"]).GetValueOrDefault(),
				special3 = ((int?)b[(object)"special3"]).GetValueOrDefault(),
				meta1 = ((int?)b[(object)"meta1"]).GetValueOrDefault(),
				explosive = ((int?)b[(object)"explosive"]).GetValueOrDefault(),
				lightning = ((int?)b[(object)"lightning"]).GetValueOrDefault(),
				voidTiles = ((int?)b[(object)"voidTiles"]).GetValueOrDefault(),
				swarm = ((int?)b[(object)"swarm"]).GetValueOrDefault(),
				unsealedLook = ((int?)b[(object)"unsealedLook"]).GetValueOrDefault()
			})).ToArray()));
			JToken obj2 = val["artifactCells"];
			JArray val5 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
			val3.artifactCells = (Vector2Int[])((val5 == null) ? ((Array)new Vector2Int[0]) : ((Array)((IEnumerable<JToken>)val5).Select((Func<JToken, Vector2Int>)((JToken a) => new Vector2Int((int)a[(object)0], (int)a[(object)1]))).ToArray()));
			int num = ((int?)val["cellCount"]) ?? (-1);
			if (num != val2.count)
			{
				MapLoaderPlugin.Log.LogWarning((object)$"[maploader] '{id}' contract cellCount {num} != map count {val2.count}; using {val2.count}");
			}
			catalog.campaign = Prepend(catalog.campaign, val3);
			catalog.ladder = Prepend(catalog.ladder, val3);
			if (AccessTools.Field(typeof(StructureCatalog), "_cache")?.GetValue(null) is Dictionary<string, StructureDef> dictionary)
			{
				dictionary[val3.id] = val3;
			}
			MapLoaderPlugin.Log.LogInfo((object)$"[maploader] injected '{val3.id}' ({val2.count:N0} cells, {val3.bands.Length} bands) from {mapPath}");
		}

		private static bool Has(StructureDef[] list, string id)
		{
			if (list == null)
			{
				return false;
			}
			foreach (StructureDef val in list)
			{
				if ((Object)(object)val != (Object)null && val.id == id)
				{
					return true;
				}
			}
			return false;
		}

		private static StructureDef[] Prepend(StructureDef[] list, StructureDef def)
		{
			List<StructureDef> list2 = new List<StructureDef> { def };
			if (list != null)
			{
				list2.AddRange(list);
			}
			return list2.ToArray();
		}
	}
	[BepInPlugin("agentbox.graveyardorbit.maploader", "Graveyard Orbit - Map Loader", "1.0.0")]
	public sealed class MapLoaderPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "agentbox.graveyardorbit.maploader";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("agentbox.graveyardorbit.maploader");
			try
			{
				_harmony.PatchAll(typeof(MapLoaderPlugin).Assembly);
			}
			catch (Exception ex)
			{
				Log.LogError((object)("patch failed: " + ex));
			}
		}

		internal static void Inject()
		{
			try
			{
				MapInject.EnsureInjected();
			}
			catch (Exception ex)
			{
				Log.LogError((object)("inject failed: " + ex));
			}
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MainMenuController), "BuildUI")]
	internal static class MenuBuildPatch
	{
		private static void Postfix()
		{
			MapLoaderPlugin.Inject();
		}
	}
}