Decompiled source of Reminiscence v0.0.1

BepInEx/plugins/Reminiscence/Reminiscence.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Reminiscence")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Monster Train 1 field and boss music for Monster Train 2.")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: AssemblyInformationalVersion("0.0.1+e355ffb5cc8c33382b9f9d7318d24c9b60e266cb")]
[assembly: AssemblyProduct("Monster Train: Reminiscence")]
[assembly: AssemblyTitle("Reminiscence")]
[assembly: AssemblyVersion("0.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Reminiscence
{
	internal static class BattleMusicPatches
	{
		[HarmonyPatch]
		private static class StartPatch
		{
			private static bool Prepare()
			{
				return TargetMethod() != null;
			}

			private static MethodBase? TargetMethod()
			{
				Type type = AccessTools.TypeByName("SoundManager");
				if (!(type == null))
				{
					return AccessTools.Method(type, "Start", (Type[])null, (Type[])null);
				}
				return null;
			}

			private static void Postfix(MonoBehaviour __instance)
			{
				try
				{
					MusicInstaller.Install(__instance);
				}
				catch (Exception arg)
				{
					Plugin.LogSource.LogError((object)$"Music install failed: {arg}");
				}
			}
		}

		[HarmonyPatch]
		private static class PlayPatch
		{
			private static bool Prepare()
			{
				return TargetMethod() != null;
			}

			private static MethodBase? TargetMethod()
			{
				Type type = AccessTools.TypeByName("SoundManager");
				if (!(type == null))
				{
					return AccessTools.Method(type, "PlayBattleMusic", (Type[])null, (Type[])null);
				}
				return null;
			}

			private static void Prefix(ref string trackNameOverride)
			{
				if (Plugin.BossMusics.Value && !string.IsNullOrEmpty(trackNameOverride) && BossAlternates.TryGetValue(trackNameOverride, out string value) && Loaded.Contains(value) && Coin.Next(2) == 0)
				{
					trackNameOverride = value;
				}
			}

			private static void Postfix(MonoBehaviour __instance)
			{
				if (!InRestart(__instance))
				{
					return;
				}
				try
				{
					float num = HighTransitionSeconds(__instance);
					AccessTools.Method(((object)__instance).GetType(), "TransitionToSnapshot", (Type[])null, (Type[])null)?.Invoke(__instance, new object[2] { "Base", num });
				}
				catch (Exception ex)
				{
					Plugin.LogSource.LogError((object)("Could not return music to the base layer: " + ex.Message));
				}
			}

			private static float HighTransitionSeconds(MonoBehaviour soundManager)
			{
				Component component = ((Component)soundManager).GetComponent(AccessTools.TypeByName("ShinyShoe.Audio.CoreAudioSystem"));
				if ((Object)(object)component == (Object)null)
				{
					return 0f;
				}
				Array array = AccessTools.Field(((object)component).GetType(), "_musicState")?.GetValue(component) as Array;
				object obj = AccessTools.Field(((object)component).GetType(), "_musicNextTrackSlot")?.GetValue(component);
				if (array == null || obj == null || array.Length == 0)
				{
					return 0f;
				}
				object value = array.GetValue(((int)obj + 1) % array.Length);
				object obj2 = ((value == null) ? null : AccessTools.Field(value.GetType(), "MusicDefinition")?.GetValue(value));
				if (obj2 == null || !(AccessTools.Field(obj2.GetType(), "Snapshots")?.GetValue(obj2) is Array array2))
				{
					return 0f;
				}
				foreach (object item in array2)
				{
					if (item != null && !(AccessTools.Field(item.GetType(), "Name")?.GetValue(item) as string != "High"))
					{
						object obj3 = AccessTools.Field(item.GetType(), "TransitionTimeSeconds")?.GetValue(item);
						if (obj3 is float)
						{
							return (float)obj3;
						}
					}
				}
				return 0f;
			}

			private static bool InRestart(MonoBehaviour soundManager)
			{
				object value = AccessTools.Field(((object)soundManager).GetType(), "saveManager").GetValue(soundManager);
				if (value == null)
				{
					return false;
				}
				PropertyInfo propertyInfo = AccessTools.Property(value.GetType(), "IsInRestartBattleMode");
				bool flag = default(bool);
				int num;
				if (propertyInfo != null)
				{
					object value2 = propertyInfo.GetValue(value);
					if (value2 is bool)
					{
						flag = (bool)value2;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
		}

		[HarmonyPatch(typeof(AudioClip), "UnloadAudioData")]
		private static class KeepClipDataPatch
		{
			private static bool Prefix(AudioClip __instance)
			{
				if (!((Object)(object)__instance == (Object)null) && ((Object)__instance).name != null)
				{
					return !((Object)__instance).name.StartsWith("Reminiscence/", StringComparison.Ordinal);
				}
				return true;
			}
		}

		private static readonly Dictionary<string, string> BossAlternates = new Dictionary<string, string>
		{
			{ "BattleMusic_Arkios", "Reminiscence/BattleMusic_Daedalus" },
			{ "BattleMusic_Fleshweaver", "Reminiscence/BattleMusic_Talos" },
			{ "BattleMusic_Cael", "Reminiscence/BattleMusic_Fel" },
			{ "BattleMusic_HallowStryx", "Reminiscence/BattleMusic_Archus" },
			{ "BattleMusic_Seraph", "Reminiscence/BattleMusic_Seraph" },
			{ "BattleMusic_Titans", "Reminiscence/BattleMusic_TLD" }
		};

		private static readonly Random Coin = new Random();

		private static readonly HashSet<string> Loaded = new HashSet<string>();

		internal static void Remember(string trackId)
		{
			if (!string.IsNullOrEmpty(trackId))
			{
				Loaded.Add(trackId);
			}
		}
	}
	internal static class Mt1Install
	{
		public static string? Resolve(string configured)
		{
			foreach (string item in Candidates(configured))
			{
				if (IsInstall(item))
				{
					return Path.GetFullPath(item);
				}
			}
			return null;
		}

		public static bool IsInstall(string path)
		{
			if (!string.IsNullOrWhiteSpace(path))
			{
				return File.Exists(Path.Combine(path, "MonsterTrain.exe"));
			}
			return false;
		}

		private static IEnumerable<string> Candidates(string configured)
		{
			if (!string.IsNullOrWhiteSpace(configured))
			{
				yield return configured;
			}
			string environmentVariable = Environment.GetEnvironmentVariable("MT1_ROOT");
			if (!string.IsNullOrWhiteSpace(environmentVariable))
			{
				yield return environmentVariable;
			}
			string dataPath = Application.dataPath;
			if (!string.IsNullOrEmpty(dataPath))
			{
				string directoryName = Path.GetDirectoryName(dataPath);
				string text = (string.IsNullOrEmpty(directoryName) ? null : Path.GetDirectoryName(directoryName));
				if (!string.IsNullOrEmpty(text))
				{
					yield return Path.Combine(text, "Monster Train");
				}
			}
		}
	}
	internal static class MusicCache
	{
		public const int ManifestVersion = 3;

		public static string DirectoryForPlugin()
		{
			return Path.Combine(Path.GetDirectoryName(typeof(MusicCache).Assembly.Location), "reminiscence-music");
		}

		public static MusicManifest? Load(string directory)
		{
			string path = Path.Combine(directory, "manifest.json");
			if (!File.Exists(path))
			{
				return null;
			}
			MusicManifest musicManifest = ManifestReader.Read(File.ReadAllText(path));
			if (musicManifest.version != 3 || musicManifest.pieces == null)
			{
				return null;
			}
			return musicManifest;
		}
	}
	[Serializable]
	internal sealed class MusicManifest
	{
		public int version;

		public bool tld;

		public MusicPiece[] pieces = Array.Empty<MusicPiece>();
	}
	[Serializable]
	internal sealed class MusicPiece
	{
		public string id = "";

		public string musicId = "";

		public string trackId = "";

		public string role = "";

		public string name = "";

		public float highTransitionSeconds;

		public bool layersShareLength;

		public MusicLayer[] layers = Array.Empty<MusicLayer>();
	}
	[Serializable]
	internal sealed class MusicLayer
	{
		public string id = "";

		public string file = "";

		public int sampleRate;

		public int channels;

		public int samples;
	}
	internal static class ManifestReader
	{
		private sealed class JsonCursor
		{
			private readonly string _text;

			private int _index;

			public JsonCursor(string text)
			{
				_text = text;
			}

			public void Object(Action<string> field)
			{
				Expect('{');
				if (Peek() == '}')
				{
					Take();
					return;
				}
				while (true)
				{
					string obj = String();
					Expect(':');
					field(obj);
					if (Peek() != ',')
					{
						break;
					}
					Take();
				}
				Expect('}');
			}

			public void Array(Action element)
			{
				Expect('[');
				if (Peek() == ']')
				{
					Take();
					return;
				}
				while (true)
				{
					element();
					if (Peek() != ',')
					{
						break;
					}
					Take();
				}
				Expect(']');
			}

			public void Skip()
			{
				char c = Peek();
				if (c == '"')
				{
					String();
				}
				else if (c == '{')
				{
					Object(delegate
					{
						Skip();
					});
				}
				else if (c == '[')
				{
					Array(Skip);
				}
				else if (c == 't' || c == 'f' || c == 'n')
				{
					while (_index < _text.Length && char.IsLetter(_text[_index]))
					{
						_index++;
					}
				}
				else
				{
					while (_index < _text.Length && "-+.eE0123456789".IndexOf(_text[_index]) >= 0)
					{
						_index++;
					}
				}
			}

			public string String()
			{
				Expect('"');
				StringBuilder stringBuilder = new StringBuilder();
				while (_index < _text.Length)
				{
					char c = _text[_index++];
					switch (c)
					{
					case '"':
						return stringBuilder.ToString();
					default:
						stringBuilder.Append(c);
						break;
					case '\\':
					{
						char c2 = _text[_index++];
						if (c2 == 'u')
						{
							int num = int.Parse(_text.Substring(_index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
							_index += 4;
							stringBuilder.Append((char)num);
							break;
						}
						StringBuilder stringBuilder2 = stringBuilder;
						stringBuilder2.Append(c2 switch
						{
							'"' => '"', 
							'\\' => '\\', 
							'/' => '/', 
							'b' => '\b', 
							'f' => '\f', 
							'n' => '\n', 
							'r' => '\r', 
							't' => '\t', 
							_ => throw new InvalidDataException("Music manifest has an invalid string escape."), 
						});
						break;
					}
					}
				}
				throw new InvalidDataException("Music manifest has an unclosed string.");
			}

			public int Int()
			{
				return int.Parse(Number(), CultureInfo.InvariantCulture);
			}

			public float Float()
			{
				return float.Parse(Number(), CultureInfo.InvariantCulture);
			}

			public bool Bool()
			{
				if (Peek() == 't')
				{
					Literal("true");
					return true;
				}
				Literal("false");
				return false;
			}

			private string Number()
			{
				SkipSpace();
				int index = _index;
				while (_index < _text.Length && "-+.eE0123456789".IndexOf(_text[_index]) >= 0)
				{
					_index++;
				}
				return _text.Substring(index, _index - index);
			}

			private void Literal(string word)
			{
				SkipSpace();
				for (int i = 0; i < word.Length; i++)
				{
					if (_text[_index + i] != word[i])
					{
						throw new InvalidDataException("Music manifest has an invalid value.");
					}
				}
				_index += word.Length;
			}

			private char Peek()
			{
				SkipSpace();
				if (_index >= _text.Length)
				{
					throw new InvalidDataException("Music manifest ended early.");
				}
				return _text[_index];
			}

			private char Take()
			{
				char result = Peek();
				_index++;
				return result;
			}

			private void Expect(char expected)
			{
				if (Take() != expected)
				{
					throw new InvalidDataException($"Music manifest expected '{expected}'.");
				}
			}

			private void SkipSpace()
			{
				while (_index < _text.Length && char.IsWhiteSpace(_text[_index]))
				{
					_index++;
				}
			}
		}

		public static MusicManifest Read(string json)
		{
			JsonCursor reader = new JsonCursor(json);
			MusicManifest manifest = new MusicManifest();
			List<MusicPiece> pieces = new List<MusicPiece>();
			reader.Object(delegate(string key)
			{
				switch (key)
				{
				case "version":
					manifest.version = reader.Int();
					break;
				case "tld":
					manifest.tld = reader.Bool();
					break;
				case "pieces":
					reader.Array(delegate
					{
						pieces.Add(ReadPiece(reader));
					});
					break;
				default:
					reader.Skip();
					break;
				}
			});
			manifest.pieces = pieces.ToArray();
			return manifest;
		}

		private static MusicPiece ReadPiece(JsonCursor reader)
		{
			MusicPiece piece = new MusicPiece();
			List<MusicLayer> layers = new List<MusicLayer>();
			reader.Object(delegate(string key)
			{
				switch (key)
				{
				case "id":
					piece.id = reader.String();
					break;
				case "musicId":
					piece.musicId = reader.String();
					break;
				case "trackId":
					piece.trackId = reader.String();
					break;
				case "role":
					piece.role = reader.String();
					break;
				case "name":
					piece.name = reader.String();
					break;
				case "highTransitionSeconds":
					piece.highTransitionSeconds = reader.Float();
					break;
				case "layersShareLength":
					piece.layersShareLength = reader.Bool();
					break;
				case "layers":
					reader.Array(delegate
					{
						layers.Add(ReadLayer(reader));
					});
					break;
				default:
					reader.Skip();
					break;
				}
			});
			piece.layers = layers.ToArray();
			return piece;
		}

		private static MusicLayer ReadLayer(JsonCursor reader)
		{
			MusicLayer layer = new MusicLayer();
			reader.Object(delegate(string key)
			{
				switch (key)
				{
				case "id":
					layer.id = reader.String();
					break;
				case "file":
					layer.file = reader.String();
					break;
				case "sampleRate":
					layer.sampleRate = reader.Int();
					break;
				case "channels":
					layer.channels = reader.Int();
					break;
				case "samples":
					layer.samples = reader.Int();
					break;
				default:
					reader.Skip();
					break;
				}
			});
			return layer;
		}
	}
	internal static class MusicInstaller
	{
		private static bool _installed;

		private static bool _extractDone;

		private static Process? _process;

		internal static bool Installed => _installed;

		internal static bool ReadyToReport { get; private set; }

		internal static bool ExtractionRunning
		{
			get
			{
				if (_process != null)
				{
					return !_process.HasExited;
				}
				return false;
			}
		}

		internal static string MenuMessage()
		{
			if (_installed)
			{
				return "Reminiscence Activated!";
			}
			if (Mt1Install.Resolve(Plugin.Mt1Path.Value) == null)
			{
				return "Cannot find MT1 installation.";
			}
			return "Reminiscence could not load MT1 music.";
		}

		public static void OnPluginAwake()
		{
			Application.quitting += OnQuit;
			string text = Mt1Install.Resolve(Plugin.Mt1Path.Value);
			if (text == null)
			{
				Plugin.LogSource.LogError((object)"MT1 not found. Set MT1 InstallPath in the Reminiscence config and restart.");
				ReadyToReport = true;
				StatusNotices.WatchForMainMenu((MonoBehaviour)(object)Plugin.Instance);
			}
			else if (MusicCache.Load(MusicCache.DirectoryForPlugin()) == null)
			{
				if (!BeginExtract(text, MusicCache.DirectoryForPlugin()))
				{
					Plugin.LogSource.LogError((object)("Music cache is missing at " + MusicCache.DirectoryForPlugin() + "."));
					ReadyToReport = true;
					StatusNotices.WatchForMainMenu((MonoBehaviour)(object)Plugin.Instance);
				}
				else
				{
					HoldLoadingScreen();
				}
			}
		}

		public static void Install(MonoBehaviour soundManager)
		{
			if (_installed)
			{
				ReadyToReport = true;
				StatusNotices.WatchForMainMenu(soundManager);
				return;
			}
			if (_process != null && !_process.HasExited)
			{
				soundManager.StartCoroutine(InstallWhenExtracted(soundManager));
				return;
			}
			try
			{
				InstallNow(soundManager);
			}
			finally
			{
				ReadyToReport = true;
				StatusNotices.WatchForMainMenu(soundManager);
			}
		}

		private static void InstallNow(MonoBehaviour soundManager)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			FinishProcess();
			string text = Mt1Install.Resolve(Plugin.Mt1Path.Value);
			if (text == null)
			{
				Plugin.LogSource.LogError((object)"MT1 not found. Set MT1 InstallPath in the Reminiscence config and restart.");
				return;
			}
			bool flag = TldInstall.Present(text);
			string text2 = MusicCache.DirectoryForPlugin();
			MusicManifest musicManifest = MusicCache.Load(text2);
			if (musicManifest == null)
			{
				Plugin.LogSource.LogError((object)("Music cache is missing at " + text2 + "."));
				return;
			}
			Plugin.LogSource.LogInfo((object)$"Music cache has {musicManifest.pieces.Length} pieces. TLD bundle on disk: {flag}.");
			Component component = ((Component)soundManager).GetComponent(AccessTools.TypeByName("ShinyShoe.Audio.CoreAudioSystem"));
			if ((Object)(object)component == (Object)null)
			{
				Plugin.LogSource.LogError((object)"CoreAudioSystem is missing from SoundManager.");
				return;
			}
			object target = Field(Field(component, "AudioSystemData"), "MusicDefData");
			Array array = (Array)Field(target, "Tracks");
			object obj = FindTemplate(array);
			if (obj == null)
			{
				Plugin.LogSource.LogError((object)"MT2 battle music definitions were not found.");
				return;
			}
			AudioMixer val = (AudioMixer)Field(obj, "Mixer");
			AudioMixerGroup val2 = FindGroup(val, "Base");
			AudioMixerGroup highGroup = FindGroup(val, "High");
			AudioMixerSnapshot val3 = val.FindSnapshot("Base");
			AudioMixerSnapshot highSnapshot = val.FindSnapshot("High Intensity");
			if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
			{
				Plugin.LogSource.LogError((object)"BattleMusic mixer is missing its Base group or snapshot.");
				return;
			}
			Type elementType = array.GetType().GetElementType();
			Type nestedType = elementType.DeclaringType.GetNestedType("MusicClipDefinition");
			Type nestedType2 = elementType.DeclaringType.GetNestedType("MusicSnapshotDefinition");
			List<object> list = new List<object>();
			MusicPiece[] pieces = musicManifest.pieces;
			foreach (MusicPiece musicPiece in pieces)
			{
				if (musicPiece == null || string.IsNullOrEmpty(musicPiece.trackId))
				{
					continue;
				}
				if (musicPiece.musicId == "BattleMusic_TLD" && !flag)
				{
					Plugin.LogSource.LogInfo((object)"The Last Divinity bundle is absent. BattleMusic_TLD stays out.");
					continue;
				}
				object obj2 = TryCreate(text2, musicPiece, elementType, nestedType, nestedType2, val, val2, highGroup, val3, highSnapshot);
				if (obj2 != null)
				{
					list.Add(obj2);
					AddTrackEntry(soundManager, musicPiece);
					BattleMusicPatches.Remember(musicPiece.trackId);
					Plugin.LogSource.LogInfo((object)("Registered " + musicPiece.name + " as " + musicPiece.trackId + "."));
				}
			}
			if (list.Count == 0)
			{
				Plugin.LogSource.LogError((object)"No Reminiscence tracks were registered.");
				return;
			}
			Array array2 = Array.CreateInstance(elementType, array.Length + list.Count);
			Array.Copy(array, array2, array.Length);
			for (int j = 0; j < list.Count; j++)
			{
				array2.SetValue(list[j], array.Length + j);
			}
			SetField(target, "Tracks", array2);
			_installed = true;
			Plugin.LogSource.LogInfo((object)$"Registered {list.Count} Reminiscence tracks. TLD bundle: {flag}.");
		}

		private static bool BeginExtract(string mt1, string cacheDir)
		{
			string text = Path.Combine(Path.GetDirectoryName(typeof(MusicInstaller).Assembly.Location), "ReminiscenceExtract.exe");
			if (!File.Exists(text))
			{
				return false;
			}
			Plugin.LogSource.LogInfo((object)("Extracting MT1 music into " + cacheDir + "."));
			Directory.CreateDirectory(cacheDir);
			ProcessStartInfo processStartInfo = new ProcessStartInfo();
			processStartInfo.FileName = text;
			processStartInfo.Arguments = "--mt1 \"" + mt1 + "\" --out \"" + cacheDir + "\"";
			processStartInfo.UseShellExecute = false;
			processStartInfo.CreateNoWindow = true;
			_process = Process.Start(processStartInfo);
			if (_process != null)
			{
				StatusNotices.ShowExtraction();
			}
			return _process != null;
		}

		private static void HoldLoadingScreen()
		{
			Type type = AccessTools.TypeByName("ShinyShoe.Loading.LoadingScreen");
			Type type2 = AccessTools.TypeByName("ShinyShoe.Loading.LoadWaitPredicateTask");
			Type type3 = AccessTools.TypeByName("ShinyShoe.Loading.LoadingTask");
			Type type4 = type?.GetNestedType("DisplayStyle");
			MethodInfo methodInfo = ((type == null || type3 == null) ? null : AccessTools.Method(type, "AddTask", new Type[2]
			{
				type3,
				typeof(bool)
			}, (Type[])null));
			if (type2 == null || type4 == null || methodInfo == null)
			{
				Plugin.LogSource.LogError((object)"Loading screen is unavailable. Startup will not wait for music extraction.");
				return;
			}
			object obj = Activator.CreateInstance(type2, new Func<bool>(ExtractionFinished), Enum.Parse(type4, "FullScreen"), null);
			methodInfo.Invoke(null, new object[2] { obj, true });
			Plugin.LogSource.LogInfo((object)"Holding the loading screen until MT1 music is extracted.");
		}

		private static bool ExtractionFinished()
		{
			if (_extractDone)
			{
				return true;
			}
			if (_process != null && !_process.HasExited)
			{
				StatusNotices.ShowOnFlame();
				return false;
			}
			_extractDone = true;
			StatusNotices.HideExtraction();
			Plugin.LogSource.LogInfo((object)"Music extraction finished. Releasing the loading screen.");
			return true;
		}

		private static IEnumerator InstallWhenExtracted(MonoBehaviour soundManager)
		{
			while (_process != null && !_process.HasExited)
			{
				yield return null;
			}
			Install(soundManager);
		}

		private static void FinishProcess()
		{
			Process process = _process;
			_process = null;
			if (process == null)
			{
				return;
			}
			try
			{
				if (process.HasExited && process.ExitCode != 0)
				{
					Plugin.LogSource.LogError((object)$"Music extraction failed ({process.ExitCode}).");
				}
			}
			finally
			{
				process.Dispose();
			}
		}

		private static void OnQuit()
		{
			if (_process == null || _process.HasExited)
			{
				return;
			}
			try
			{
				_process.Kill();
			}
			catch (Exception ex)
			{
				Plugin.LogSource.LogError((object)("Could not stop music extraction on quit: " + ex.Message));
			}
		}

		private static object? TryCreate(string cacheDir, MusicPiece piece, Type musicType, Type clipType, Type snapType, AudioMixer mixer, AudioMixerGroup baseGroup, AudioMixerGroup? highGroup, AudioMixerSnapshot baseSnapshot, AudioMixerSnapshot? highSnapshot)
		{
			MusicLayer musicLayer = FindLayer(piece, "base");
			if (musicLayer == null)
			{
				Plugin.LogSource.LogError((object)(piece.trackId + " has no base layer."));
				return null;
			}
			AudioClip val = LoadLayer(cacheDir, musicLayer, piece.trackId + ".base");
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			Array value;
			Array value2;
			if (piece.role == "field")
			{
				MusicLayer musicLayer2 = FindLayer(piece, "high");
				if (musicLayer2 == null || (Object)(object)highGroup == (Object)null || (Object)(object)highSnapshot == (Object)null)
				{
					Plugin.LogSource.LogError((object)(piece.trackId + " is missing its high layer or the High mixer snapshot."));
					return null;
				}
				AudioClip val2 = LoadLayer(cacheDir, musicLayer2, piece.trackId + ".high");
				if ((Object)(object)val2 == (Object)null)
				{
					return null;
				}
				value = Two(clipType, Clip(clipType, val, baseGroup), Clip(clipType, val2, highGroup));
				value2 = Two(snapType, Snap(snapType, "Base", baseSnapshot, 1f), Snap(snapType, "High", highSnapshot, 0f));
			}
			else
			{
				value = One(clipType, Clip(clipType, val, baseGroup));
				value2 = One(snapType, Snap(snapType, "Base", baseSnapshot, 1f));
			}
			object obj = Activator.CreateInstance(musicType);
			if (obj == null)
			{
				return null;
			}
			SetField(obj, "Name", piece.trackId);
			SetField(obj, "Mixer", mixer);
			SetField(obj, "Clips", value);
			SetField(obj, "Snapshots", value2);
			return obj;
		}

		private static AudioClip? LoadLayer(string cacheDir, MusicLayer layer, string clipName)
		{
			string text = Path.Combine(cacheDir, layer.file ?? "");
			if (!File.Exists(text))
			{
				Plugin.LogSource.LogError((object)("Missing music file " + text + "."));
				return null;
			}
			return WavPcm.ToClip(text, clipName);
		}

		private static void AddTrackEntry(MonoBehaviour soundManager, MusicPiece piece)
		{
			string name = ((piece.role == "boss") ? "bossBattleMusicTracks" : "battleMusicTracks");
			IList obj = (IList)Field(soundManager, name);
			Type? nestedType = ((object)soundManager).GetType().GetNestedType("BattleMusicTrack");
			object obj2 = Activator.CreateInstance(nestedType);
			nestedType.GetField("publicTrackNameKey").SetValue(obj2, MusicTitles.KeyFor(piece));
			nestedType.GetField("trackNameData").SetValue(obj2, piece.trackId);
			obj.Add(obj2);
			if (piece.role == "field")
			{
				IList list = (IList)Field(soundManager, "battleMusicTrackRandomBucket");
				if (list.Count > 0)
				{
					list.Add(obj2);
				}
			}
		}

		private static object? FindTemplate(Array tracks)
		{
			foreach (object track in tracks)
			{
				if (Field(track, "Name") is string text && text.StartsWith("BattleMusic_", StringComparison.Ordinal))
				{
					return track;
				}
			}
			return null;
		}

		private static MusicLayer? FindLayer(MusicPiece piece, string id)
		{
			if (piece.layers == null)
			{
				return null;
			}
			MusicLayer[] layers = piece.layers;
			foreach (MusicLayer musicLayer in layers)
			{
				if (musicLayer != null && musicLayer.id == id)
				{
					return musicLayer;
				}
			}
			return null;
		}

		private static AudioMixerGroup? FindGroup(AudioMixer mixer, string name)
		{
			AudioMixerGroup[] array = mixer.FindMatchingGroups(name);
			foreach (AudioMixerGroup val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name == name)
				{
					return val;
				}
			}
			return null;
		}

		private static object Clip(Type clipType, AudioClip clip, AudioMixerGroup group)
		{
			object? obj = Activator.CreateInstance(clipType);
			SetField(obj, "Clip", clip);
			SetField(obj, "MixerGroup", group);
			return obj;
		}

		private static object Snap(Type snapType, string name, AudioMixerSnapshot snapshot, float seconds)
		{
			object? obj = Activator.CreateInstance(snapType);
			SetField(obj, "Name", name);
			SetField(obj, "Snapshot", snapshot);
			SetField(obj, "TransitionTimeSeconds", seconds);
			return obj;
		}

		private static Array One(Type element, object value)
		{
			Array array = Array.CreateInstance(element, 1);
			array.SetValue(value, 0);
			return array;
		}

		private static Array Two(Type element, object first, object second)
		{
			Array array = Array.CreateInstance(element, 2);
			array.SetValue(first, 0);
			array.SetValue(second, 1);
			return array;
		}

		private static object Field(object target, string name)
		{
			return TargetField(target, name).GetValue(target);
		}

		private static void SetField(object target, string name, object value)
		{
			TargetField(target, name).SetValue(target, value);
		}

		private static FieldInfo TargetField(object target, string name)
		{
			FieldInfo fieldInfo = AccessTools.Field(target.GetType(), name);
			if (fieldInfo == null)
			{
				throw new MissingFieldException(target.GetType().FullName, name);
			}
			return fieldInfo;
		}
	}
	internal static class MusicTitles
	{
		private static bool _reported;

		public static string KeyFor(MusicPiece piece)
		{
			string text = "Reminiscence/" + piece.musicId + "_Name";
			string title = (string.IsNullOrEmpty(piece.name) ? piece.musicId : piece.name);
			try
			{
				Insert(text, title);
			}
			catch (Exception ex)
			{
				Plugin.LogSource.LogError((object)("Could not add the music title for " + piece.musicId + ": " + ex.Message));
			}
			return text;
		}

		private static void Insert(string key, string title)
		{
			MethodInfo methodInfo = AccessTools.Method(AccessTools.TypeByName("LocalizationUtil"), "GetMainLanguageSource", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException("LocalizationUtil", "GetMainLanguageSource");
			}
			object obj = methodInfo.Invoke(null, null);
			if (obj == null)
			{
				throw new InvalidOperationException("Main language source is missing.");
			}
			IList list = (IList)AccessTools.Field(obj.GetType(), "mLanguages").GetValue(obj);
			if (list == null || list.Count == 0)
			{
				throw new InvalidOperationException("Main language source has no languages.");
			}
			if (AccessTools.Field(obj.GetType(), "translationsData").GetValue(obj) == null)
			{
				throw new InvalidOperationException("Main language source has no translation table.");
			}
			object obj2 = AccessTools.Method(obj.GetType(), "AddTerm", new Type[1] { typeof(string) }, (Type[])null).Invoke(obj, new object[1] { key });
			if (obj2 == null)
			{
				throw new InvalidOperationException("AddTerm returned no term.");
			}
			MethodInfo methodInfo2 = AccessTools.Method(obj2.GetType(), "SetTranslation", new Type[3]
			{
				typeof(int),
				typeof(string),
				typeof(string)
			}, (Type[])null);
			for (int i = 0; i < list.Count; i++)
			{
				methodInfo2.Invoke(obj2, new object[3] { i, title, null });
			}
			if (!_reported)
			{
				_reported = true;
				Plugin.LogSource.LogInfo((object)$"Music titles use the same name in all {list.Count} languages.");
			}
		}
	}
	[BepInPlugin("com.reminiscence.mod", "Monster Train: Reminiscence", "0.0.1")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.reminiscence.mod";

		public const string PluginName = "Monster Train: Reminiscence";

		public const string PluginVersion = "0.0.1";

		internal static ManualLogSource LogSource { get; private set; }

		internal static ConfigEntry<string> Mt1Path { get; private set; }

		internal static ConfigEntry<bool> BossMusics { get; private set; }

		internal static Plugin Instance { get; private set; }

		private void Awake()
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			LogSource = ((BaseUnityPlugin)this).Logger;
			Mt1Path = ((BaseUnityPlugin)this).Config.Bind<string>("Options", "MT1 Path", "", "Monster Train 1 install directory. Empty for autodetection. A change applies on the next launch.");
			BossMusics = ((BaseUnityPlugin)this).Config.Bind<bool>("Options", "MT1 Boss Musics", true, "Coin-flip an MT1 boss theme against the MT2 theme for that boss. Applies on the next battle.");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Monster Train: Reminiscence 0.0.1 loaded.");
			if (AccessTools.TypeByName("SoundManager") == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"SoundManager was not found. Battle music will stay vanilla.");
			}
			new Harmony("com.reminiscence.mod").PatchAll(typeof(Plugin).Assembly);
			MusicInstaller.OnPluginAwake();
		}

		private void Update()
		{
			StatusNotices.Tick();
		}
	}
	internal static class StatusNotices
	{
		[HarmonyPatch]
		private static class MainMenuPatch
		{
			private static bool Prepare()
			{
				return TargetMethod() != null;
			}

			private static MethodBase? TargetMethod()
			{
				Type type = AccessTools.TypeByName("MainMenuScreen");
				if (!(type == null))
				{
					return AccessTools.Method(type, "Initialize", (Type[])null, (Type[])null);
				}
				return null;
			}

			private static void Postfix(MonoBehaviour __instance)
			{
				WatchForMainMenu(__instance);
			}
		}

		private const string ExtractingMessage = "Extracting MT1 contents...";

		private static Font? _font;

		private static bool _fontResolved;

		private static GameObject? _extractRoot;

		private static bool _extractAttached;

		private static GameObject? _sceneLabel;

		private static Behaviour? _sceneLocalize;

		private static bool _sceneLogged;

		private static bool _menuShown;

		private static GameObject? _menuRoot;

		private static float _menuHideAt;

		internal static void ShowExtraction()
		{
			ShowOnFlame();
		}

		internal static void ShowOnFlame()
		{
			try
			{
				Component val = LoadingScreenInstance();
				if (!((Object)(object)val == (Object)null))
				{
					EnsureFlamePlate(val);
				}
			}
			catch (Exception ex)
			{
				Plugin.LogSource.LogError((object)("Extraction notice failed: " + ex.Message));
			}
		}

		internal static void HideExtraction()
		{
			if ((Object)(object)_sceneLabel != (Object)null)
			{
				_sceneLabel.SetActive(false);
				_sceneLabel = null;
			}
			if ((Object)(object)_sceneLocalize != (Object)null)
			{
				_sceneLocalize.enabled = true;
				_sceneLocalize = null;
			}
			if ((Object)(object)_extractRoot != (Object)null)
			{
				Object.Destroy((Object)(object)_extractRoot);
			}
			_extractRoot = null;
			_extractAttached = false;
		}

		internal static void WatchForMainMenu(MonoBehaviour host)
		{
			if (!((Object)(object)host == (Object)null) && !_menuShown)
			{
				host.StartCoroutine(WaitForMainMenu());
			}
		}

		internal static void Tick()
		{
			if (MusicInstaller.ExtractionRunning)
			{
				ShowExtraction();
				return;
			}
			HideExtraction();
			if (!_menuShown && MusicInstaller.ReadyToReport && MenuIsReady())
			{
				ShowMenuNotice(MusicInstaller.MenuMessage());
			}
			if ((Object)(object)_menuRoot != (Object)null && Time.unscaledTime >= _menuHideAt)
			{
				Object.Destroy((Object)(object)_menuRoot);
				_menuRoot = null;
			}
		}

		private static IEnumerator WaitForMainMenu()
		{
			float waited = 0f;
			while (waited < 90f && !_menuShown)
			{
				if (MusicInstaller.ReadyToReport && MenuIsReady())
				{
					ShowMenuNotice(MusicInstaller.MenuMessage());
					yield break;
				}
				waited += Time.unscaledDeltaTime;
				yield return null;
			}
			if (!_menuShown)
			{
				Plugin.LogSource.LogInfo((object)"Main menu notice was not shown.");
			}
		}

		private static bool MenuIsReady()
		{
			if (LoadingDisplayed())
			{
				return false;
			}
			return (Object)(object)FindMainMenu() != (Object)null;
		}

		private static void ShowMenuNotice(string message)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			if (_menuShown)
			{
				return;
			}
			_menuShown = true;
			try
			{
				if (TryShowMusicToast(message))
				{
					Plugin.LogSource.LogInfo((object)("Main menu notice: " + message));
					return;
				}
				GameObject val = CreateNotice(message, bottomRight: false);
				if (!((Object)(object)val == (Object)null))
				{
					Transform val2 = val.transform.Find("Plate");
					Component val3 = FindMainMenu();
					Canvas val4 = (((Object)(object)val3 == (Object)null) ? null : val3.GetComponentInParent<Canvas>());
					if ((Object)(object)val2 != (Object)null && (Object)(object)val4 != (Object)null)
					{
						val2.SetParent(((Component)val4).transform, false);
						val2.SetAsLastSibling();
						Place((RectTransform)val2, bottomRight: false, screenPixels: false);
						Object.Destroy((Object)(object)val);
						_menuRoot = ((Component)val2).gameObject;
					}
					else
					{
						Object.DontDestroyOnLoad((Object)(object)val);
						_menuRoot = val;
					}
					_menuHideAt = Time.unscaledTime + 4.2f;
					Plugin.LogSource.LogInfo((object)("Main menu notice: " + message));
				}
			}
			catch (Exception ex)
			{
				Plugin.LogSource.LogError((object)("Main menu notice failed: " + ex.Message));
			}
		}

		private static void EnsureFlamePlate(Component screen)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			Canvas componentInParent = screen.GetComponentInParent<Canvas>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return;
			}
			if (_extractAttached && (Object)(object)_extractRoot != (Object)null)
			{
				_extractRoot.transform.SetAsLastSibling();
				return;
			}
			GameObject val = CreateNotice("Extracting MT1 contents...", bottomRight: true);
			Transform val2 = (((Object)(object)val == (Object)null) ? null : val.transform.Find("Plate"));
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
			{
				val2.SetParent(((Component)componentInParent).transform, false);
				val2.SetAsLastSibling();
				Place((RectTransform)val2, bottomRight: true, screenPixels: false);
				Canvas obj = ((Component)val2).gameObject.AddComponent<Canvas>();
				obj.overrideSorting = true;
				obj.sortingOrder = 5000;
				Object.Destroy((Object)(object)val);
				_extractRoot = ((Component)val2).gameObject;
				_extractAttached = true;
				if (!_sceneLogged)
				{
					_sceneLogged = true;
					Plugin.LogSource.LogInfo((object)"Extracting MT1 contents...");
				}
			}
		}

		private static bool TryShowMusicToast(string message)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			Type type = AccessTools.TypeByName("MusicNotificationHandler");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "ShowContent", (Type[])null, (Type[])null));
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "notificationUI"));
			if (type == null || methodInfo == null || fieldInfo == null)
			{
				return false;
			}
			Object[] array = Resources.FindObjectsOfTypeAll(type);
			foreach (Object obj in array)
			{
				Component val = (Component)(object)((obj is Component) ? obj : null);
				if (val == null)
				{
					continue;
				}
				Scene scene = val.gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && val.gameObject.activeInHierarchy)
				{
					try
					{
						methodInfo.Invoke(val, new object[1] { message });
					}
					catch (Exception ex)
					{
						Plugin.LogSource.LogError((object)("Music toast failed: " + ex.GetBaseException().Message));
						continue;
					}
					object? value = fieldInfo.GetValue(val);
					Component val2 = (Component)((value is Component) ? value : null);
					if (val2 != null && val2.gameObject.activeInHierarchy)
					{
						return true;
					}
				}
			}
			return false;
		}

		private static GameObject? CreateNotice(string message, bool bottomRight)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: 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)
			Font val = ResolveFont();
			Type type = AccessTools.TypeByName("UnityEngine.UI.Text");
			if ((Object)(object)val == (Object)null || type == null)
			{
				Plugin.LogSource.LogError((object)"Cannot draw a notice. UI text is unavailable.");
				return null;
			}
			GameObject val2 = new GameObject(bottomRight ? "ReminiscenceExtractNotice" : "ReminiscenceMenuNotice");
			Canvas obj = val2.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 5000;
			GameObject val3 = new GameObject("Plate");
			val3.transform.SetParent(val2.transform, false);
			Place(val3.AddComponent<RectTransform>(), bottomRight, screenPixels: true);
			val3.AddComponent<CanvasGroup>();
			Type type2 = AccessTools.TypeByName("UnityEngine.UI.Image");
			if (type2 != null)
			{
				Component target = val3.AddComponent(type2);
				SetProperty(target, "color", (object)new Color(0.05f, 0.03f, 0.02f, 0.92f));
				SetProperty(target, "raycastTarget", false);
			}
			GameObject val4 = new GameObject("Label");
			val4.transform.SetParent(val3.transform, false);
			RectTransform obj2 = val4.AddComponent<RectTransform>();
			obj2.anchorMin = Vector2.zero;
			obj2.anchorMax = Vector2.one;
			obj2.offsetMin = new Vector2(18f, 6f);
			obj2.offsetMax = new Vector2(-18f, -6f);
			Component target2 = val4.AddComponent(type);
			SetProperty(target2, "font", val);
			SetProperty(target2, "fontSize", NoticeFontSize());
			SetProperty(target2, "color", Color.white);
			SetProperty(target2, "raycastTarget", false);
			SetProperty(target2, "text", message);
			SetEnum(target2, "alignment", bottomRight ? "MiddleRight" : "MiddleCenter");
			SetEnum(target2, "horizontalOverflow", "Overflow");
			SetEnum(target2, "verticalOverflow", "Overflow");
			return val2;
		}

		private static void Place(RectTransform rt, bool bottomRight, bool screenPixels)
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (bottomRight)
			{
				rt.anchorMin = new Vector2(1f, 0f);
				rt.anchorMax = new Vector2(1f, 0f);
				rt.pivot = new Vector2(1f, 0f);
				rt.sizeDelta = (screenPixels ? new Vector2(PixelWidth() * 0.4f, PixelHeight() * 0.055f) : new Vector2(680f, 64f));
				rt.anchoredPosition = (screenPixels ? new Vector2((0f - PixelWidth()) * 0.09f, PixelHeight() * 0.04f) : new Vector2(-170f, 36f));
			}
			else
			{
				rt.anchorMin = new Vector2(0.5f, 1f);
				rt.anchorMax = new Vector2(0.5f, 1f);
				rt.pivot = new Vector2(0.5f, 1f);
				rt.sizeDelta = (screenPixels ? new Vector2(PixelWidth() * 0.46f, PixelHeight() * 0.05f) : new Vector2(820f, 58f));
				rt.anchoredPosition = (screenPixels ? new Vector2(0f, (0f - PixelHeight()) * 0.1f) : new Vector2(0f, -120f));
			}
		}

		private static int NoticeFontSize()
		{
			return Mathf.Clamp(Mathf.RoundToInt(PixelHeight() * 0.028f), 22, 48);
		}

		private static float PixelWidth()
		{
			if (Screen.width <= 100)
			{
				return 1920f;
			}
			return Screen.width;
		}

		private static float PixelHeight()
		{
			if (Screen.height <= 100)
			{
				return 1080f;
			}
			return Screen.height;
		}

		private static Font? ResolveFont()
		{
			if (_fontResolved)
			{
				return _font;
			}
			_fontResolved = true;
			_font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf") ?? Resources.GetBuiltinResource<Font>("Arial.ttf");
			if ((Object)(object)_font == (Object)null)
			{
				try
				{
					_font = Font.CreateDynamicFontFromOSFont(new string[3] { "Arial", "Liberation Sans", "DejaVu Sans" }, 32);
				}
				catch (Exception ex)
				{
					Plugin.LogSource.LogError((object)("Notice font lookup failed: " + ex.Message));
				}
			}
			if ((Object)(object)_font == (Object)null)
			{
				Plugin.LogSource.LogError((object)"No font available for the Reminiscence notice.");
			}
			return _font;
		}

		private static Component? LoadingScreenInstance()
		{
			Type type = AccessTools.TypeByName("ShinyShoe.Loading.LoadingScreen");
			object? obj = ((type == null) ? null : AccessTools.Field(type, "_loadingScreenInst"))?.GetValue(null);
			return (Component?)((obj is Component) ? obj : null);
		}

		private static bool LoadingDisplayed()
		{
			Type type = AccessTools.TypeByName("ShinyShoe.Loading.LoadingScreen");
			object obj = ((type == null) ? null : AccessTools.Method(type, "IsDisplaying", (Type[])null, (Type[])null))?.Invoke(null, null);
			if (obj is bool)
			{
				return (bool)obj;
			}
			return false;
		}

		private static Component? FindMainMenu()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			Type type = AccessTools.TypeByName("MainMenuScreen");
			if (type == null)
			{
				return null;
			}
			Object[] array = Resources.FindObjectsOfTypeAll(type);
			foreach (Object obj in array)
			{
				Component val = (Component)(object)((obj is Component) ? obj : null);
				if (val != null)
				{
					Scene scene = val.gameObject.scene;
					if (((Scene)(ref scene)).IsValid() && val.gameObject.activeInHierarchy)
					{
						return val;
					}
				}
			}
			return null;
		}

		private static void SetEnum(object target, string property, string name)
		{
			PropertyInfo propertyInfo = AccessTools.Property(target.GetType(), property);
			if (propertyInfo == null || !propertyInfo.PropertyType.IsEnum)
			{
				return;
			}
			try
			{
				propertyInfo.SetValue(target, Enum.Parse(propertyInfo.PropertyType, name));
			}
			catch (ArgumentException)
			{
			}
		}

		private static void SetProperty(object target, string property, object? value)
		{
			PropertyInfo propertyInfo = AccessTools.Property(target.GetType(), property);
			if (propertyInfo == null || !propertyInfo.CanWrite)
			{
				return;
			}
			try
			{
				propertyInfo.SetValue(target, value);
			}
			catch (Exception)
			{
			}
		}
	}
	internal static class TldInstall
	{
		public static bool Present(string mt1)
		{
			if (string.IsNullOrWhiteSpace(mt1))
			{
				return false;
			}
			string path = Path.Combine(mt1, "MonsterTrain_Data", "StreamingAssets", "aa", "StandaloneWindows64", "DLC", "DLC_1");
			if (!Directory.Exists(path))
			{
				return false;
			}
			return Directory.EnumerateFiles(path, "*.bundle").Any();
		}
	}
	internal static class WavPcm
	{
		public static AudioClip ToClip(string path, string name)
		{
			using FileStream fileStream = File.OpenRead(path);
			using BinaryReader binaryReader = new BinaryReader(fileStream);
			if (ReadId(binaryReader) != "RIFF")
			{
				throw new InvalidDataException(path + " is not a RIFF wav");
			}
			binaryReader.ReadInt32();
			if (ReadId(binaryReader) != "WAVE")
			{
				throw new InvalidDataException(path + " is not a WAVE file");
			}
			short num = 0;
			short num2 = 0;
			int num3 = 0;
			byte[] array = null;
			while (fileStream.Position + 8 <= fileStream.Length)
			{
				string text = ReadId(binaryReader);
				int num4 = binaryReader.ReadInt32();
				if (text == "fmt ")
				{
					short num5 = binaryReader.ReadInt16();
					num = binaryReader.ReadInt16();
					num3 = binaryReader.ReadInt32();
					binaryReader.ReadInt32();
					binaryReader.ReadInt16();
					num2 = binaryReader.ReadInt16();
					int num6 = 16;
					if (num4 > num6)
					{
						binaryReader.ReadBytes(num4 - num6);
					}
					if (num5 != 1 || num2 != 16)
					{
						throw new InvalidDataException(path + " is not 16-bit PCM");
					}
				}
				else if (text == "data")
				{
					array = binaryReader.ReadBytes(num4);
				}
				else
				{
					binaryReader.ReadBytes(num4);
				}
				if ((num4 & 1) == 1 && fileStream.Position < fileStream.Length)
				{
					binaryReader.ReadByte();
				}
			}
			if (array == null || num < 1 || num3 < 1)
			{
				throw new InvalidDataException(path + " has no PCM data");
			}
			int num7 = array.Length / (num * 2);
			float[] array2 = new float[num7 * num];
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i] = (float)BitConverter.ToInt16(array, i * 2) / 32768f;
			}
			AudioClip obj = AudioClip.Create(name, num7, (int)num, num3, false);
			if (!obj.SetData(array2, 0))
			{
				throw new InvalidDataException("Unity rejected the PCM for " + name);
			}
			return obj;
		}

		private static string ReadId(BinaryReader reader)
		{
			return new string(reader.ReadChars(4));
		}
	}
}