Decompiled source of VioletSpace21Deluxe v1.0.1

VioletSpace21Deluxe.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace VioletSpace21Deluxe;

[BepInPlugin("VioletSpace21Deluxe", "VioletSpace21Deluxe", "1.0.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class VioletSpace21DeluxePlugin : BaseUnityPlugin
{
	public const string PLUGIN_GUID = "VioletSpace21Deluxe";

	public const string PLUGIN_NAME = "VioletSpace21Deluxe";

	public const string PLUGIN_VERSION = "1.0.1";

	public static readonly Color ColorOrangeViolet = new Color(0.29f, 0.012f, 0.651f, 1f);

	public static readonly Color ColorRedViolet = new Color(0.263f, 0.055f, 0.541f, 1f);

	public static readonly Color ColorGreenViolet = new Color(0.373f, 0.082f, 0.749f, 1f);

	public static readonly Color ColorButtonIdle = new Color(0.29f, 0.012f, 0.651f, 1f);

	public static readonly Color ColorButtonHover = new Color(0.373f, 0.082f, 0.749f, 1f);

	public static readonly Color ColorButtonFlash = new Color(0.55f, 0.15f, 0.95f, 1f);

	public static readonly Color ColorHealthPlus = new Color(0.769f, 0.302f, 1f, 1f);

	public static readonly Color ColorHealthNumber = new Color(0.624f, 0.451f, 1f, 1f);

	public static readonly Color ColorStaminaZap = new Color(0.769f, 0.302f, 1f, 1f);

	public static readonly Color ColorStaminaNumber = new Color(0.596f, 0.259f, 0.961f, 1f);

	private static Material _selectionBoxMaterialInstance = null;

	public static readonly Color ColorPurpleLight = new Color(0.58f, 0.12f, 0.98f, 1f);

	public static readonly Color ColorPurpleGlow = new Color(0.7f, 0.18f, 1f, 1f);

	public static readonly Color ColorAmbientNight = new Color(0.12f, 0.035f, 0.22f, 1f);

	public static readonly Color ColorFogNight = new Color(0.08f, 0.02f, 0.16f, 1f);

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

	private float _uiScanTimer;

	private float _lightScanTimer;

	private float _initialEnforceTimer;

	private int _initialEnforceCount;

	public static VioletSpace21DeluxePlugin Instance { get; private set; }

	public static ManualLogSource Log { get; private set; }

	public static AudioClip MainMenuClip { get; private set; }

	public static AudioClip LobbyMenuClip { get; private set; }

	public static Texture2D CustomLogoTexture { get; private set; }

	public static Sprite CustomLogoSprite { get; private set; }

	private void Awake()
	{
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		Log.LogInfo((object)string.Format("{0} v{1} initializing...", "VioletSpace21Deluxe", "1.0.1"));
		EnsureAndSyncBundledConfigs();
		EnforceInMemoryPluginConfigurations();
		SceneManager.sceneLoaded += OnSceneLoaded;
		SceneManager.activeSceneChanged += OnActiveSceneChanged;
		LoadCustomMusic();
		LoadCustomLogo();
		ApplyHarmonyPatchesSafely();
		Log.LogInfo((object)string.Format("{0} successfully initialized!", "VioletSpace21Deluxe"));
	}

	private void EnsureAndSyncBundledConfigs()
	{
		try
		{
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			string text = Path.Combine(directoryName, "configs");
			string configPath = Paths.ConfigPath;
			if (!Directory.Exists(configPath))
			{
				Directory.CreateDirectory(configPath);
			}
			string[] array = null;
			if (Directory.Exists(text))
			{
				array = Directory.GetFiles(text, "*.cfg");
			}
			else
			{
				array = Directory.GetFiles(directoryName, "*.cfg");
				if (array != null && array.Length > 0)
				{
					try
					{
						Directory.CreateDirectory(text);
						string[] array2 = array;
						foreach (string text2 in array2)
						{
							string text3 = Path.Combine(text, Path.GetFileName(text2));
							if (!File.Exists(text3))
							{
								File.Copy(text2, text3, overwrite: false);
							}
						}
						Log.LogInfo((object)$"[ConfigSync] Restored {array.Length} config(s) from plugin root into '{text}'");
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)$"[ConfigSync] Folder restore warning: {ex.Message}");
					}
				}
			}
			if (array == null || array.Length <= 0)
			{
				return;
			}
			string[] array3 = array;
			foreach (string text4 in array3)
			{
				string fileName = Path.GetFileName(text4);
				string text5 = Path.Combine(configPath, fileName);
				if (!File.Exists(text5))
				{
					File.Copy(text4, text5, overwrite: true);
					Log.LogInfo((object)$"[ConfigSync] Seeded missing config: {fileName} -> {text5}");
				}
				else
				{
					SyncConfigValues(text5, fileName);
				}
			}
		}
		catch (Exception ex2)
		{
			Log.LogError((object)$"[ConfigSync] Exception during configuration sync: {ex2.Message}");
		}
	}

	private void SyncConfigValues(string configPath, string fileName)
	{
		try
		{
			string text = File.ReadAllText(configPath);
			bool flag = false;
			if (fileName.Equals("Swaggies.PlayerTweaks.cfg", StringComparison.OrdinalIgnoreCase))
			{
				flag |= EnsureConfigLine(ref text, "Plus Sign Color", "#c44dff");
				flag |= EnsureConfigLine(ref text, "Health Color", "#9f73ff");
				flag |= EnsureConfigLine(ref text, "Max Health Color", "#9f73ff");
				flag |= EnsureConfigLine(ref text, "Use Same Color for Max and Current HP", "false");
				flag |= EnsureConfigLine(ref text, "Use Plus Sign as Health Bar", "true");
				flag |= EnsureConfigLine(ref text, "Zap Sign Color", "#c44dff");
				flag |= EnsureConfigLine(ref text, "Stamina Color", "#9842f5");
				flag |= EnsureConfigLine(ref text, "Max Stamina Color", "#9842f5");
				flag |= EnsureConfigLine(ref text, "Use Same Color for Max and Current Stamina", "false");
				flag |= EnsureConfigLine(ref text, "Use Zap Sign as Stamina Bar", "true");
			}
			else if (fileName.Equals("local.repo.playervieweffects.cfg", StringComparison.OrdinalIgnoreCase))
			{
				flag |= EnsureConfigLine(ref text, "Multiplier", "3.02");
				flag |= EnsureConfigLine(ref text, "Bloom", "true");
				flag |= EnsureConfigLine(ref text, "Vignette", "true");
				flag |= EnsureConfigLine(ref text, "ColorGrading", "false");
				flag |= EnsureConfigLine(ref text, "LensDistortion", "true");
				flag |= EnsureConfigLine(ref text, "ChromaticAberration", "false");
				flag |= EnsureConfigLine(ref text, "Distance", "Default");
				flag |= EnsureConfigLine(ref text, "EnableHotkey", "false");
				flag |= EnsureConfigLine(ref text, "ModEnabled", "true");
			}
			else if (fileName.Equals("Omniscye.SnowEverywhere.cfg", StringComparison.OrdinalIgnoreCase))
			{
				flag |= EnsureConfigLine(ref text, "Enabled", "true");
				flag |= EnsureConfigLine(ref text, "StickToCamera", "true");
				flag |= EnsureConfigLine(ref text, "UseUnscaledTime", "true");
				flag |= EnsureConfigLine(ref text, "FlakesPerSecond", "907");
				flag |= EnsureConfigLine(ref text, "FallSpeed", "12.04");
				flag |= EnsureConfigLine(ref text, "FlakeSize", "0.12");
				flag |= EnsureConfigLine(ref text, "WindX", "12.53");
				flag |= EnsureConfigLine(ref text, "WindZ", "0.39");
				flag |= EnsureConfigLine(ref text, "MaxParticles", "169349");
				flag |= EnsureConfigLine(ref text, "SpawnBoxHalfExtent", "31.1");
				flag |= EnsureConfigLine(ref text, "OnlyInMenuLobby", "false");
				flag |= EnsureConfigLine(ref text, "UseCustomTexture", "true");
				flag |= EnsureConfigLine(ref text, "CustomTextureName", "snow.png");
			}
			else if (fileName.Equals("nickklmao.repoconfig.cfg", StringComparison.OrdinalIgnoreCase))
			{
				flag |= EnsureConfigLine(ref text, "Show In Game", "true");
			}
			else if (fileName.Equals("me.loaforc.soundapi.cfg", StringComparison.OrdinalIgnoreCase))
			{
				flag |= EnsureConfigLine(ref text, "AudioClipSpoofing", "true");
				flag |= EnsureConfigLine(ref text, "PreferredBackend", "NativeBackend");
				flag |= EnsureConfigLine(ref text, "GenerateReports", "true");
				flag |= EnsureConfigLine(ref text, "SoundReplacementLoader", "true");
				flag |= EnsureConfigLine(ref text, "SoundReplacementHandler", "true");
				flag |= EnsureConfigLine(ref text, "MatchStrings", "true");
			}
			if (flag)
			{
				File.WriteAllText(configPath, text);
				Log.LogInfo((object)$"[ConfigSync] Successfully synchronized custom values into {fileName}");
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)$"[ConfigSync] Failed to sync config values for {fileName}: {ex.Message}");
		}
	}

	private static bool EnsureConfigLine(ref string text, string key, string expectedValue)
	{
		string pattern = "^\\s*" + Regex.Escape(key) + "\\s*=.*$";
		Regex regex = new Regex(pattern, RegexOptions.Multiline);
		string text2 = $"{key} = {expectedValue}";
		if (regex.IsMatch(text))
		{
			Match match = regex.Match(text);
			if (match.Value.Trim() != text2.Trim())
			{
				text = regex.Replace(text, text2, 1);
				return true;
			}
			return false;
		}
		text = text + Environment.NewLine + text2;
		return true;
	}

	public static void EnforceInMemoryPluginConfigurations()
	{
		try
		{
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				try
				{
					if (value == null)
					{
						continue;
					}
					BaseUnityPlugin instance = value.Instance;
					if (instance != null)
					{
						ConfigFile config = instance.Config;
						if (config != null)
						{
							config.Reload();
						}
					}
				}
				catch
				{
				}
			}
		}
		catch (Exception ex)
		{
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogWarning((object)$"[ConfigEnforce] Chainloader plugin config reload: {ex.Message}");
			}
		}
		try
		{
			EnforcePlayerTweaksMemory();
		}
		catch (Exception ex2)
		{
			ManualLogSource log2 = Log;
			if (log2 != null)
			{
				log2.LogWarning((object)$"[ConfigEnforce] PlayerTweaks memory enforcement: {ex2.Message}");
			}
		}
		try
		{
			EnforceShaderEditMemory();
		}
		catch (Exception ex3)
		{
			ManualLogSource log3 = Log;
			if (log3 != null)
			{
				log3.LogWarning((object)$"[ConfigEnforce] ShaderEdit memory enforcement: {ex3.Message}");
			}
		}
		try
		{
			EnforceSnowEverywhereMemory();
		}
		catch (Exception ex4)
		{
			ManualLogSource log4 = Log;
			if (log4 != null)
			{
				log4.LogWarning((object)$"[ConfigEnforce] SnowEverywhere memory enforcement: {ex4.Message}");
			}
		}
	}

	private static void EnforcePlayerTweaksMemory()
	{
		Type type = FindType("RepoHUDTweaks.Plugin");
		if (type != null)
		{
			SetStaticConfigEntryValue(type, "HealthPlusSignColor", "#c44dff");
			SetStaticConfigEntryValue(type, "HealthColor", "#9f73ff");
			SetStaticConfigEntryValue(type, "HealthMaxColor", "#9f73ff");
			SetStaticConfigEntryValue(type, "HealthMaxMatchSlash", false);
			SetStaticConfigEntryValue(type, "HealthPlusSignAsHealthBar", true);
			SetStaticConfigEntryValue(type, "StaminaZapSignColor", "#c44dff");
			SetStaticConfigEntryValue(type, "StaminaColor", "#9842f5");
			SetStaticConfigEntryValue(type, "StaminaMaxColor", "#9842f5");
			SetStaticConfigEntryValue(type, "StaminaMaxMatchSlash", false);
			SetStaticConfigEntryValue(type, "StaminaZapSignAsStaminaBar", true);
		}
	}

	private static void EnforceShaderEditMemory()
	{
		Type type = FindType("ShaderEdit.Plugin");
		if (!(type != null))
		{
			return;
		}
		object value = Traverse.Create(type).Field("instance").GetValue();
		if (value == null)
		{
			return;
		}
		object value2 = Traverse.Create(value).Field("settings").GetValue();
		if (value2 != null)
		{
			Traverse val = Traverse.Create(value2);
			SetConfigEntryBoxed(val.Property("Brightness", (object[])null).GetValue(), 3.02f);
			SetConfigEntryBoxed(val.Property("Fog", (object[])null).GetValue(), "Default");
			SetConfigEntryBoxed(val.Property("EnableHotkey", (object[])null).GetValue(), false);
			SetConfigEntryBoxed(val.Property("Enabled", (object[])null).GetValue(), true);
			Dictionary<string, ConfigEntry<bool>> value3 = val.Field<Dictionary<string, ConfigEntry<bool>>>("effects").Value;
			if (value3 != null)
			{
				if (value3.ContainsKey("Bloom"))
				{
					value3["Bloom"].Value = true;
				}
				if (value3.ContainsKey("Vignette"))
				{
					value3["Vignette"].Value = true;
				}
				if (value3.ContainsKey("ColorGrading"))
				{
					value3["ColorGrading"].Value = false;
				}
				if (value3.ContainsKey("LensDistortion"))
				{
					value3["LensDistortion"].Value = true;
				}
				if (value3.ContainsKey("ChromaticAberration"))
				{
					value3["ChromaticAberration"].Value = false;
				}
			}
		}
		Traverse.Create(value).Method("OnSettingChanged", Array.Empty<object>()).GetValue();
	}

	private static void EnforceSnowEverywhereMemory()
	{
		Type type = FindType("Omniscye.SnowEverywhere.SnowEverywhere");
		if (!(type != null))
		{
			return;
		}
		object value = Traverse.Create(type).Property("Instance", (object[])null).GetValue();
		if (value != null)
		{
			Traverse val = Traverse.Create(value);
			SetConfigEntryBoxed(val.Field("_flakesPerSecond").GetValue(), 907f);
			SetConfigEntryBoxed(val.Field("_fallSpeed").GetValue(), 12.04f);
			SetConfigEntryBoxed(val.Field("_flakeSize").GetValue(), 0.12f);
			SetConfigEntryBoxed(val.Field("_windX").GetValue(), 12.53f);
			SetConfigEntryBoxed(val.Field("_windZ").GetValue(), 0.39f);
			SetConfigEntryBoxed(val.Field("_maxParticles").GetValue(), 169349);
			SetConfigEntryBoxed(val.Field("_spawnBoxHalfExtent").GetValue(), 31.1f);
			SetConfigEntryBoxed(val.Field("_onlyInMenuLobby").GetValue(), false);
			SetConfigEntryBoxed(val.Field("_useCustomTexture").GetValue(), true);
			SetConfigEntryBoxed(val.Field("_customTextureName").GetValue(), "snow.png");
			object value2 = val.Field("_controller").GetValue();
			if (value2 != null)
			{
				Traverse.Create(value2).Method("SetEmissionRate", new object[1] { 907f }).GetValue();
			}
		}
	}

	private static Type FindType(string fullName)
	{
		Type type = Type.GetType(fullName);
		if (type != null)
		{
			return type;
		}
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			try
			{
				type = assembly.GetType(fullName);
				if (type != null)
				{
					return type;
				}
			}
			catch
			{
			}
		}
		return null;
	}

	private static void SetStaticConfigEntryValue(Type type, string fieldName, object value)
	{
		try
		{
			object value2 = Traverse.Create(type).Field(fieldName).GetValue();
			SetConfigEntryBoxed(value2, value);
		}
		catch
		{
		}
	}

	private static void SetConfigEntryBoxed(object configEntry, object value)
	{
		if (configEntry == null)
		{
			return;
		}
		try
		{
			Traverse.Create(configEntry).Property("Value", (object[])null).SetValue(value);
		}
		catch
		{
		}
	}

	private void ApplyHarmonyPatchesSafely()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		Harmony val = new Harmony("VioletSpace21Deluxe");
		Type[] array = new Type[18]
		{
			typeof(Patch_RunManager_Awake),
			typeof(Patch_RunManager_ChangeLevel),
			typeof(Patch_ConstantMusic_Setup),
			typeof(Patch_TextMeshProUGUI_Awake),
			typeof(Patch_TextMeshProUGUI_GenerateTextMesh),
			typeof(Patch_TMP_Text_SetText),
			typeof(Patch_MenuSelectionBox_Awake),
			typeof(Patch_MenuSelectionBox_Update),
			typeof(Patch_MenuButtonColor_Start),
			typeof(Patch_MenuLogoHalloweenOverlay_Awake),
			typeof(Patch_PropLight_Start),
			typeof(Patch_PropLightEmission_Awake),
			typeof(Patch_SemiLaser_Start),
			typeof(Patch_SemiLaser_Update),
			typeof(Patch_TruckHalloweenLighting_LightColorsSet),
			typeof(Patch_EnvironmentDirector_Update),
			typeof(Patch_HealthUI_EnforcePurple),
			typeof(Patch_EnergyUI_EnforcePurple)
		};
		Type[] array2 = array;
		foreach (Type type in array2)
		{
			try
			{
				val.CreateClassProcessor(type).Patch();
				Log.LogDebug((object)$"Applied patch: {type.Name}");
			}
			catch (Exception ex)
			{
				Log.LogError((object)$"Error applying patch {type.Name}: {ex.Message}");
			}
		}
	}

	private void Update()
	{
		_uiScanTimer += Time.deltaTime;
		if (_uiScanTimer >= 0.2f)
		{
			_uiScanTimer = 0f;
			ProcessAllUI();
			ApplyCustomLogo();
		}
		_lightScanTimer += Time.deltaTime;
		if (_lightScanTimer >= 0.6f)
		{
			_lightScanTimer = 0f;
			ProcessSceneLightsAndEmissions();
			ConfigureMenuAtmosphere();
		}
		if (_initialEnforceCount < 5)
		{
			_initialEnforceTimer += Time.deltaTime;
			if (_initialEnforceTimer >= 1f)
			{
				_initialEnforceTimer = 0f;
				_initialEnforceCount++;
				EnforceInMemoryPluginConfigurations();
			}
		}
		EnforceMenuMusic();
	}

	private void OnDestroy()
	{
		SceneManager.sceneLoaded -= OnSceneLoaded;
		SceneManager.activeSceneChanged -= OnActiveSceneChanged;
	}

	private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		Log.LogInfo((object)$"Scene loaded: {((Scene)(ref scene)).name}. Running visual update pass...");
		ProcessedLights.Clear();
		EnforceInMemoryPluginConfigurations();
		ProcessAllUI();
		ApplyCustomLogo();
		ProcessSceneLightsAndEmissions();
		ConfigureMenuAtmosphere();
	}

	private void OnActiveSceneChanged(Scene oldScene, Scene newScene)
	{
		ProcessedLights.Clear();
		EnforceInMemoryPluginConfigurations();
		ProcessAllUI();
		ApplyCustomLogo();
		ProcessSceneLightsAndEmissions();
		ConfigureMenuAtmosphere();
	}

	private void LoadCustomLogo()
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Expected O, but got Unknown
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		string text = Path.Combine(directoryName, "logo.png");
		if (!File.Exists(text))
		{
			Log.LogWarning((object)$"Custom logo file not found at: {text}");
			return;
		}
		try
		{
			byte[] array = File.ReadAllBytes(text);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (ImageConversion.LoadImage(val, array))
			{
				((Object)val).name = "VioletSpace21Deluxe_Logo";
				((Texture)val).wrapMode = (TextureWrapMode)1;
				((Texture)val).filterMode = (FilterMode)1;
				CustomLogoTexture = val;
				CustomLogoSprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				((Object)CustomLogoSprite).name = "VioletSpace21Deluxe_LogoSprite";
				Log.LogInfo((object)$"Successfully loaded custom logo ({((Texture)val).width}x{((Texture)val).height})!");
			}
		}
		catch (Exception ex)
		{
			Log.LogError((object)$"Error loading logo from {text}: {ex.Message}");
		}
	}

	public static void ApplyCustomLogo()
	{
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)CustomLogoTexture == (Object)null || !SemiFunc.IsMainMenu())
		{
			return;
		}
		GameObject val = GameObject.Find("Logo");
		if ((Object)(object)val == (Object)null)
		{
			MenuPageMain val2 = Object.FindAnyObjectByType<MenuPageMain>();
			if ((Object)(object)val2 != (Object)null)
			{
				Transform val3 = ((Component)val2).transform.Find("Logo") ?? ((Component)val2).transform.Find("Left/Logo") ?? ((Component)val2).transform.Find("Menu/Logo");
				if ((Object)(object)val3 != (Object)null)
				{
					val = ((Component)val3).gameObject;
				}
			}
		}
		if ((Object)(object)val != (Object)null)
		{
			RawImage component = val.GetComponent<RawImage>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.texture != (Object)(object)CustomLogoTexture)
			{
				component.texture = (Texture)(object)CustomLogoTexture;
				((Graphic)component).color = Color.white;
			}
			Image component2 = val.GetComponent<Image>();
			if ((Object)(object)component2 != (Object)null && (Object)(object)component2.sprite != (Object)(object)CustomLogoSprite)
			{
				component2.sprite = CustomLogoSprite;
				((Graphic)component2).color = Color.white;
			}
			Transform val4 = val.transform.Find("Halloween Overlay");
			if ((Object)(object)val4 != (Object)null && ((Component)val4).gameObject.activeSelf)
			{
				((Component)val4).gameObject.SetActive(false);
			}
		}
	}

	private void LoadCustomMusic()
	{
		string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		string text = Path.Combine(directoryName, "music");
		string text2 = Path.Combine(directoryName, "replacers");
		string text3 = Path.Combine(directoryName, "main-menu.ogg");
		string text4 = Path.Combine(directoryName, "lobby-menu.ogg");
		string text5 = Path.Combine(directoryName, "menu_music.json");
		string text6 = Path.Combine(text, "main-menu.ogg");
		string text7 = Path.Combine(text, "lobby-menu.ogg");
		string text8 = Path.Combine(text2, "menu_music.json");
		try
		{
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			if (!Directory.Exists(text2))
			{
				Directory.CreateDirectory(text2);
			}
			if (File.Exists(text3) && !File.Exists(text6))
			{
				File.Copy(text3, text6, overwrite: true);
				Log.LogInfo((object)$"[MusicSync] Restored music file: {text6}");
			}
			if (File.Exists(text4) && !File.Exists(text7))
			{
				File.Copy(text4, text7, overwrite: true);
				Log.LogInfo((object)$"[MusicSync] Restored music file: {text7}");
			}
			if (File.Exists(text5) && !File.Exists(text8))
			{
				File.Copy(text5, text8, overwrite: true);
				Log.LogInfo((object)$"[MusicSync] Restored replacer config: {text8}");
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)$"Auto-heal directory structure warning: {ex.Message}");
		}
		if (!File.Exists(text6) && File.Exists(text3))
		{
			text6 = text3;
		}
		if (!File.Exists(text7) && File.Exists(text4))
		{
			text7 = text4;
		}
		Log.LogInfo((object)$"Loading music from: mainMenu='{text6}' (exists={File.Exists(text6)}), lobbyMenu='{text7}' (exists={File.Exists(text7)})");
		try
		{
			TryLoadViaSoundAPI(text6, text7);
		}
		catch (Exception ex2)
		{
			Log.LogWarning((object)$"loaforcsSoundAPI loader exception: {ex2.Message}");
		}
		if (File.Exists(text6))
		{
			((MonoBehaviour)this).StartCoroutine(LoadAudioClipWebRequest(text6, delegate(AudioClip clip)
			{
				MainMenuClip = clip;
				EnforceMenuMusic();
			}));
		}
		else
		{
			Log.LogWarning((object)$"Main menu music not found at {text6}");
		}
		if (File.Exists(text7))
		{
			((MonoBehaviour)this).StartCoroutine(LoadAudioClipWebRequest(text7, delegate(AudioClip clip)
			{
				LobbyMenuClip = clip;
				EnforceMenuMusic();
			}));
		}
		else
		{
			Log.LogWarning((object)$"Lobby menu music not found at {text7}");
		}
	}

	private bool TryLoadViaSoundAPI(string mainMenuPath, string lobbyMenuPath)
	{
		Type type = Type.GetType("loaforcsSoundAPI.SoundAPI, me.loaforc.soundapi");
		if (type == null)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				type = assembly.GetType("loaforcsSoundAPI.SoundAPI");
				if (type != null)
				{
					break;
				}
			}
		}
		if (type != null)
		{
			MethodInfo method = type.GetMethod("LoadAudioFileAsync", new Type[1] { typeof(string) });
			if (method != null)
			{
				bool result = false;
				if (File.Exists(mainMenuPath))
				{
					Task<AudioClip> task = (Task<AudioClip>)method.Invoke(null, new object[1] { mainMenuPath });
					task.ContinueWith(delegate(Task<AudioClip> t)
					{
						if (t.IsCompleted && !t.IsFaulted && (Object)(object)t.Result != (Object)null)
						{
							MainMenuClip = t.Result;
							Log.LogInfo((object)"Successfully loaded main-menu.ogg via loaforcsSoundAPI!");
							EnforceMenuMusic();
						}
					});
					result = true;
				}
				if (File.Exists(lobbyMenuPath))
				{
					Task<AudioClip> task2 = (Task<AudioClip>)method.Invoke(null, new object[1] { lobbyMenuPath });
					task2.ContinueWith(delegate(Task<AudioClip> t)
					{
						if (t.IsCompleted && !t.IsFaulted && (Object)(object)t.Result != (Object)null)
						{
							LobbyMenuClip = t.Result;
							Log.LogInfo((object)"Successfully loaded lobby-menu.ogg via loaforcsSoundAPI!");
							EnforceMenuMusic();
						}
					});
					result = true;
				}
				return result;
			}
		}
		return false;
	}

	private IEnumerator LoadAudioClipWebRequest(string filePath, Action<AudioClip> onLoaded)
	{
		string uri = "file://" + filePath.Replace("\\", "/");
		UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(uri, (AudioType)14);
		try
		{
			yield return uwr.SendWebRequest();
			if ((int)uwr.result == 1)
			{
				AudioClip content = DownloadHandlerAudioClip.GetContent(uwr);
				if ((Object)(object)content != (Object)null)
				{
					((Object)content).name = Path.GetFileNameWithoutExtension(filePath);
					onLoaded?.Invoke(content);
					Log.LogInfo((object)$"Successfully loaded audio clip '{((Object)content).name}' via UnityWebRequest!");
				}
			}
			else
			{
				Log.LogError((object)$"Failed to load audio from {filePath}: {uwr.error}");
			}
		}
		finally
		{
			((IDisposable)uwr)?.Dispose();
		}
	}

	public static void EnforceMenuMusic()
	{
		if ((Object)(object)RunManager.instance == (Object)null)
		{
			return;
		}
		bool flag = SemiFunc.IsMainMenu();
		bool flag2 = SemiFunc.RunIsLobbyMenu();
		if (flag && (Object)(object)MainMenuClip != (Object)null)
		{
			if ((Object)(object)RunManager.instance.levelMainMenu != (Object)null && (Object)(object)RunManager.instance.levelMainMenu.ConstantMusicPreset != (Object)null && (Object)(object)RunManager.instance.levelMainMenu.ConstantMusicPreset.clip != (Object)(object)MainMenuClip)
			{
				RunManager.instance.levelMainMenu.ConstantMusicPreset.clip = MainMenuClip;
				RunManager.instance.levelMainMenu.ConstantMusicPreset.volume = 1f;
			}
			if ((Object)(object)ConstantMusic.instance != (Object)null)
			{
				AudioSource component = ((Component)ConstantMusic.instance).GetComponent<AudioSource>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.clip != (Object)(object)MainMenuClip)
				{
					Traverse.Create((object)ConstantMusic.instance).Field<AudioClip>("clip").Value = MainMenuClip;
					component.clip = MainMenuClip;
					component.volume = 1f;
					component.Play();
				}
			}
		}
		else
		{
			if (!flag2 || !((Object)(object)LobbyMenuClip != (Object)null))
			{
				return;
			}
			if ((Object)(object)RunManager.instance.levelLobbyMenu != (Object)null && (Object)(object)RunManager.instance.levelLobbyMenu.ConstantMusicPreset != (Object)null && (Object)(object)RunManager.instance.levelLobbyMenu.ConstantMusicPreset.clip != (Object)(object)LobbyMenuClip)
			{
				RunManager.instance.levelLobbyMenu.ConstantMusicPreset.clip = LobbyMenuClip;
				RunManager.instance.levelLobbyMenu.ConstantMusicPreset.volume = 1f;
			}
			if ((Object)(object)ConstantMusic.instance != (Object)null)
			{
				AudioSource component2 = ((Component)ConstantMusic.instance).GetComponent<AudioSource>();
				if ((Object)(object)component2 != (Object)null && (Object)(object)component2.clip != (Object)(object)LobbyMenuClip)
				{
					Traverse.Create((object)ConstantMusic.instance).Field<AudioClip>("clip").Value = LobbyMenuClip;
					component2.clip = LobbyMenuClip;
					component2.volume = 1f;
					component2.Play();
				}
			}
		}
	}

	public static bool IsPlayerOrEnemy(GameObject go)
	{
		if ((Object)(object)go == (Object)null)
		{
			return false;
		}
		if ((Object)(object)go.GetComponentInParent<PlayerAvatar>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<PlayerAvatarVisuals>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<Enemy>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<EnemyParent>() != (Object)null)
		{
			return true;
		}
		Transform val = go.transform;
		while ((Object)(object)val != (Object)null)
		{
			string text = ((Object)val).name.ToLower();
			if (text.Contains("player") || text.Contains("enemy") || text.Contains("monster") || text.Contains("avatar") || text.Contains("ragdoll") || text.Contains("arm_") || text.Contains("hand_") || text.Contains("snatcher") || text.Contains("bowtie"))
			{
				return true;
			}
			val = val.parent;
		}
		return false;
	}

	public static bool IsKeyLightFixture(GameObject go)
	{
		if ((Object)(object)go == (Object)null)
		{
			return false;
		}
		if (IsPlayerOrEnemy(go))
		{
			return false;
		}
		if ((Object)(object)go.GetComponentInParent<PropLight>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<PropLightEmission>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<SemiLaser>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<TruckMenuAnimated>() != (Object)null)
		{
			return true;
		}
		string text = ((Object)go).name.ToLower();
		if (text.Contains("lamp") || text.Contains("lantern") || text.Contains("bulb") || text.Contains("ceilinglight") || text.Contains("spotlight") || text.Contains("laser") || text.Contains("headlight") || text.Contains("proplight"))
		{
			return true;
		}
		return false;
	}

	public static void ProcessSceneLightsAndEmissions()
	{
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_0315: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)LightManager.instance != (Object)null)
		{
			List<PropLight> value = Traverse.Create((object)LightManager.instance).Field<List<PropLight>>("propLights").Value;
			if (value != null)
			{
				foreach (PropLight item in value)
				{
					if (!((Object)(object)item == (Object)null) && !IsPlayerOrEnemy(((Component)item).gameObject))
					{
						Light val = ((Component)item).GetComponent<Light>() ?? Traverse.Create((object)item).Field<Light>("lightComponent").Value;
						if ((Object)(object)val != (Object)null)
						{
							val.color = ColorPurpleLight;
						}
					}
				}
			}
			List<PropLightEmission> value2 = Traverse.Create((object)LightManager.instance).Field<List<PropLightEmission>>("propEmissions").Value;
			if (value2 != null)
			{
				foreach (PropLightEmission item2 in value2)
				{
					if (!((Object)(object)item2 == (Object)null) && !IsPlayerOrEnemy(((Component)item2).gameObject))
					{
						Material value3 = Traverse.Create((object)item2).Field<Material>("material").Value;
						if ((Object)(object)value3 != (Object)null)
						{
							ApplyLampEmissionMaterial(value3);
						}
					}
				}
			}
		}
		PropLight[] array = Object.FindObjectsByType<PropLight>((FindObjectsSortMode)0);
		PropLight[] array2 = array;
		foreach (PropLight val2 in array2)
		{
			if (!((Object)(object)val2 == (Object)null) && !IsPlayerOrEnemy(((Component)val2).gameObject))
			{
				Light val3 = ((Component)val2).GetComponent<Light>() ?? Traverse.Create((object)val2).Field<Light>("lightComponent").Value;
				if ((Object)(object)val3 != (Object)null)
				{
					val3.color = ColorPurpleLight;
				}
			}
		}
		PropLightEmission[] array3 = Object.FindObjectsByType<PropLightEmission>((FindObjectsSortMode)0);
		PropLightEmission[] array4 = array3;
		foreach (PropLightEmission val4 in array4)
		{
			if (!((Object)(object)val4 == (Object)null) && !IsPlayerOrEnemy(((Component)val4).gameObject))
			{
				Material value4 = Traverse.Create((object)val4).Field<Material>("material").Value;
				if ((Object)(object)value4 != (Object)null)
				{
					ApplyLampEmissionMaterial(value4);
				}
			}
		}
		SemiLaser[] array5 = Object.FindObjectsByType<SemiLaser>((FindObjectsSortMode)0);
		SemiLaser[] array6 = array5;
		foreach (SemiLaser val5 in array6)
		{
			if ((Object)(object)val5 != (Object)null)
			{
				ProcessSemiLaser(val5);
			}
		}
		Light[] array7 = Object.FindObjectsByType<Light>((FindObjectsSortMode)0);
		Light[] array8 = array7;
		foreach (Light val6 in array8)
		{
			if (!((Object)(object)val6 == (Object)null))
			{
				int instanceID = ((Object)val6).GetInstanceID();
				if (!ProcessedLights.Contains(instanceID) && IsKeyLightFixture(((Component)val6).gameObject))
				{
					ProcessedLights.Add(instanceID);
					val6.color = ColorPurpleLight;
				}
			}
		}
	}

	public static void ProcessSemiLaser(SemiLaser laser)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: 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_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)laser == (Object)null)
		{
			return;
		}
		if ((Object)(object)laser.laserSpotLight != (Object)null)
		{
			laser.laserSpotLight.color = ColorPurpleLight;
		}
		Light value = Traverse.Create((object)laser).Field<Light>("hitLight").Value;
		if ((Object)(object)value != (Object)null)
		{
			value.color = ColorPurpleLight;
		}
		List<Light> value2 = Traverse.Create((object)laser).Field<List<Light>>("pointLights").Value;
		if (value2 != null)
		{
			foreach (Light item in value2)
			{
				if ((Object)(object)item != (Object)null)
				{
					item.color = ColorPurpleLight;
				}
			}
		}
		List<LineRenderer> value3 = Traverse.Create((object)laser).Field<List<LineRenderer>>("lineRenderers").Value;
		if (value3 == null)
		{
			return;
		}
		foreach (LineRenderer item2 in value3)
		{
			if ((Object)(object)item2 == (Object)null)
			{
				continue;
			}
			item2.startColor = ColorPurpleGlow;
			item2.endColor = ColorPurpleGlow;
			if ((Object)(object)((Renderer)item2).material != (Object)null)
			{
				if (((Renderer)item2).material.HasProperty("_Color"))
				{
					((Renderer)item2).material.SetColor("_Color", ColorPurpleGlow);
				}
				if (((Renderer)item2).material.HasProperty("_TintColor"))
				{
					((Renderer)item2).material.SetColor("_TintColor", ColorPurpleGlow);
				}
				if (((Renderer)item2).material.HasProperty("_EmissionColor"))
				{
					((Renderer)item2).material.SetColor("_EmissionColor", ColorPurpleGlow * 2.5f);
				}
			}
		}
	}

	public static void ApplyLampEmissionMaterial(Material mat)
	{
		//IL_002e: 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)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)mat == (Object)null))
		{
			if (mat.HasProperty("_EmissionColor"))
			{
				mat.EnableKeyword("_EMISSION");
				mat.SetColor("_EmissionColor", ColorPurpleGlow * 2.5f);
			}
			if (mat.HasProperty("_EmissionMap") && (Object)(object)mat.GetTexture("_EmissionMap") != (Object)null)
			{
				mat.EnableKeyword("_EMISSION");
				mat.SetColor("_EmissionColor", ColorPurpleGlow * 3f);
			}
		}
	}

	public static void ConfigureMenuAtmosphere()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		if (!SemiFunc.IsMainMenu() && !SemiFunc.RunIsLobbyMenu())
		{
			return;
		}
		RenderSettings.ambientLight = ColorAmbientNight;
		RenderSettings.fog = true;
		RenderSettings.fogColor = ColorFogNight;
		RenderSettings.fogMode = (FogMode)2;
		RenderSettings.fogDensity = 0.025f;
		TruckHalloweenLighting val = Object.FindAnyObjectByType<TruckHalloweenLighting>();
		if ((Object)(object)val != (Object)null)
		{
			val.emissionColor = ColorPurpleGlow;
			val.wetColor = new Color(0.35f, 0.05f, 0.65f, 1f);
			val.fogColor = ColorFogNight;
			val.ambientColor = ColorAmbientNight;
			if (val.lightColors != null)
			{
				LightColor[] lightColors = val.lightColors;
				foreach (LightColor val2 in lightColors)
				{
					if (val2 != null)
					{
						val2.color = ColorPurpleLight;
						if ((Object)(object)val2.light != (Object)null)
						{
							val2.light.color = ColorPurpleLight;
						}
					}
				}
			}
		}
		TruckMenuAnimated val3 = Object.FindAnyObjectByType<TruckMenuAnimated>();
		if ((Object)(object)val3 != (Object)null)
		{
			Light[] componentsInChildren = ((Component)val3).GetComponentsInChildren<Light>(true);
			Light[] array = componentsInChildren;
			foreach (Light val4 in array)
			{
				val4.color = ColorPurpleLight;
			}
		}
		GameObject val5 = GameObject.Find("Road") ?? GameObject.Find("Ground") ?? GameObject.Find("Landscape");
		if (!((Object)(object)val5 != (Object)null))
		{
			return;
		}
		Renderer[] componentsInChildren2 = val5.GetComponentsInChildren<Renderer>(true);
		Renderer[] array2 = componentsInChildren2;
		foreach (Renderer val6 in array2)
		{
			if ((Object)(object)val6 != (Object)null && (Object)(object)val6.material != (Object)null && val6.material.HasProperty("_Color"))
			{
				Color color = val6.material.GetColor("_Color");
				val6.material.SetColor("_Color", Color.Lerp(color, ColorPurpleLight, 0.25f));
			}
		}
	}

	public static void ApplySelectionBoxStyle(MenuSelectionBox box)
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Expected O, but got Unknown
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)box == (Object)null)
		{
			return;
		}
		Traverse.Create(typeof(MenuSelectionBox)).Field("colorIdleDefault").SetValue((object)ColorButtonIdle);
		Traverse.Create(typeof(MenuSelectionBox)).Field("colorMovingDefault").SetValue((object)ColorButtonHover);
		Traverse.Create((object)box).Field<Color>("flashColor").Value = ColorButtonFlash;
		RawImage val = ((Component)box).GetComponentInChildren<RawImage>() ?? Traverse.Create((object)box).Field<RawImage>("rawImage").Value;
		if (!((Object)(object)val != (Object)null))
		{
			return;
		}
		if ((Object)(object)_selectionBoxMaterialInstance == (Object)null && (Object)(object)((Graphic)val).material != (Object)null)
		{
			_selectionBoxMaterialInstance = new Material(((Graphic)val).material);
			((Object)_selectionBoxMaterialInstance).name = "VioletSpace_SelectionBox_Isolated";
			if (_selectionBoxMaterialInstance.HasProperty("_Color"))
			{
				_selectionBoxMaterialInstance.SetColor("_Color", ColorButtonHover);
			}
			if (_selectionBoxMaterialInstance.HasProperty("_TintColor"))
			{
				_selectionBoxMaterialInstance.SetColor("_TintColor", ColorButtonHover);
			}
		}
		if ((Object)(object)_selectionBoxMaterialInstance != (Object)null && (Object)(object)((Graphic)val).material != (Object)(object)_selectionBoxMaterialInstance)
		{
			((Graphic)val).material = _selectionBoxMaterialInstance;
		}
	}

	public static bool IsCustomizationColorElement(Component comp)
	{
		if ((Object)(object)comp == (Object)null)
		{
			return false;
		}
		if ((Object)(object)comp.GetComponentInParent<MenuButtonColor>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)comp.GetComponentInParent<MenuPageColor>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)comp.GetComponentInParent<MenuColorSelected>() != (Object)null)
		{
			return true;
		}
		if ((Object)(object)comp.GetComponentInParent<MenuElementCosmeticButton>() != (Object)null)
		{
			return true;
		}
		Transform val = comp.transform;
		while ((Object)(object)val != (Object)null)
		{
			string text = ((Object)val).name.ToLower();
			if (text.Contains("colorbutton") || text.Contains("menupagecolor") || text.Contains("colorholder") || text.Contains("colorswatch") || text.Contains("customizationcolor"))
			{
				return true;
			}
			val = val.parent;
		}
		return false;
	}

	public static void ProcessAllUI()
	{
		TextMeshProUGUI[] array = Object.FindObjectsByType<TextMeshProUGUI>((FindObjectsSortMode)0);
		TextMeshProUGUI[] array2 = array;
		foreach (TextMeshProUGUI val in array2)
		{
			if ((Object)(object)val != (Object)null && !IsCustomizationColorElement((Component)(object)val))
			{
				RecolorTMPText((TMP_Text)(object)val);
			}
		}
	}

	public static bool TryTransformColor(Color inColor, out Color outColor)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//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_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		outColor = inColor;
		float num = default(float);
		float num2 = default(float);
		float num3 = default(float);
		Color.RGBToHSV(inColor, ref num, ref num2, ref num3);
		if (num2 < 0.2f || num3 < 0.15f)
		{
			return false;
		}
		if (num <= 0.045f || num >= 0.955f)
		{
			Color colorRedViolet = ColorRedViolet;
			float r = colorRedViolet.r;
			Color colorRedViolet2 = ColorRedViolet;
			float g = colorRedViolet2.g;
			Color colorRedViolet3 = ColorRedViolet;
			((Color)(ref outColor))..ctor(r, g, colorRedViolet3.b, inColor.a);
			return true;
		}
		if (num > 0.045f && num < 0.135f)
		{
			Color colorOrangeViolet = ColorOrangeViolet;
			float r2 = colorOrangeViolet.r;
			Color colorOrangeViolet2 = ColorOrangeViolet;
			float g2 = colorOrangeViolet2.g;
			Color colorOrangeViolet3 = ColorOrangeViolet;
			((Color)(ref outColor))..ctor(r2, g2, colorOrangeViolet3.b, inColor.a);
			return true;
		}
		if (num >= 0.2f && num < 0.46f)
		{
			Color colorGreenViolet = ColorGreenViolet;
			float r3 = colorGreenViolet.r;
			Color colorGreenViolet2 = ColorGreenViolet;
			float g3 = colorGreenViolet2.g;
			Color colorGreenViolet3 = ColorGreenViolet;
			((Color)(ref outColor))..ctor(r3, g3, colorGreenViolet3.b, inColor.a);
			return true;
		}
		return false;
	}

	public static string TransformRichTextTags(string text)
	{
		if (string.IsNullOrEmpty(text) || !text.Contains("<color"))
		{
			return text;
		}
		text = Regex.Replace(text, "<color\\s*=\\s*[\"']?orange[\"']?>", "<color=#4a03a6>", RegexOptions.IgnoreCase);
		text = Regex.Replace(text, "<color\\s*=\\s*[\"']?red[\"']?>", "<color=#430e8a>", RegexOptions.IgnoreCase);
		text = Regex.Replace(text, "<color\\s*=\\s*[\"']?green[\"']?>", "<color=#5f15bf>", RegexOptions.IgnoreCase);
		text = Regex.Replace(text, "<color\\s*=\\s*[\"']?#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})[\"']?>", delegate(Match m)
		{
			//IL_0029: 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)
			string value = m.Groups[1].Value;
			Color inColor = default(Color);
			Color outColor;
			return (ColorUtility.TryParseHtmlString("#" + value, ref inColor) && TryTransformColor(inColor, out outColor)) ? $"<color=#{ColorUtility.ToHtmlStringRGBA(outColor)}>" : m.Value;
		});
		return text;
	}

	public static void RecolorTMPText(TMP_Text tmp)
	{
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)tmp == (Object)null || IsCustomizationColorElement((Component)(object)tmp))
		{
			return;
		}
		string name = ((Object)((Component)tmp).gameObject).name;
		string text = tmp.text;
		if (name.IndexOf("Logo", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("REPO", StringComparison.OrdinalIgnoreCase) < 0 && (text == null || !(text.Trim() == "R.E.P.O.")))
		{
			if (TryTransformColor(((Graphic)tmp).color, out var outColor))
			{
				((Graphic)tmp).color = outColor;
			}
			if (!string.IsNullOrEmpty(tmp.text) && tmp.text.Contains("<color"))
			{
				tmp.text = TransformRichTextTags(tmp.text);
			}
		}
	}
}
[HarmonyPatch(typeof(RunManager), "Awake")]
public static class Patch_RunManager_Awake
{
	public static void Postfix(RunManager __instance)
	{
		if ((Object)(object)__instance.levelMainMenu != (Object)null && (Object)(object)__instance.levelMainMenu.ConstantMusicPreset != (Object)null && (Object)(object)VioletSpace21DeluxePlugin.MainMenuClip != (Object)null)
		{
			__instance.levelMainMenu.ConstantMusicPreset.clip = VioletSpace21DeluxePlugin.MainMenuClip;
			__instance.levelMainMenu.ConstantMusicPreset.volume = 1f;
		}
		if ((Object)(object)__instance.levelLobbyMenu != (Object)null && (Object)(object)__instance.levelLobbyMenu.ConstantMusicPreset != (Object)null && (Object)(object)VioletSpace21DeluxePlugin.LobbyMenuClip != (Object)null)
		{
			__instance.levelLobbyMenu.ConstantMusicPreset.clip = VioletSpace21DeluxePlugin.LobbyMenuClip;
			__instance.levelLobbyMenu.ConstantMusicPreset.volume = 1f;
		}
	}
}
[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
public static class Patch_RunManager_ChangeLevel
{
	public static void Postfix(RunManager __instance)
	{
		VioletSpace21DeluxePlugin.EnforceMenuMusic();
	}
}
[HarmonyPatch(typeof(ConstantMusic), "Setup")]
public static class Patch_ConstantMusic_Setup
{
	public static void Postfix(ConstantMusic __instance)
	{
		if (SemiFunc.IsMainMenu() && (Object)(object)VioletSpace21DeluxePlugin.MainMenuClip != (Object)null)
		{
			Traverse.Create((object)__instance).Field<AudioClip>("clip").Value = VioletSpace21DeluxePlugin.MainMenuClip;
			Traverse.Create((object)__instance).Field<float>("volume").Value = 1f;
		}
		else if (SemiFunc.RunIsLobbyMenu() && (Object)(object)VioletSpace21DeluxePlugin.LobbyMenuClip != (Object)null)
		{
			Traverse.Create((object)__instance).Field<AudioClip>("clip").Value = VioletSpace21DeluxePlugin.LobbyMenuClip;
			Traverse.Create((object)__instance).Field<float>("volume").Value = 1f;
		}
	}
}
[HarmonyPatch(typeof(TextMeshProUGUI), "Awake")]
public static class Patch_TextMeshProUGUI_Awake
{
	public static void Postfix(TextMeshProUGUI __instance)
	{
		if (!VioletSpace21DeluxePlugin.IsCustomizationColorElement((Component)(object)__instance))
		{
			VioletSpace21DeluxePlugin.RecolorTMPText((TMP_Text)(object)__instance);
		}
	}
}
[HarmonyPatch(typeof(TextMeshProUGUI), "GenerateTextMesh")]
public static class Patch_TextMeshProUGUI_GenerateTextMesh
{
	public static void Prefix(TextMeshProUGUI __instance)
	{
		if (!VioletSpace21DeluxePlugin.IsCustomizationColorElement((Component)(object)__instance))
		{
			VioletSpace21DeluxePlugin.RecolorTMPText((TMP_Text)(object)__instance);
		}
	}
}
[HarmonyPatch(typeof(TMP_Text), "set_text")]
public static class Patch_TMP_Text_SetText
{
	public static void Prefix(TMP_Text __instance, ref string value)
	{
		if (!VioletSpace21DeluxePlugin.IsCustomizationColorElement((Component)(object)__instance) && !string.IsNullOrEmpty(value) && value.Contains("<color"))
		{
			value = VioletSpace21DeluxePlugin.TransformRichTextTags(value);
		}
	}
}
[HarmonyPatch(typeof(MenuLogoHalloweenOverlay), "Awake")]
public static class Patch_MenuLogoHalloweenOverlay_Awake
{
	public static bool Prefix(MenuLogoHalloweenOverlay __instance)
	{
		VioletSpace21DeluxePlugin.ApplyCustomLogo();
		return false;
	}
}
[HarmonyPatch(typeof(MenuSelectionBox), "Awake")]
public static class Patch_MenuSelectionBox_Awake
{
	public static void Postfix(MenuSelectionBox __instance)
	{
		VioletSpace21DeluxePlugin.ApplySelectionBoxStyle(__instance);
	}
}
[HarmonyPatch(typeof(MenuSelectionBox), "Update")]
public static class Patch_MenuSelectionBox_Update
{
	public static void Postfix(MenuSelectionBox __instance)
	{
		VioletSpace21DeluxePlugin.ApplySelectionBoxStyle(__instance);
	}
}
[HarmonyPatch(typeof(MenuButtonColor), "Start")]
public static class Patch_MenuButtonColor_Start
{
	public static void Postfix(MenuButtonColor __instance)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		MenuButton val = ((Component)__instance).GetComponent<MenuButton>() ?? Traverse.Create((object)__instance).Field<MenuButton>("menuButton").Value;
		SemiColor value = Traverse.Create((object)__instance).Field<SemiColor>("color").Value;
		if ((Object)(object)val != (Object)null && (Object)(object)value != (Object)null)
		{
			Color color = (val.colorNormal = value.color + Color.black * 0.5f);
			val.colorHover = value.color;
			val.colorClick = value.color + Color.white * 0.95f;
			TextMeshProUGUI val2 = ((Component)val).GetComponentInChildren<TextMeshProUGUI>() ?? Traverse.Create((object)val).Field<TextMeshProUGUI>("buttonText").Value;
			if ((Object)(object)val2 != (Object)null)
			{
				((Graphic)val2).color = color;
			}
		}
	}
}
[HarmonyPatch(typeof(PropLight), "Start")]
public static class Patch_PropLight_Start
{
	public static void Postfix(PropLight __instance)
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		if (!VioletSpace21DeluxePlugin.IsPlayerOrEnemy(((Component)__instance).gameObject))
		{
			Light val = ((Component)__instance).GetComponent<Light>() ?? Traverse.Create((object)__instance).Field<Light>("lightComponent").Value;
			if ((Object)(object)val != (Object)null)
			{
				val.color = VioletSpace21DeluxePlugin.ColorPurpleLight;
			}
		}
	}
}
[HarmonyPatch(typeof(PropLightEmission), "Awake")]
public static class Patch_PropLightEmission_Awake
{
	public static void Postfix(PropLightEmission __instance)
	{
		if (!VioletSpace21DeluxePlugin.IsPlayerOrEnemy(((Component)__instance).gameObject))
		{
			Material value = Traverse.Create((object)__instance).Field<Material>("material").Value;
			if ((Object)(object)value != (Object)null)
			{
				VioletSpace21DeluxePlugin.ApplyLampEmissionMaterial(value);
			}
		}
	}
}
[HarmonyPatch(typeof(SemiLaser), "Start")]
public static class Patch_SemiLaser_Start
{
	public static void Postfix(SemiLaser __instance)
	{
		VioletSpace21DeluxePlugin.ProcessSemiLaser(__instance);
	}
}
[HarmonyPatch(typeof(SemiLaser), "Update")]
public static class Patch_SemiLaser_Update
{
	public static void Postfix(SemiLaser __instance)
	{
		VioletSpace21DeluxePlugin.ProcessSemiLaser(__instance);
	}
}
[HarmonyPatch(typeof(TruckHalloweenLighting), "LightColorsSet")]
public static class Patch_TruckHalloweenLighting_LightColorsSet
{
	public static void Postfix(TruckHalloweenLighting __instance)
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		if (__instance.lightColors != null)
		{
			LightColor[] lightColors = __instance.lightColors;
			foreach (LightColor val in lightColors)
			{
				if (val != null)
				{
					val.color = VioletSpace21DeluxePlugin.ColorPurpleLight;
					if ((Object)(object)val.light != (Object)null)
					{
						val.light.color = VioletSpace21DeluxePlugin.ColorPurpleLight;
					}
				}
			}
		}
		__instance.emissionColor = VioletSpace21DeluxePlugin.ColorPurpleGlow;
		__instance.wetColor = new Color(0.35f, 0.05f, 0.65f, 1f);
		__instance.fogColor = VioletSpace21DeluxePlugin.ColorFogNight;
		__instance.ambientColor = VioletSpace21DeluxePlugin.ColorAmbientNight;
	}
}
[HarmonyPatch(typeof(EnvironmentDirector), "Update")]
public static class Patch_EnvironmentDirector_Update
{
	public static void Postfix(EnvironmentDirector __instance)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if (SemiFunc.IsMainMenu() || SemiFunc.RunIsLobbyMenu())
		{
			RenderSettings.ambientLight = VioletSpace21DeluxePlugin.ColorAmbientNight;
			RenderSettings.fogColor = VioletSpace21DeluxePlugin.ColorFogNight;
		}
	}
}
[HarmonyPatch(typeof(HealthUI), "Update")]
public static class Patch_HealthUI_EnforcePurple
{
	public static void Postfix(HealthUI __instance)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance == (Object)null)
		{
			return;
		}
		TextMeshProUGUI val = ((Component)__instance).GetComponent<TextMeshProUGUI>() ?? Traverse.Create((object)__instance).Field<TextMeshProUGUI>("Text").Value;
		if ((Object)(object)val != (Object)null && ((Graphic)val).color != VioletSpace21DeluxePlugin.ColorHealthNumber)
		{
			((Graphic)val).color = VioletSpace21DeluxePlugin.ColorHealthNumber;
		}
		TextMeshProUGUI val2 = Traverse.Create((object)__instance).Field<TextMeshProUGUI>("textMaxHealth").Value;
		if ((Object)(object)val2 == (Object)null)
		{
			Transform val3 = ((Component)__instance).transform.Find("HealthMax");
			if ((Object)(object)val3 != (Object)null)
			{
				val2 = ((Component)val3).GetComponent<TextMeshProUGUI>();
			}
		}
		if ((Object)(object)val2 != (Object)null && ((Graphic)val2).color != VioletSpace21DeluxePlugin.ColorHealthNumber)
		{
			((Graphic)val2).color = VioletSpace21DeluxePlugin.ColorHealthNumber;
		}
		Transform val4 = ((Component)__instance).transform.Find("Plus");
		if ((Object)(object)val4 != (Object)null)
		{
			Image component = ((Component)val4).GetComponent<Image>();
			if ((Object)(object)component != (Object)null && ((Graphic)component).color != VioletSpace21DeluxePlugin.ColorHealthPlus)
			{
				((Graphic)component).color = VioletSpace21DeluxePlugin.ColorHealthPlus;
			}
		}
	}
}
[HarmonyPatch(typeof(EnergyUI), "Update")]
public static class Patch_EnergyUI_EnforcePurple
{
	public static void Postfix(EnergyUI __instance)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance == (Object)null)
		{
			return;
		}
		TextMeshProUGUI val = ((Component)__instance).GetComponent<TextMeshProUGUI>() ?? Traverse.Create((object)__instance).Field<TextMeshProUGUI>("Text").Value;
		if ((Object)(object)val != (Object)null && ((Graphic)val).color != VioletSpace21DeluxePlugin.ColorStaminaNumber)
		{
			((Graphic)val).color = VioletSpace21DeluxePlugin.ColorStaminaNumber;
		}
		TextMeshProUGUI val2 = Traverse.Create((object)__instance).Field<TextMeshProUGUI>("textEnergyMax").Value;
		if ((Object)(object)val2 == (Object)null)
		{
			Transform val3 = ((Component)__instance).transform.Find("TextEnergyMax") ?? ((Component)__instance).transform.Find("EnergyMax");
			if ((Object)(object)val3 != (Object)null)
			{
				val2 = ((Component)val3).GetComponent<TextMeshProUGUI>();
			}
		}
		if ((Object)(object)val2 != (Object)null && ((Graphic)val2).color != VioletSpace21DeluxePlugin.ColorStaminaNumber)
		{
			((Graphic)val2).color = VioletSpace21DeluxePlugin.ColorStaminaNumber;
		}
		Transform val4 = ((Component)__instance).transform.Find("EnergySign") ?? ((Component)__instance).transform.Find("Zap") ?? ((Component)__instance).transform.Find("Image");
		if ((Object)(object)val4 != (Object)null)
		{
			Image component = ((Component)val4).GetComponent<Image>();
			if ((Object)(object)component != (Object)null && ((Graphic)component).color != VioletSpace21DeluxePlugin.ColorStaminaZap)
			{
				((Graphic)component).color = VioletSpace21DeluxePlugin.ColorStaminaZap;
			}
		}
	}
}

modules/me.loaforc.soundapi.dll

Decompiled a week ago
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
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 System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using loaforcsSoundAPI.Core;
using loaforcsSoundAPI.Core.Data;
using loaforcsSoundAPI.Core.JSON;
using loaforcsSoundAPI.Core.Networking;
using loaforcsSoundAPI.Core.Patches;
using loaforcsSoundAPI.Core.Patches.Harmony;
using loaforcsSoundAPI.Core.Patches.Native;
using loaforcsSoundAPI.Core.Util;
using loaforcsSoundAPI.Core.Util.Extensions;
using loaforcsSoundAPI.Reporting;
using loaforcsSoundAPI.Reporting.Data;
using loaforcsSoundAPI.SoundPacks;
using loaforcsSoundAPI.SoundPacks.Data;
using loaforcsSoundAPI.SoundPacks.Data.Conditions;

[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("me.loaforc.soundapi")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.0.13.0")]
[assembly: AssemblyInformationalVersion("2.0.13+fe10f5c1a08a9ae2f354cdc3650fe39e1494c473")]
[assembly: AssemblyProduct("loaforcsSoundAPI")]
[assembly: AssemblyTitle("me.loaforc.soundapi")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.13.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	internal static class IsExternalInit
	{
	}
}
namespace loaforcsSoundAPI
{
	[Flags]
	public enum AudioSourceCopyFlags
	{
		DontCopyPlayOnAwake = 1
	}
	[BepInPlugin("me.loaforc.soundapi", "loaforcsSoundAPI", "2.0.13")]
	internal class loaforcsSoundAPI : BaseUnityPlugin
	{
		internal static ManualLogSource Logger { get; private set; }

		private void Awake()
		{
			Logger = Logger.CreateLogSource("me.loaforc.soundapi");
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			Logger.LogInfo((object)"Setting up config");
			Debuggers.Bind(((BaseUnityPlugin)this).Config);
			SoundReportHandler.Bind(((BaseUnityPlugin)this).Config);
			PatchConfig.Bind(((BaseUnityPlugin)this).Config);
			PackLoadingConfig.Bind(((BaseUnityPlugin)this).Config);
			Logger.LogInfo((object)"Running patches");
			Harmony harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "me.loaforc.soundapi");
			if (PatchConfig.PreferredBackend == PatchConfig.Backend.HarmonyX)
			{
				Logger.LogInfo((object)"Native backend is manually disabled.");
				HarmonyBackend.Init(harmony);
			}
			else if (NativeBackend.TryInit())
			{
				Logger.LogInfo((object)("Native backend is supported on " + Application.unityVersion + "!"));
			}
			else
			{
				Logger.LogWarning((object)"Native backend failed, falling back to default harmony backend!");
				HarmonyBackend.Init(harmony);
			}
			Logger.LogInfo((object)"Registering data");
			SoundAPI.RegisterAll(Assembly.GetExecutingAssembly());
			SoundAPIAudioManager.SpawnManager();
			SoundReplacementHandler.Register();
			((BaseUnityPlugin)this).Config.Save();
			Logger.LogInfo((object)"me.loaforc.soundapi by loaforc has loaded :3");
		}

		internal static ConfigFile GenerateConfigFile(string name, BepInPlugin metadata)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			return new ConfigFile(Utility.CombinePaths(new string[2]
			{
				Paths.ConfigPath,
				name + ".cfg"
			}), false, metadata);
		}
	}
	public static class SoundAPI
	{
		public const string PLUGIN_GUID = "me.loaforc.soundapi";

		internal static NetworkAdapter CurrentNetworkAdapter { get; private set; }

		public static async Task<AudioClip> LoadAudioFileAsync(string fullPath)
		{
			if (!File.Exists(fullPath))
			{
				throw new FileNotFoundException("'" + fullPath + "' not found.");
			}
			if (!SoundPackLoadPipeline.audioExtensions.ContainsKey(Path.GetExtension(fullPath)))
			{
				throw new NotImplementedException("Audio file extension: '" + Path.GetExtension(fullPath) + "' is not implemented.");
			}
			UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(fullPath, SoundPackLoadPipeline.audioExtensions[Path.GetExtension(fullPath)]);
			await (AsyncOperation)(object)request.SendWebRequest();
			AudioClip content = DownloadHandlerAudioClip.GetContent(request);
			request.Dispose();
			return content;
		}

		public static void RegisterAll(Assembly assembly)
		{
			foreach (Type loadableType in assembly.GetLoadableTypes())
			{
				if (loadableType.IsNested)
				{
					continue;
				}
				foreach (SoundAPIConditionAttribute conditionAttribute in loadableType.GetCustomAttributes<SoundAPIConditionAttribute>())
				{
					if (!typeof(Condition).IsAssignableFrom(loadableType))
					{
						loaforcsSoundAPI.Logger.LogError((object)("Condition: '" + loadableType.FullName + "' has been marked with [SoundAPICondition] but does not extend Condition!"));
						continue;
					}
					ConstructorInfo info = loadableType.GetConstructor(Array.Empty<Type>());
					if (info == null)
					{
						loaforcsSoundAPI.Logger.LogError((object)("Condition: '" + loadableType.FullName + "' has no valid constructor! It must have a constructor with no parameters! If you need extra parameters do not mark it with [SoundAPICondition] and register it manually."));
						continue;
					}
					RegisterCondition(conditionAttribute.ID, delegate
					{
						if (conditionAttribute.IsDeprecated)
						{
							if (conditionAttribute.DeprecationReason == null)
							{
								loaforcsSoundAPI.Logger.LogWarning((object)("Condition: '" + conditionAttribute.ID + "' is deprecated and may be removed in future."));
							}
							else
							{
								loaforcsSoundAPI.Logger.LogWarning((object)("Condition: '" + conditionAttribute.ID + "' is deprecated. " + conditionAttribute.DeprecationReason));
							}
						}
						return (Condition)info.Invoke(Array.Empty<object>());
					});
				}
			}
		}

		public static void RegisterCondition(string id, Func<Condition> factory)
		{
			SoundPackDataHandler.Register(id, factory);
		}

		public static void RegisterNetworkAdapter(NetworkAdapter adapter)
		{
			CurrentNetworkAdapter = adapter;
			loaforcsSoundAPI.Logger.LogInfo((object)("Registered network adapter: '" + CurrentNetworkAdapter.Name + "'"));
			CurrentNetworkAdapter.OnRegister();
		}

		public static void RegisterSoundPack(SoundPack pack)
		{
			if (SoundPackDataHandler.LoadedPacks.Contains(pack))
			{
				throw new InvalidOperationException("Already registered sound-pack: '" + pack.Name + "'!");
			}
			SoundPackDataHandler.AddLoadedPack(pack);
			foreach (SoundReplacementCollection replacementCollection in pack.ReplacementCollections)
			{
				foreach (SoundReplacementGroup replacement in replacementCollection.Replacements)
				{
					SoundPackDataHandler.AddReplacement(replacement);
				}
			}
		}

		public static AudioSource CopyAudioSource(AudioSource source, GameObject target, AudioSourceCopyFlags flags = (AudioSourceCopyFlags)0)
		{
			//IL_00b1: 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)
			AudioSource val = target.AddComponent<AudioSource>();
			val.clip = source.clip;
			val.loop = source.loop;
			val.mute = source.mute;
			val.pitch = source.pitch;
			val.outputAudioMixerGroup = source.outputAudioMixerGroup;
			val.priority = source.priority;
			val.spatialize = source.spatialize;
			val.spread = source.spread;
			val.volume = source.volume;
			val.bypassEffects = source.bypassEffects;
			val.dopplerLevel = source.dopplerLevel;
			val.maxDistance = source.maxDistance;
			val.minDistance = source.minDistance;
			val.panStereo = source.panStereo;
			val.rolloffMode = source.rolloffMode;
			val.spatialBlend = source.spatialBlend;
			val.bypassReverbZones = source.bypassReverbZones;
			val.ignoreListenerPause = source.ignoreListenerPause;
			val.ignoreListenerVolume = source.ignoreListenerVolume;
			if ((flags & AudioSourceCopyFlags.DontCopyPlayOnAwake) == 0)
			{
				val.playOnAwake = source.playOnAwake;
			}
			val.reverbZoneMix = source.reverbZoneMix;
			val.spatializePostEffects = source.spatializePostEffects;
			val.velocityUpdateMode = source.velocityUpdateMode;
			return val;
		}
	}
	internal static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "me.loaforc.soundapi";

		public const string PLUGIN_NAME = "loaforcsSoundAPI";

		public const string PLUGIN_VERSION = "2.0.13";
	}
}
namespace loaforcsSoundAPI.SoundPacks
{
	public readonly struct AudioSourcePlayEvent
	{
		public bool IsOneShot { get; }

		public AudioSource Source { get; }

		public AudioSourceAdditionalData Data { get; }

		public IContext Context { get; }

		public AudioClip Clip { get; }

		public AudioSourcePlayEvent(AudioSource source, AudioClip clip, bool isOneShot)
		{
			IsOneShot = isOneShot;
			Source = source;
			Clip = clip;
			Data = AudioSourceAdditionalData.GetOrCreate(source);
			Context = Data.CurrentContext ?? DefaultConditionContext.DEFAULT;
		}
	}
	internal class LoadSoundOperation
	{
		public readonly UnityWebRequest WebRequest = webRequest.webRequest;

		public readonly SoundInstance Sound;

		public bool IsReady => WebRequest.isDone;

		public bool IsDone { get; set; }

		public LoadSoundOperation(SoundInstance soundInstance, UnityWebRequestAsyncOperation webRequest)
		{
			Sound = soundInstance;
			base..ctor();
		}
	}
	internal static class PackLoadingConfig
	{
		internal static bool MetadataSpoofing { get; private set; }

		internal static void Bind(ConfigFile file)
		{
			MetadataSpoofing = file.Bind<bool>("PackLoading", "MetadataSpoofing", true, "Should SoundAPI use a fake BepInPlugin attribute when generating configs? This can fix some issues with mod managers, notably with Gale displaying the config file name, instead of the sound-pack name.").Value;
		}
	}
	internal static class SoundPackDataHandler
	{
		private static List<SoundPack> _loadedPacks = new List<SoundPack>();

		internal static Dictionary<string, List<SoundReplacementGroup>> SoundReplacements = new Dictionary<string, List<SoundReplacementGroup>>();

		internal static Dictionary<string, Func<Condition>> conditionFactories = new Dictionary<string, Func<Condition>>();

		internal static List<AudioClip> allLoadedClips = new List<AudioClip>();

		internal static IReadOnlyList<SoundPack> LoadedPacks => _loadedPacks.AsReadOnly();

		internal static void Register(string id, Func<Condition> factory)
		{
			conditionFactories[id] = factory;
		}

		public static Condition CreateCondition(string id)
		{
			if (conditionFactories.TryGetValue(id, out var value))
			{
				return value();
			}
			return new InvalidCondition(id);
		}

		internal static void AddLoadedPack(SoundPack pack)
		{
			_loadedPacks.Add(pack);
		}

		internal static void AddReplacement(SoundReplacementGroup group)
		{
			foreach (string match in group.Matches)
			{
				string key = match.Split(":").Last();
				if (!SoundReplacements.TryGetValue(key, out var value))
				{
					value = new List<SoundReplacementGroup>();
				}
				if (!value.Contains(group))
				{
					value.Add(group);
					SoundReplacements[key] = value;
				}
			}
		}
	}
	internal static class SoundPackLoadPipeline
	{
		private class SkippedResults
		{
			public int Collections;

			public int Groups;

			public int Sounds;
		}

		private static volatile int _activeThreads;

		private static Dictionary<string, List<string>> mappings;

		internal static Dictionary<string, AudioType> audioExtensions;

		internal static event Action OnFinishedPipeline;

		internal static async void StartPipeline()
		{
			Stopwatch completeLoadingTimer = Stopwatch.StartNew();
			Stopwatch timer = Stopwatch.StartNew();
			List<SoundPack> list = FindAndLoadPacks();
			loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 1) Loading Sound-pack definitions took {timer.ElapsedMilliseconds}ms");
			if (list.Count == 0)
			{
				loaforcsSoundAPI.Logger.LogWarning((object)"No sound-packs were found to load! This can be ignorable if you're doing testing or using SoundAPI for another purpose, but if you expected sound-packs to load you may have set it up incorrectly.");
			}
			timer.Restart();
			List<LoadSoundOperation> webRequestOperations = new List<LoadSoundOperation>();
			foreach (SoundPack item2 in list)
			{
				string path = Path.Combine(item2.PackFolder, "soundapi_mappings.json");
				if (!File.Exists(path))
				{
					continue;
				}
				Dictionary<string, List<string>> dictionary = JSONDataLoader.LoadFromFile<Dictionary<string, List<string>>>(path);
				foreach (KeyValuePair<string, List<string>> item3 in dictionary)
				{
					if (mappings.ContainsKey(item3.Key))
					{
						mappings[item3.Key].AddRange(item3.Value);
					}
					else
					{
						mappings[item3.Key] = item3.Value;
					}
				}
			}
			loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 2) Loading Sound-pack mappings ('{mappings.Count}') took {timer.ElapsedMilliseconds}ms");
			timer.Restart();
			SkippedResults skippedStats = new SkippedResults();
			foreach (SoundPack item4 in list)
			{
				foreach (SoundReplacementCollection item5 in LoadSoundReplacementCollections(item4, ref skippedStats))
				{
					foreach (SoundReplacementGroup replacement in item5.Replacements)
					{
						SoundPackDataHandler.AddReplacement(replacement);
						foreach (SoundInstance sound in replacement.Sounds)
						{
							if (sound.Condition is ConstantCondition { Value: false })
							{
								Debuggers.SoundReplacementLoader?.Log("skipping a sound in '" + LogFormats.FormatFilePath(item5.FilePath) + "' because sound is marked as constant and has a value of false.");
								skippedStats.Sounds++;
							}
							else
							{
								webRequestOperations.Add(StartWebRequestOperation(item4, sound, audioExtensions[Path.GetExtension(sound.Sound)]));
							}
						}
					}
				}
			}
			int amountOfOperations = webRequestOperations.Count;
			loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 3) Skipped {skippedStats.Collections} collection(s), {skippedStats.Groups} replacement(s), {skippedStats.Sounds} sound(s)");
			loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 3) Loading sound replacement collections took {timer.ElapsedMilliseconds}ms");
			if (SoundReportHandler.CurrentReport != null)
			{
				SoundReportHandler.CurrentReport.AudioClipsLoaded = amountOfOperations;
			}
			loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 4) Started loading {amountOfOperations} audio file(s)");
			loaforcsSoundAPI.Logger.LogInfo((object)"Waiting for splash screens to complete to continue...");
			completeLoadingTimer.Stop();
			await Task.Delay(1);
			loaforcsSoundAPI.Logger.LogInfo((object)"Splash screens done! Continuing pipeline");
			loaforcsSoundAPI.Logger.LogWarning((object)"The game will freeze for a moment!");
			timer.Restart();
			completeLoadingTimer.Start();
			bool flag = false;
			bool threadsShouldExit = false;
			ConcurrentQueue<LoadSoundOperation> queuedOperations = new ConcurrentQueue<LoadSoundOperation>();
			ConcurrentBag<Exception> threadPoolExceptions = new ConcurrentBag<Exception>();
			for (int i = 0; i < 16; i++)
			{
				new Thread((ThreadStart)delegate
				{
					while (queuedOperations.Count == 0 && !threadsShouldExit)
					{
						Thread.Yield();
					}
					Interlocked.Increment(ref _activeThreads);
					Debuggers.SoundReplacementLoader?.Log($"active threads at {_activeThreads}");
					LoadSoundOperation result;
					while (queuedOperations.TryDequeue(out result))
					{
						try
						{
							AudioClip content = DownloadHandlerAudioClip.GetContent(result.WebRequest);
							result.Sound.Clip = content;
							result.WebRequest.Dispose();
							Debuggers.SoundReplacementLoader?.Log("clip generated");
							result.IsDone = true;
						}
						catch (Exception item)
						{
							threadPoolExceptions.Add(item);
						}
					}
					Interlocked.Decrement(ref _activeThreads);
				}).Start();
			}
			while (webRequestOperations.Count > 0)
			{
				foreach (LoadSoundOperation item6 in from operation in webRequestOperations.ToList()
					where operation.IsReady
					select operation)
				{
					queuedOperations.Enqueue(item6);
					webRequestOperations.Remove(item6);
				}
				if (!flag && webRequestOperations.Count < amountOfOperations / 2)
				{
					flag = true;
					loaforcsSoundAPI.Logger.LogInfo((object)"(Step 5) Queued half of the needed operations!");
				}
				Thread.Yield();
			}
			loaforcsSoundAPI.Logger.LogInfo((object)"(Step 5) All file reads are done, waiting for the audio clips conversions.");
			threadsShouldExit = true;
			while (_activeThreads > 0 || webRequestOperations.Any((LoadSoundOperation operation) => !operation.IsDone))
			{
				Thread.Yield();
			}
			loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 6) Took {timer.ElapsedMilliseconds}ms to finish loading audio clips from files");
			if (threadPoolExceptions.Count != 0)
			{
				loaforcsSoundAPI.Logger.LogError((object)$"(Step 6) {threadPoolExceptions.Count} internal error(s) happened while loading:");
				foreach (Exception item7 in threadPoolExceptions)
				{
					loaforcsSoundAPI.Logger.LogError((object)item7.ToString());
				}
			}
			SoundPackLoadPipeline.OnFinishedPipeline();
			mappings = null;
			loaforcsSoundAPI.Logger.LogDebug((object)$"Active Threads that are left over: {_activeThreads}");
			loaforcsSoundAPI.Logger.LogInfo((object)$"Entire load process took an effective {completeLoadingTimer.ElapsedMilliseconds}ms");
		}

		private static List<SoundPack> FindAndLoadPacks(string entryPoint = "sound_pack.json")
		{
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Expected O, but got Unknown
			Dictionary<string, SoundPack> dictionary = new Dictionary<string, SoundPack>();
			string[] files = Directory.GetFiles(Paths.PluginPath, entryPoint, SearchOption.AllDirectories);
			foreach (string text in files)
			{
				Debuggers.SoundReplacementLoader?.Log("found entry point: '" + text + "'!");
				SoundPack soundPack = JSONDataLoader.LoadFromFile<SoundPack>(text);
				if (soundPack == null)
				{
					continue;
				}
				soundPack.PackFolder = Path.GetDirectoryName(text);
				if (dictionary.TryGetValue(soundPack.Name, out var value))
				{
					IValidatable.LogAndCheckValidationResult("loading '" + text + "'", new List<IValidatable.ValidationResult>(1)
					{
						new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "A sound-pack with name '" + soundPack.Name + "' was already loaded from '" + LogFormats.FormatFilePath(Path.Combine(value.PackFolder, "sound_pack.json")) + "'. Skipping loading the duplicate!!")
					}, soundPack.Logger);
					continue;
				}
				Debuggers.SoundReplacementLoader?.Log("json loaded, validating");
				List<IValidatable.ValidationResult> results = soundPack.Validate();
				if (IValidatable.LogAndCheckValidationResult("loading '" + text + "'", results, soundPack.Logger))
				{
					ConfigFile val = loaforcsSoundAPI.GenerateConfigFile(metadata: (BepInPlugin)((!PackLoadingConfig.MetadataSpoofing) ? ((object)MetadataHelper.GetMetadata(typeof(loaforcsSoundAPI))) : ((object)new BepInPlugin(soundPack.GUID, soundPack.Name, soundPack.Version ?? "1.0.0"))), name: soundPack.GUID);
					val.SaveOnConfigSet = false;
					soundPack.Bind(val);
					if (val.Count > 0)
					{
						val.Save();
					}
					dictionary[soundPack.Name] = soundPack;
					SoundPackDataHandler.AddLoadedPack(soundPack);
					Debuggers.SoundReplacementLoader?.Log("pack folder: " + soundPack.PackFolder);
				}
			}
			Debuggers.SoundReplacementLoader?.Log($"loaded '{dictionary.Count}' packs.");
			return dictionary.Values.ToList();
		}

		private static List<SoundReplacementCollection> LoadSoundReplacementCollections(SoundPack pack, ref SkippedResults skippedStats)
		{
			List<SoundReplacementCollection> list = new List<SoundReplacementCollection>();
			if (!Directory.Exists(Path.Combine(pack.PackFolder, "replacers")))
			{
				return list;
			}
			Debuggers.SoundReplacementLoader?.Log("start loading '" + pack.Name + "'!");
			string[] files = Directory.GetFiles(Path.Combine(pack.PackFolder, "replacers"), "*.json", SearchOption.AllDirectories);
			foreach (string text in files)
			{
				Debuggers.SoundReplacementLoader?.Log("found replacer: '" + text + "'!");
				SoundReplacementCollection soundReplacementCollection = JSONDataLoader.LoadFromFile<SoundReplacementCollection>(text);
				if (soundReplacementCollection == null)
				{
					continue;
				}
				soundReplacementCollection.Pack = pack;
				if (soundReplacementCollection.Condition is ConstantCondition { Value: false })
				{
					Debuggers.SoundReplacementLoader?.Log("skipping '" + LogFormats.FormatFilePath(soundReplacementCollection.FilePath) + "' because collection is marked as constant and has a value of false.");
					skippedStats.Collections++;
				}
				else
				{
					if (!IValidatable.LogAndCheckValidationResult("loading '" + LogFormats.FormatFilePath(text) + "'", soundReplacementCollection.Validate(), pack.Logger))
					{
						continue;
					}
					List<IValidatable.ValidationResult> list2 = new List<IValidatable.ValidationResult>();
					foreach (SoundReplacementGroup replacement in soundReplacementCollection.Replacements)
					{
						replacement.Parent = soundReplacementCollection;
						if (replacement.Condition is ConstantCondition { Value: false })
						{
							Debuggers.SoundReplacementLoader?.Log("skipping a replacement in '" + LogFormats.FormatFilePath(soundReplacementCollection.FilePath) + "' because group is marked as constant and has a value of false.");
							skippedStats.Groups++;
							continue;
						}
						List<IValidatable.ValidationResult> list3 = replacement.Validate();
						foreach (string item in replacement.Matches.ToList())
						{
							if (item.StartsWith("#"))
							{
								replacement.Matches.Remove(item);
								if (mappings.TryGetValue(item.Substring(1), out var value))
								{
									replacement.Matches.AddRange(value);
								}
								else
								{
									list3.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Mapping: '" + item + "' has not been found. If it's part of a soft dependency, make sure to use a 'mod_installed' condition with 'constant' enabled."));
								}
							}
						}
						if (list3.Count != 0)
						{
							list2.AddRange(list3);
							continue;
						}
						foreach (SoundInstance sound in replacement.Sounds)
						{
							sound.Parent = replacement;
							list3.AddRange(sound.Validate());
						}
						if (list3.Count != 0)
						{
							list2.AddRange(list3);
							continue;
						}
						List<string> collection = replacement.Matches.Select((string match) => (match.Split(":").Length != 2) ? match : ("*:" + match)).ToList();
						replacement.Matches.Clear();
						replacement.Matches.AddRange(collection);
					}
					if (IValidatable.LogAndCheckValidationResult("loading '" + LogFormats.FormatFilePath(text) + "'", list2, pack.Logger))
					{
						list.Add(soundReplacementCollection);
					}
				}
			}
			return list;
		}

		private static LoadSoundOperation StartWebRequestOperation(SoundPack pack, SoundInstance sound, AudioType type)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(pack.PackFolder, "sounds", sound.Sound);
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(text, type);
			return new LoadSoundOperation(sound, audioClip.SendWebRequest());
		}

		static SoundPackLoadPipeline()
		{
			SoundPackLoadPipeline.OnFinishedPipeline = delegate
			{
			};
			mappings = new Dictionary<string, List<string>>();
			audioExtensions = new Dictionary<string, AudioType>
			{
				{
					".ogg",
					(AudioType)14
				},
				{
					".wav",
					(AudioType)20
				},
				{
					".mp3",
					(AudioType)13
				}
			};
		}
	}
	internal readonly struct ReplacementResult
	{
		public AudioClip ReplacedClip { get; }

		public SoundReplacementGroup ReplacedWith { get; }

		public bool IsUpdateEveryFrame { get; }

		public ReplacementResult(AudioClip replacement, SoundReplacementGroup group)
		{
			ReplacedClip = replacement;
			ReplacedWith = group;
			IsUpdateEveryFrame = group.Parent.UpdateEveryFrame;
		}
	}
	internal static class SoundReplacementHandler
	{
		private const int TOKEN_PARENT_NAME = 0;

		private const int TOKEN_OBJECT_NAME = 1;

		private const int TOKEN_CLIP_NAME = 2;

		private static readonly string[] _suffixesToRemove = new string[1] { "(Clone)" };

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

		private static readonly StringBuilder _builder = new StringBuilder();

		private static string[] _workingName = Array.Empty<string>();

		internal static void Register()
		{
			SceneManager.sceneLoaded += delegate
			{
				_cachedObjectNames.Clear();
			};
		}

		private static bool ShouldBeReplaced(in AudioSourcePlayEvent @event)
		{
			if (!Object.op_Implicit((Object)(object)((Component)@event.Source).gameObject))
			{
				return false;
			}
			if (@event.Data.ReplacedWith != null && @event.Data.ReplacedWith.Parent.UpdateEveryFrame)
			{
				return false;
			}
			return !@event.Data.DisableReplacing;
		}

		internal static bool TryReplaceAudio(in AudioSourcePlayEvent @event, [NotNullWhen(true)] out ReplacementResult? result)
		{
			result = null;
			if (!ShouldBeReplaced(in @event))
			{
				return false;
			}
			string[] name = ArrayPool<string>.Shared.Rent(3);
			if (!TryProcessName(ref name, @event.Source, @event.Clip) || !TryGetReplacementClip(name, out var group, out var clip, @event.Context ?? DefaultConditionContext.DEFAULT))
			{
				ArrayPool<string>.Shared.Return(name);
				return false;
			}
			ArrayPool<string>.Shared.Return(name);
			((Object)clip).name = group.Pack.Name + " " + ((Object)@event.Clip).name;
			result = new ReplacementResult(clip, group);
			@event.Data.ReplacedWith = group;
			if (result.Value.IsUpdateEveryFrame)
			{
				Debuggers.UpdateEveryFrame?.Log($"swapped to a clip that uses update_every_frame !!! isOneShot = {@event.IsOneShot}");
			}
			return true;
		}

		[Obsolete]
		internal static bool TryReplaceAudio(AudioSource source, AudioClip clip, out AudioClip replacement)
		{
			if (TryReplaceAudio(new AudioSourcePlayEvent(source, clip, isOneShot: false), out var result))
			{
				replacement = result.Value.ReplacedClip;
				return true;
			}
			replacement = null;
			return false;
		}

		private static string TrimObjectName(GameObject gameObject)
		{
			if (_cachedObjectNames.ContainsKey(((object)gameObject).GetHashCode()))
			{
				return _cachedObjectNames[((object)gameObject).GetHashCode()];
			}
			_builder.Clear();
			_builder.Append(((Object)gameObject).name);
			string[] suffixesToRemove = _suffixesToRemove;
			foreach (string oldValue in suffixesToRemove)
			{
				_builder.Replace(oldValue, string.Empty);
			}
			for (int j = 0; j < _builder.Length; j++)
			{
				if (_builder[j] == '(')
				{
					int num = j;
					for (j++; j < _builder.Length && char.IsDigit(_builder[j]); j++)
					{
					}
					if (j < _builder.Length && _builder[j] == ')')
					{
						_builder.Remove(num, j - num + 1);
						j = num - 1;
					}
				}
			}
			int num2 = _builder.Length;
			while (num2 > 0 && _builder[num2 - 1] == ' ')
			{
				num2--;
			}
			_builder.Remove(num2, _builder.Length - num2);
			string text = _builder.ToString();
			_cachedObjectNames[((object)gameObject).GetHashCode()] = text;
			return text;
		}

		private static bool TryProcessName(ref string[] name, AudioSource source, AudioClip clip)
		{
			if ((Object)(object)clip == (Object)null)
			{
				return false;
			}
			if ((Object)(object)((Component)source).transform.parent == (Object)null)
			{
				name[0] = "*";
			}
			else
			{
				name[0] = TrimObjectName(((Component)((Component)source).transform.parent).gameObject);
			}
			name[1] = TrimObjectName(((Component)source).gameObject);
			name[2] = ((Object)clip).name;
			if (SoundReportHandler.CurrentReport != null)
			{
				string caller;
				try
				{
					caller = new StackTrace(fNeedFileInfo: true).GetFrame(5).GetMethod().DeclaringType.Name;
				}
				catch
				{
					caller = "unknown caller";
				}
				SoundReport.PlayedSound playedSound = new SoundReport.PlayedSound(name[0] + ":" + name[1] + ":" + name[2], caller, source.playOnAwake);
				if (!SoundReportHandler.CurrentReport.PlayedSounds.Any(playedSound.Equals))
				{
					SoundReportHandler.CurrentReport.PlayedSounds.Add(playedSound);
				}
			}
			Debuggers.MatchStrings?.Log(name[0] + ":" + name[1] + ":" + name[2]);
			return true;
		}

		private static bool TryGetReplacementClip(string[] name, out SoundReplacementGroup group, out AudioClip clip, IContext context)
		{
			group = null;
			clip = null;
			if (name == null)
			{
				return false;
			}
			Debuggers.SoundReplacementHandler?.Log("beginning replacement attempt for " + name[2]);
			if (!SoundPackDataHandler.SoundReplacements.TryGetValue(name[2], out var value))
			{
				return false;
			}
			Debuggers.SoundReplacementHandler?.Log("sound dictionary hit");
			value = value.Where((SoundReplacementGroup it) => it.Parent.Evaluate(context) && it.Evaluate(context) && CheckGroupMatches(it, name)).ToList();
			if (value.Count == 0)
			{
				return false;
			}
			Debuggers.SoundReplacementHandler?.Log("sound group that matches");
			group = value[Random.Range(0, value.Count)];
			List<SoundInstance> list = group.Sounds.Where((SoundInstance it) => it.Evaluate(context)).ToList();
			if (list.Count == 0)
			{
				return false;
			}
			Debuggers.SoundReplacementHandler?.Log("has valid sounds");
			int totalWeight = 0;
			list.ForEach(delegate(SoundInstance replacement)
			{
				totalWeight += replacement.Weight;
			});
			int num = Random.Range(0, totalWeight + 1);
			SoundInstance soundInstance = null;
			foreach (SoundInstance item in list)
			{
				soundInstance = item;
				num -= soundInstance.Weight;
				if (num <= 0)
				{
					break;
				}
			}
			clip = soundInstance.Clip;
			Debuggers.SoundReplacementHandler?.Log("done, dumping stack trace!");
			Debuggers.SoundReplacementHandler?.Log(string.Join(", ", group.Matches));
			Debuggers.SoundReplacementHandler?.Log(((Object)clip).name);
			Debuggers.SoundReplacementHandler?.Log(new StackTrace(fNeedFileInfo: true).ToString().Trim());
			return true;
		}

		private static bool CheckGroupMatches(SoundReplacementGroup group, string[] a)
		{
			foreach (string match in group.Matches)
			{
				if (MatchStrings(a, match))
				{
					return true;
				}
			}
			return false;
		}

		private static bool MatchStrings(string[] a, string b)
		{
			string[] array = b.Split(":");
			if (array[0] != "*" && array[0] != a[0])
			{
				return false;
			}
			if (array[1] != "*" && array[1] != a[1])
			{
				return false;
			}
			return a[2] == array[2];
		}
	}
}
namespace loaforcsSoundAPI.SoundPacks.Data
{
	public interface IPackData
	{
		SoundPack Pack { get; internal set; }
	}
	public class SoundInstance : Conditional
	{
		[field: NonSerialized]
		public SoundReplacementGroup Parent { get; internal set; }

		public string Sound { get; private set; }

		public int Weight { get; private set; }

		[field: NonSerialized]
		public AudioClip Clip { get; internal set; }

		public override SoundPack Pack
		{
			get
			{
				return Parent.Pack;
			}
			set
			{
				if (Parent.Pack != null)
				{
					throw new InvalidOperationException("Pack has already been set.");
				}
				Parent.Pack = value;
			}
		}

		[JsonConstructor]
		internal SoundInstance()
		{
		}

		public SoundInstance(SoundReplacementGroup parent, int weight, AudioClip clip)
		{
			Parent = parent;
			Weight = weight;
			Clip = clip;
			parent.AddSoundReplacement(this);
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			List<IValidatable.ValidationResult> list = base.Validate();
			if (!File.Exists(Path.Combine(Pack.PackFolder, "sounds", Sound)))
			{
				list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Sound '" + Sound + "' couldn't be found or doesn't exist!"));
			}
			else if (!SoundPackLoadPipeline.audioExtensions.ContainsKey(Path.GetExtension(Sound)))
			{
				list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Audio type: '" + Path.GetExtension(Sound) + "' is not supported!"));
			}
			return list;
		}
	}
	public class SoundPack : IValidatable
	{
		[NonSerialized]
		private readonly Dictionary<string, object> _configData = new Dictionary<string, object>();

		private ManualLogSource _logger;

		[JsonProperty]
		private Dictionary<string, JObject> config { get; set; }

		public string Name { get; private set; }

		public string GUID => "soundpack." + Name;

		[CanBeNull]
		public string Version { get; private set; }

		public string PackFolder { get; internal set; }

		[field: NonSerialized]
		public List<SoundReplacementCollection> ReplacementCollections { get; private set; } = new List<SoundReplacementCollection>();

		public ManualLogSource Logger
		{
			get
			{
				if (_logger == null)
				{
					_logger = Logger.CreateLogSource(GUID);
				}
				return _logger;
			}
		}

		[JsonConstructor]
		internal SoundPack()
		{
		}

		internal void Bind(ConfigFile file)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Invalid comparison between Unknown and I4
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Invalid comparison between Unknown and I4
			if (config == null || config.Count == 0)
			{
				return;
			}
			loaforcsSoundAPI.Logger.LogDebug((object)"handling config");
			JToken val2 = default(JToken);
			foreach (KeyValuePair<string, JObject> item in config)
			{
				string[] array = item.Key.Split(":");
				string text = array[0];
				string text2 = array[1];
				JToken val = item.Value["default"];
				string text3 = (item.Value.TryGetValue("description", ref val2) ? ((object)val2).ToString() : "no description defined!");
				JTokenType type = val.Type;
				if ((int)type != 8)
				{
					if ((int)type != 9)
					{
						throw new NotImplementedException("WHAT");
					}
					_configData[item.Key] = file.Bind<bool>(text, text2, (bool)val, text3).Value;
				}
				else
				{
					_configData[item.Key] = file.Bind<string>(text, text2, (string)val, text3).Value;
				}
			}
		}

		public SoundPack(string name, string packFolder)
		{
			Name = name;
			PackFolder = packFolder;
		}

		internal bool TryGetConfigValue(string id, out object returnValue)
		{
			returnValue = null;
			if (!_configData.TryGetValue(id, out var value))
			{
				return false;
			}
			returnValue = value;
			return true;
		}

		public List<IValidatable.ValidationResult> Validate()
		{
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Invalid comparison between Unknown and I4
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Invalid comparison between Unknown and I4
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			List<IValidatable.ValidationResult> list = new List<IValidatable.ValidationResult>();
			if (string.IsNullOrEmpty(Name))
			{
				list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'name' can not be missing or empty!"));
				return list;
			}
			string name = Name;
			foreach (char c in name)
			{
				if (!char.IsLetter(c) && c != '_')
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, $"'name' can not contain special character '{c}'!"));
				}
			}
			if (string.IsNullOrEmpty(Version) && PackLoadingConfig.MetadataSpoofing)
			{
				list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.WARN, "'version' should not be empty, defaulting to '1.0.0' (needed by MetadataSpoofing config)"));
			}
			if (config == null)
			{
				return list;
			}
			JToken val = default(JToken);
			foreach (KeyValuePair<string, JObject> item in config)
			{
				string[] array = item.Key.Split(":");
				if (array.Length != 2)
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + item.Key + "' is not a valid key for config! It must be 'section:name' with exactly one colon!"));
				}
				if (!item.Value.TryGetValue("default", ref val))
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + item.Key + "' does not have a 'default' value! This is needed to get what type the config is!"));
				}
				else if ((int)val.Type != 9 && (int)val.Type != 8)
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, $"'{item.Key}' is of unsupported type: '{val.Type}'! Only supported types are strings/text or booleans!"));
				}
				if (!item.Value.ContainsKey("description"))
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.WARN, "'" + item.Key + "' does not have a description."));
				}
			}
			return list;
		}
	}
	public class SoundReplacementCollection : Conditional, IFilePathAware, IPackData
	{
		[field: NonSerialized]
		public override SoundPack Pack { get; set; }

		public bool UpdateEveryFrame { get; private set; }

		public bool Synced { get; private set; }

		public List<SoundReplacementGroup> Replacements { get; private set; } = new List<SoundReplacementGroup>();

		public string FilePath { get; set; }

		[JsonConstructor]
		internal SoundReplacementCollection()
		{
		}

		public SoundReplacementCollection(SoundPack pack)
		{
			Pack = pack;
			pack.ReplacementCollections.Add(this);
		}

		internal void AddSoundReplacementGroup(SoundReplacementGroup group)
		{
			Replacements.Add(group);
		}
	}
	public class SoundReplacementGroup : Conditional
	{
		[field: NonSerialized]
		public SoundReplacementCollection Parent { get; internal set; }

		public List<string> Matches { get; private set; }

		public List<SoundInstance> Sounds { get; private set; } = new List<SoundInstance>();

		public override SoundPack Pack
		{
			get
			{
				return Parent.Pack;
			}
			set
			{
				if (Parent.Pack != null)
				{
					throw new InvalidOperationException("Pack has already been set.");
				}
				Parent.Pack = value;
			}
		}

		[JsonConstructor]
		internal SoundReplacementGroup()
		{
		}

		public SoundReplacementGroup(SoundReplacementCollection parent, List<string> matches)
		{
			Parent = parent;
			Matches = matches;
			if (SoundPackDataHandler.LoadedPacks.Contains(parent.Pack))
			{
				throw new InvalidOperationException("SoundPack has already been registered, trying to add a new SoundReplacementGroup does not work!");
			}
			parent.AddSoundReplacementGroup(this);
		}

		internal void AddSoundReplacement(SoundInstance sound)
		{
			Sounds.Add(sound);
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			List<IValidatable.ValidationResult> list = base.Validate();
			foreach (string match in Matches)
			{
				if (string.IsNullOrEmpty(match))
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Match string can not be empty!"));
					continue;
				}
				string[] array = match.Split(":");
				if (array.Length == 1)
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + match + "' is not valid! If you mean to match to all Audio clips with this name you must explicitly do '*:" + match + "'."));
				}
				if (array.Length > 3)
				{
					list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.WARN, $"'{match}' has more than 3 parts! SoundAPI will handle this as '{match[0]}:{match[1]}:{match[2]}', discarding the rest!"));
				}
			}
			return list;
		}
	}
}
namespace loaforcsSoundAPI.SoundPacks.Data.Conditions
{
	public abstract class Condition : IValidatable
	{
		[field: NonSerialized]
		public Conditional Parent { get; internal set; }

		protected SoundPack Pack => Parent.Pack;

		public bool? Constant { get; private set; }

		protected internal virtual void OnRegistered()
		{
		}

		public abstract bool Evaluate(IContext context);

		public virtual List<IValidatable.ValidationResult> Validate()
		{
			return new List<IValidatable.ValidationResult>();
		}

		protected bool EvaluateRangeOperator(int number, string condition)
		{
			return EvaluateRangeOperator((double)number, condition);
		}

		protected bool EvaluateRangeOperator(float number, string condition)
		{
			return EvaluateRangeOperator((double)number, condition);
		}

		protected bool EvaluateRangeOperator(double value, string condition)
		{
			string[] array = condition.Split("..");
			if (array.Length == 1)
			{
				if (double.TryParse(array[0], out var result))
				{
					return value == result;
				}
				return false;
			}
			if (array.Length == 2)
			{
				double result2;
				if (array[0] == "")
				{
					result2 = double.MinValue;
				}
				else if (!double.TryParse(array[0], out result2))
				{
					return false;
				}
				double result3;
				if (array[1] == "")
				{
					result3 = double.MaxValue;
				}
				else if (!double.TryParse(array[1], out result3))
				{
					return false;
				}
				if (value >= result2)
				{
					return value <= result3;
				}
				return false;
			}
			return false;
		}

		protected bool ValidateRangeOperator(string condition, out IValidatable.ValidationResult result)
		{
			result = null;
			if (string.IsNullOrEmpty(condition))
			{
				result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Range operator can not be missing or empty!");
				return false;
			}
			string[] array = condition.Split("..");
			int num = array.Length;
			if (num <= 2)
			{
				switch (num)
				{
				case 1:
				{
					if (!double.TryParse(array[0], out var _))
					{
						result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Failed to parse: '" + array[0] + "' as a number!");
					}
					break;
				}
				case 2:
				{
					double num2;
					if (array[0] == "")
					{
						num2 = double.MinValue;
					}
					else if (!double.TryParse(array[0], out num2))
					{
						result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Failed to parse: '" + array[0] + "' as a number!");
					}
					double num3;
					if (array[1] == "")
					{
						num3 = double.MaxValue;
					}
					else if (!double.TryParse(array[1], out num3))
					{
						result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Failed to parse: '" + array[1] + "' as a number!");
					}
					break;
				}
				}
			}
			else
			{
				result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Range operator: '" + condition + "' uses .. more than once!");
			}
			return result == null;
		}

		protected static void LogDebug(string name, object message)
		{
			Debuggers.ConditionsInfo?.Log($"({name}) {message}");
		}
	}
	internal sealed class InvalidCondition(string type) : Condition()
	{
		public override bool Evaluate(IContext context)
		{
			return false;
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			if (string.IsNullOrEmpty(type))
			{
				return new List<IValidatable.ValidationResult>(1)
				{
					new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Condition must have a type!")
				};
			}
			return new List<IValidatable.ValidationResult>(1)
			{
				new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + type + "' is not a valid condition type!")
			};
		}
	}
	internal sealed class ConstantCondition : Condition
	{
		public static ConstantCondition TRUE = new ConstantCondition(constant: true);

		public static ConstantCondition FALSE = new ConstantCondition(constant: false);

		public bool Value { get; private set; }

		private ConstantCondition(bool constant)
		{
			Value = constant;
		}

		public override bool Evaluate(IContext context)
		{
			return Value;
		}
	}
	public abstract class Condition<TContext> : Condition where TContext : IContext
	{
		public override bool Evaluate(IContext context)
		{
			if (!(context is TContext context2))
			{
				return EvaluateFallback(context);
			}
			return EvaluateWithContext(context2);
		}

		protected abstract bool EvaluateWithContext(TContext context);

		protected virtual bool EvaluateFallback(IContext context)
		{
			return false;
		}
	}
	public abstract class Conditional : IValidatable, IPackData
	{
		public Condition Condition { get; set; }

		public abstract SoundPack Pack { get; set; }

		public bool Evaluate(IContext context)
		{
			if (Condition == null)
			{
				return true;
			}
			return Condition.Evaluate(context);
		}

		public virtual List<IValidatable.ValidationResult> Validate()
		{
			if (Condition == null)
			{
				return new List<IValidatable.ValidationResult>();
			}
			Condition.Parent = this;
			Condition.OnRegistered();
			return Condition.Validate();
		}
	}
	public interface IContext
	{
	}
	internal class DefaultConditionContext : IContext
	{
		internal static readonly DefaultConditionContext DEFAULT = new DefaultConditionContext();

		private DefaultConditionContext()
		{
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	[MeansImplicitUse]
	public class SoundAPIConditionAttribute(string id, bool deprecated = false, string deprecationReason = null) : Attribute()
	{
		public string ID { get; private set; } = id;

		public bool IsDeprecated { get; private set; } = deprecated;

		public string DeprecationReason { get; private set; } = deprecationReason;
	}
}
namespace loaforcsSoundAPI.SoundPacks.Conditions
{
	public abstract class LogicGateCondition : Condition
	{
		public abstract Condition[] Conditions { get; protected set; }

		protected abstract string ValidateWarnMessage { get; }

		protected internal override void OnRegistered()
		{
			Condition[] conditions = Conditions;
			foreach (Condition condition in conditions)
			{
				condition.Parent = base.Parent;
				condition.OnRegistered();
			}
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			if (Conditions.Length == 0)
			{
				return new List<IValidatable.ValidationResult>(1)
				{
					new IValidatable.ValidationResult(IValidatable.ResultType.WARN, ValidateWarnMessage)
				};
			}
			return new List<IValidatable.ValidationResult>();
		}

		protected static bool And(Condition[] conditions, IContext context)
		{
			foreach (Condition condition in conditions)
			{
				if (condition is InvalidCondition)
				{
					return false;
				}
				if (!condition.Evaluate(context))
				{
					return false;
				}
			}
			return true;
		}

		protected static bool Or(Condition[] conditions, IContext context)
		{
			foreach (Condition condition in conditions)
			{
				if (condition is InvalidCondition)
				{
					return false;
				}
				if (condition.Evaluate(context))
				{
					return true;
				}
			}
			return false;
		}
	}
	[SoundAPICondition("and", false, null)]
	internal class AndCondition : LogicGateCondition
	{
		public override Condition[] Conditions { get; protected set; }

		protected override string ValidateWarnMessage => "'and' condition has no conditions and will always return true!";

		public override bool Evaluate(IContext context)
		{
			return LogicGateCondition.And(Conditions, context);
		}
	}
	[SoundAPICondition("nand", false, null)]
	internal class NandCondition : LogicGateCondition
	{
		public override Condition[] Conditions { get; protected set; }

		protected override string ValidateWarnMessage => "'nand' condition has no conditions and will always return false!";

		public override bool Evaluate(IContext context)
		{
			return !LogicGateCondition.And(Conditions, context);
		}
	}
	[SoundAPICondition("config", false, null)]
	internal class ConfigCondition : Condition
	{
		public string Config { get; private set; }

		public object Value { get; private set; }

		public override bool Evaluate(IContext context)
		{
			if (!base.Pack.TryGetConfigValue(Config, out var returnValue))
			{
				return false;
			}
			if (Value == null)
			{
				if (returnValue is bool)
				{
					return (bool)returnValue;
				}
				if (returnValue is string value)
				{
					return string.IsNullOrEmpty(value);
				}
				return false;
			}
			if (returnValue is bool flag)
			{
				return flag == (bool)Value;
			}
			if (returnValue is string text)
			{
				return text == (string)Value;
			}
			return false;
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			if (!base.Pack.TryGetConfigValue(Config, out var returnValue))
			{
				List<IValidatable.ValidationResult> list = new List<IValidatable.ValidationResult>(1);
				list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Config '" + Config + "' does not exist on SoundPack '" + base.Pack.Name + "'"));
				return list;
			}
			if (Value != null && returnValue.GetType() != Value.GetType())
			{
				return new List<IValidatable.ValidationResult>(1)
				{
					new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, $"Config '{Config}' has a type of: '{returnValue.GetType()}' but the Value type is '{Value.GetType()}'!")
				};
			}
			return new List<IValidatable.ValidationResult>();
		}
	}
	[SoundAPICondition("counter", false, null)]
	public class CounterCondition : Condition
	{
		private int _count;

		public string Value { get; private set; }

		public int? ResetsAt { get; private set; }

		public override bool Evaluate(IContext context)
		{
			Condition.LogDebug("counter", $"counting: {_count} -> {_count + 1}");
			_count++;
			bool flag = EvaluateRangeOperator(_count, Value);
			Condition.LogDebug("counter", $"is {_count} in range ({Value})? {flag}");
			if (_count >= ResetsAt)
			{
				_count = 0;
				Condition.LogDebug("counter", "reset count to 0.");
			}
			return flag;
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			if (!ValidateRangeOperator(Value, out var result))
			{
				return new List<IValidatable.ValidationResult>(1) { result };
			}
			return new List<IValidatable.ValidationResult>();
		}
	}
	[SoundAPICondition("mod_installed", false, null)]
	internal class ModInstalledCondition : Condition
	{
		public string Value { get; private set; }

		public override bool Evaluate(IContext context)
		{
			return Chainloader.PluginInfos.ContainsKey(Value);
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			if (string.IsNullOrEmpty(Value))
			{
				return new List<IValidatable.ValidationResult>(1)
				{
					new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Value on 'mod_installed' must be there and must not be empty.")
				};
			}
			return new List<IValidatable.ValidationResult>();
		}
	}
	[SoundAPICondition("not", false, null)]
	internal class NotCondition : Condition
	{
		public Condition Condition { get; private set; }

		protected internal override void OnRegistered()
		{
			if (Condition != null)
			{
				Condition.Parent = base.Parent;
				Condition.OnRegistered();
			}
		}

		public override bool Evaluate(IContext context)
		{
			if (Condition is InvalidCondition)
			{
				return false;
			}
			return !Condition.Evaluate(context);
		}

		public override List<IValidatable.ValidationResult> Validate()
		{
			if (Condition == null)
			{
				return new List<IValidatable.ValidationResult>(1)
				{
					new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'not' condition has no valid condition to invert!")
				};
			}
			return new List<IValidatable.ValidationResult>();
		}
	}
	[SoundAPICondition("or", false, null)]
	internal class OrCondition : LogicGateCondition
	{
		public override Condition[] Conditions { get; protected set; }

		protected override string ValidateWarnMessage => "'or' condition has no conditions and will always return false!";

		public override bool Evaluate(IContext context)
		{
			return LogicGateCondition.Or(Conditions, context);
		}
	}
	[SoundAPICondition("nor", false, null)]
	internal class NorCondition : LogicGateCondition
	{
		public override Condition[] Conditions { get; protected set; }

		protected override string ValidateWarnMessage => "'nor' condition has no conditions and will always return true!";

		public override bool Evaluate(IContext context)
		{
			return !LogicGateCondition.Or(Conditions, context);
		}
	}
}
namespace loaforcsSoundAPI.Reporting
{
	public static class SoundReportHandler
	{
		private const string _datetimeFormat = "dd_MM_yyyy-HH_mm";

		private static Action<StreamWriter, SoundReport> _reportSections = delegate
		{
		};

		public static SoundReport CurrentReport { get; private set; }

		public static void AddReportSection(string header, Action<StreamWriter, SoundReport> callback)
		{
			_reportSections = (Action<StreamWriter, SoundReport>)Delegate.Combine(_reportSections, (Action<StreamWriter, SoundReport>)delegate(StreamWriter stream, SoundReport report)
			{
				stream.WriteLine("## " + header);
				callback(stream, report);
				stream.WriteLine("");
				stream.WriteLine("");
			});
		}

		internal static void Register()
		{
			Directory.CreateDirectory(GetFolder());
			CurrentReport = new SoundReport();
			loaforcsSoundAPI.Logger.LogWarning((object)"SoundAPI is generating a report!");
			loaforcsSoundAPI.Logger.LogInfo((object)("The report will be located at '" + LogFormats.FormatFilePath(Path.Combine(GetFolder(), GetFileName(CurrentReport, ".md")))));
			Application.quitting += delegate
			{
				WriteReportToFile(CurrentReport);
			};
			SoundPackLoadPipeline.OnFinishedPipeline += delegate
			{
				foreach (SoundPack loadedPack in SoundPackDataHandler.LoadedPacks)
				{
					CurrentReport.SoundPackNames.Add(loadedPack.Name);
				}
			};
			AddReportSection("General Information", delegate(StreamWriter stream, SoundReport report)
			{
				stream.WriteLine("Game name: `" + Application.productName + "` `v" + Application.version + "` by `" + Application.companyName + "`<br/>");
				stream.WriteLine("Unity version: `" + Application.unityVersion + "<br/>");
				stream.WriteLine($"Native Backend supported: `{NativeBackend.TryGetSettings(out var _)}`, enabled: `{NativeBackend.Enabled}` <br/>");
				stream.WriteLine("SoundAPI version: `2.0.13` <br/><br/>");
				stream.WriteLine($"Audio-clips loaded: `{report.AudioClipsLoaded}` <br/>");
				stream.WriteLine($"Match strings registered: `{SoundPackDataHandler.SoundReplacements.Values.Sum((List<SoundReplacementGroup> it) => it.Count)}` <br/>");
				WriteList("Loaded sound-packs", stream, report.SoundPackNames);
			});
			AddReportSection("Dynamic Data", delegate(StreamWriter stream, SoundReport _)
			{
				if (SoundAPI.CurrentNetworkAdapter != null)
				{
					stream.WriteLine("Network Adapter: `" + SoundAPI.CurrentNetworkAdapter.Name + "` <br/><br/>");
				}
				WriteList("Registered Conditions", stream, SoundPackDataHandler.conditionFactories.Keys.ToList());
			});
			AddReportSection("All Played Sounds", delegate(StreamWriter stream, SoundReport report)
			{
				WriteList(null, stream, report.PlayedSounds.Select((SoundReport.PlayedSound it) => it.FormatForReport()).ToList());
			});
			AddReportSection("Native Backend", delegate
			{
			});
		}

		internal static void Bind(ConfigFile file)
		{
			if (file.Bind<bool>("Developer", "GenerateReports", false, "While true SoundAPI will generate a json and markdown file per session that records information SoundAPI and related mods find.").Value)
			{
				Register();
			}
		}

		private static string GetFileName(SoundReport report, string extension)
		{
			return "generated_report-" + report.StartedAt.ToString("dd_MM_yyyy-HH_mm") + extension;
		}

		private static string GetFolder()
		{
			return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "reports");
		}

		private static void WriteReportToFile(SoundReport report)
		{
			using StreamWriter streamWriter = new StreamWriter(Path.Combine(GetFolder(), GetFileName(report, ".md")));
			streamWriter.WriteLine("# Generated Report");
			streamWriter.WriteLine($"At {report.StartedAt} :3");
			streamWriter.WriteLine("");
			_reportSections(streamWriter, report);
			streamWriter.Flush();
			streamWriter.Close();
			using StreamWriter streamWriter2 = new StreamWriter(Path.Combine(GetFolder(), GetFileName(report, ".json")));
			streamWriter2.WriteLine(JsonConvert.SerializeObject((object)report, (Formatting)1));
		}

		public static void WriteList(string header, StreamWriter stream, ICollection<string> list)
		{
			if (!string.IsNullOrEmpty(header))
			{
				stream.WriteLine($"### {header} (`{list.Count}`)");
			}
			stream.WriteLine(string.Join("<br/>\n", list.Select((string it) => "- " + it)));
		}

		public static void WriteEnum<T>(string header, StreamWriter stream) where T : Enum
		{
			WriteList(header, stream, (from it in Enum.GetValues(typeof(T)).OfType<T>()
				select it.ToString().ToLowerInvariant()).ToList());
		}
	}
}
namespace loaforcsSoundAPI.Reporting.Data
{
	public class SoundReport
	{
		public class PlayedSound(string matchString, string caller, bool isPlayOnAwake)
		{
			public string MatchString { get; private set; } = matchString;

			public string Caller { get; private set; } = caller;

			public bool IsPlayOnAwake { get; private set; } = isPlayOnAwake;

			public override bool Equals(object obj)
			{
				if (!(obj is PlayedSound other))
				{
					return false;
				}
				return Equals(other);
			}

			protected bool Equals(PlayedSound other)
			{
				if (MatchString == other.MatchString && Caller == other.Caller)
				{
					return IsPlayOnAwake == other.IsPlayOnAwake;
				}
				return false;
			}

			public override int GetHashCode()
			{
				return HashCode.Combine(MatchString, Caller, IsPlayOnAwake);
			}

			public string FormatForReport()
			{
				return $"Match String: {MatchString}, Caller: {Caller}, IsPlayOnAwake: {IsPlayOnAwake}";
			}
		}

		public DateTime StartedAt { get; private set; } = DateTime.Now;

		public List<PlayedSound> PlayedSounds { get; private set; } = new List<PlayedSound>();

		public List<string> SoundPackNames { get; private set; } = new List<string>();

		public int AudioClipsLoaded { get; set; }
	}
}
namespace loaforcsSoundAPI.Core
{
	public class AudioSourceAdditionalData
	{
		private SoundReplacementGroup _replacedWith;

		public AudioSource Source { get; private set; }

		public AudioClip OriginalClip { get; internal set; }

		public AudioClip RealClip
		{
			get
			{
				using (new SpoofBypassContext())
				{
					if (Debuggers.AudioSourceAdditionalData != null)
					{
						string text = "null";
						if (Object.op_Implicit((Object)(object)Source.clip))
						{
							text = ((Object)Source.clip).name;
						}
						string text2 = "null";
						if (Object.op_Implicit((Object)(object)OriginalClip))
						{
							text2 = ((Object)OriginalClip).name;
						}
						Debuggers.AudioSourceAdditionalData.Log("(" + ((Object)Source).name + ") Getting real clip: " + text + " (original clip: " + text2 + ")");
					}
					return Source.clip;
				}
			}
			set
			{
				using (new SpoofBypassContext())
				{
					if (Debuggers.AudioSourceAdditionalData != null)
					{
						string text = "null";
						if (Object.op_Implicit((Object)(object)OriginalClip))
						{
							text = ((Object)OriginalClip).name;
						}
						Debuggers.AudioSourceAdditionalData?.Log("(" + ((Object)Source).name + ") Setting real clip: " + ((Object)value).name + " (original clip: " + text + ")");
					}
					Source.clip = value;
				}
			}
		}

		internal SoundReplacementGroup ReplacedWith
		{
			get
			{
				return _replacedWith;
			}
			set
			{
				_replacedWith = value;
				if (RequiresUpdateFunction())
				{
					if (!SoundAPIAudioManager.liveAudioSourceData.Contains(this))
					{
						SoundAPIAudioManager.liveAudioSourceData.Add(this);
					}
				}
				else if (SoundAPIAudioManager.liveAudioSourceData.Contains(this))
				{
					SoundAPIAudioManager.liveAudioSourceData.Remove(this);
				}
			}
		}

		public bool DisableReplacing { get; set; }

		public IContext CurrentContext { get; set; }

		internal AudioSourceAdditionalData(AudioSource source)
		{
			Source = source;
		}

		internal void Update()
		{
			if (RequiresUpdateFunction() && AudioSourceIsPlaying())
			{
				Debuggers.UpdateEveryFrame?.Log("success: updating every frame for " + ((Object)Source).name);
				IContext context = CurrentContext ?? DefaultConditionContext.DEFAULT;
				SoundInstance soundInstance = ReplacedWith.Sounds.FirstOrDefault((SoundInstance x) => x.Evaluate(context));
				if (soundInstance != null && !((Object)(object)soundInstance.Clip == (Object)(object)Source.clip))
				{
					Debuggers.UpdateEveryFrame?.Log("new clip found, swapping!!");
					float time = Source.time;
					Source.clip = soundInstance.Clip;
					Source.Play();
					Source.time = time;
					Debuggers.UpdateEveryFrame?.Log("new clip found, swapped");
				}
			}
		}

		private bool RequiresUpdateFunction()
		{
			if (ReplacedWith != null)
			{
				return ReplacedWith.Parent.UpdateEveryFrame;
			}
			return false;
		}

		private bool AudioSourceIsPlaying()
		{
			if (Object.op_Implicit((Object)(object)Source) && ((Behaviour)Source).enabled)
			{
				return Source.isPlaying;
			}
			return false;
		}

		public static AudioSourceAdditionalData GetOrCreate(AudioSource source)
		{
			if (SoundAPIAudioManager.audioSourceData.TryGetValue(source, out var value))
			{
				return value;
			}
			value = new AudioSourceAdditionalData(source);
			value.OriginalClip = value.RealClip;
			SoundAPIAudioManager.audioSourceData[source] = value;
			Debuggers.AudioSourceAdditionalData?.Log($"created {((Object)((Component)source).gameObject).name} = {((Object)source).m_CachedPtr.ToInt64()}");
			return value;
		}

		internal static bool TryGet(AudioSource source, out AudioSourceAdditionalData data)
		{
			return SoundAPIAudioManager.audioSourceData.TryGetValue(source, out data);
		}
	}
	internal static class Debuggers
	{
		internal static DebugLogSource AudioSourceAdditionalData;

		internal static DebugLogSource SoundReplacementLoader;

		internal static DebugLogSource SoundReplacementHandler;

		internal static DebugLogSource MatchStrings;

		internal static DebugLogSource ConditionsInfo;

		internal static DebugLogSource UpdateEveryFrame;

		internal static DebugLogSource AudioClipSpoofing;

		internal static DebugLogSource NativeBackend;

		internal static void Bind(ConfigFile file)
		{
			FieldInfo[] fields = typeof(Debuggers).GetFields(BindingFlags.Static | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (file.Bind<bool>("InternalDebugging", fieldInfo.Name, false, "Enable/Disable this DebugLogSource. Should only be true if you know what you are doing or have been asked to.").Value)
				{
					fieldInfo.SetValue(null, new DebugLogSource(fieldInfo.Name));
					loaforcsSoundAPI.Logger.LogDebug((object)("created a DebugLogSource for " + fieldInfo.Name + "!"));
				}
				else
				{
					fieldInfo.SetValue(null, null);
					loaforcsSoundAPI.Logger.LogDebug((object)("no DebugLogSource for " + fieldInfo.Name + "."));
				}
			}
		}
	}
	internal class DebugLogSource(string title)
	{
		internal void Log(object message)
		{
			loaforcsSoundAPI.Logger.LogDebug((object)$"[Debug-{title}] {message}");
		}
	}
	internal class SoundAPIAudioManager : MonoBehaviour
	{
		internal static readonly Dictionary<AudioSource, AudioSourceAdditionalData> audioSourceData = new Dictionary<AudioSource, AudioSourceAdditionalData>();

		internal static readonly List<AudioSourceAdditionalData> liveAudioSourceData = new List<AudioSourceAdditionalData>();

		private static SoundAPIAudioManager Instance;

		private void Awake()
		{
			SceneManager.sceneLoaded += delegate
			{
				if (!Object.op_Implicit((Object)(object)Instance))
				{
					SpawnManager();
				}
			};
		}

		internal static void SpawnManager()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			loaforcsSoundAPI.Logger.LogInfo((object)"Starting AudioManager.");
			GameObject val = new GameObject("SoundAPI_AudioManager");
			Object.DontDestroyOnLoad((Object)(object)val);
			Instance = val.AddComponent<SoundAPIAudioManager>();
		}

		private void Update()
		{
			Debuggers.UpdateEveryFrame?.Log("sanity check: soundapi audio manager is running!");
			foreach (AudioSourceAdditionalData liveAudioSourceDatum in liveAudioSourceData)
			{
				liveAudioSourceDatum.Update();
			}
		}

		private void OnDisable()
		{
			loaforcsSoundAPI.Logger.LogDebug((object)"manager disabled");
		}

		private void OnDestroy()
		{
			loaforcsSoundAPI.Logger.LogDebug((object)"manager destroyed");
		}

		internal static void RunCleanup()
		{
			loaforcsSoundAPI.Logger.LogDebug((object)"cleaning up old audio source entries");
			AudioSourceAdditionalData[] array = audioSourceData.Values.ToArray();
			foreach (AudioSourceAdditionalData audioSourceAdditionalData in array)
			{
				if (!Object.op_Implicit((Object)(object)audioSourceAdditionalData.Source))
				{
					Remove(audioSourceAdditionalData);
				}
			}
		}

		internal static void Remove(AudioSourceAdditionalData data)
		{
			if (liveAudioSourceData.Contains(data))
			{
				liveAudioSourceData.Remove(data);
			}
			audioSourceData.Remove(data.Source);
		}
	}
	internal class SpoofBypassContext : IDisposable
	{
		public SpoofBypassContext()
		{
			AudioSourcePatch.bypassSpoofing = true;
		}

		public void Dispose()
		{
			AudioSourcePatch.bypassSpoofing = false;
		}
	}
}
namespace loaforcsSoundAPI.Core.Util
{
	public class AdaptiveConfigEntry
	{
		public AdaptiveBool State { get; private set; }

		public bool DefaultValue { get; private set; }

		public bool? OverrideValue { get; set; }

		public bool Value => State switch
		{
			AdaptiveBool.Enabled => true, 
			AdaptiveBool.Disabled => false, 
			_ => OverrideValue ?? DefaultValue, 
		};

		public AdaptiveConfigEntry(AdaptiveBool state, bool defaultValue)
		{
			State = state;
			DefaultValue = defaultValue;
		}
	}
	public enum AdaptiveBool
	{
		Automatic,
		Enabled,
		Disabled
	}
	internal static class LogFormats
	{
		internal static string FormatFilePath(string path)
		{
			return $"plugins{Path.DirectorySeparatorChar}{Path.Combine(Path.GetRelativePath(Paths.PluginPath, path))}";
		}
	}
}
namespace loaforcsSoundAPI.Core.Util.Extensions
{
	internal static class AssemblyExtensions
	{
		internal static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
		{
			if (assembly == null)
			{
				throw new ArgumentNullException("assembly");
			}
			try
			{
				return assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				return ex.Types.Where((Type t) => t != null);
			}
		}
	}
	public static class AsyncOperationExtensions
	{
		public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
		{
			TaskCompletionSource<AsyncOperation> tcs = new TaskCompletionSource<AsyncOperation>();
			asyncOp.completed += delegate(AsyncOperation operation)
			{
				tcs.SetResult(operation);
			};
			return ((Task)tcs.Task).GetAwaiter();
		}
	}
	public static class AudioSourceExtensions
	{
		public static void PlayThenDestroy(this AudioSource source)
		{
			source.Play();
			Object.Destroy((Object)(object)((Component)source).gameObject, source.clip.length);
		}

		public static void PlayWithoutReplacement(this AudioSource source)
		{
			AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(source);
			orCreate.DisableReplacing = true;
			source.Play();
			orCreate.DisableReplacing = false;
		}
	}
	public static class ConfigFileExtensions
	{
		public static AdaptiveConfigEntry BindAdaptive(this ConfigFile file, string section, string key, bool defaultValue, string description)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			AdaptiveBool value = file.Bind<AdaptiveBool>(section, key, AdaptiveBool.Automatic, new ConfigDescription($"{description}\nAutomatic default: {defaultValue}", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			return new AdaptiveConfigEntry(value, defaultValue);
		}
	}
	public static class ListExtensions
	{
		public static void AddUnique<T>(this List<T> list, T item)
		{
			if (!list.Contains(item))
			{
				list.Add(item);
			}
		}
	}
}
namespace loaforcsSoundAPI.Core.Patches
{
	[HarmonyPatch(typeof(AudioSource))]
	internal static class AudioSourcePatch
	{
		internal static bool bypassSpoofing;

		[HarmonyPrefix]
		[HarmonyPatch("PlayOneShot", new Type[]
		{
			typeof(AudioClip),
			typeof(float)
		})]
		private static bool PlayOneShot(AudioSource __instance, ref AudioClip clip)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)clip))
			{
				return true;
			}
			AudioSourcePlayEvent @event = new AudioSourcePlayEvent(__instance, clip, isOneShot: true);
			if (SoundReplacementHandler.TryReplaceAudio(in @event, out var result))
			{
				if (result.Value.IsUpdateEveryFrame)
				{
					if (PatchConfig.UEFOneShotWorkaround)
					{
						GameObject val = new GameObject("UEFOneShotFix - " + ((Object)clip).name);
						val.transform.SetParent(((Component)__instance).transform, false);
						AudioSource val2 = SoundAPI.CopyAudioSource(__instance, val, AudioSourceCopyFlags.DontCopyPlayOnAwake);
						AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(val2);
						val2.clip = result.Value.ReplacedClip;
						orCreate.ReplacedWith = result.Value.ReplacedWith;
						@event.Data.ReplacedWith = null;
						val2.PlayThenDestroy();
						return false;
					}
					loaforcsSoundAPI.Logger.LogWarning((object)"Replacing a PlayOneShot with a UpdateEveryFrame replacer, things are likely to break. Enable `Experiments -> UEFOneShotFix` to make this warning disappear (and help test it ig)");
				}
				clip = result.Value.ReplacedClip;
			}
			return true;
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPriority(0)]
		[HarmonyPrefix]
		private static void UpdateOriginalClip(AudioSource __instance, AudioClip value, bool __runOriginal)
		{
			if (__runOriginal && !bypassSpoofing)
			{
				AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(__instance);
				orCreate.OriginalClip = value;
				Debuggers.AudioClipSpoofing?.Log("(" + ((Object)((Component)__instance).gameObject).name + ") updating original clip to: " + ((Object)value).name);
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPrefix]
		private static bool PreventClipRestartingWithSpoofed(AudioSource __instance, AudioClip value)
		{
			if (!PatchConfig.AudioClipSpoofing || bypassSpoofing)
			{
				return true;
			}
			AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(__instance);
			if ((Object)(object)orCreate.OriginalClip == (Object)(object)value)
			{
				Debuggers.AudioClipSpoofing?.Log("prevented clip from restarting");
			}
			return (Object)(object)orCreate.OriginalClip != (Object)(object)value;
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		private static void SpoofAudioSourceClip(AudioSource __instance, ref AudioClip __result)
		{
			if (PatchConfig.AudioClipSpoofing && !bypassSpoofing)
			{
				AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(__instance);
				__result = orCreate.OriginalClip;
				Debuggers.AudioClipSpoofing?.Log($"({((Object)((Component)__instance).gameObject).name}) spoofing result to {orCreate.OriginalClip}");
			}
		}
	}
	[HarmonyPatch(typeof(GameObject))]
	internal static class GameObjectPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("AddComponent", new Type[] { typeof(Type) })]
		internal static void NewAudioSource(GameObject __instance, ref Component __result)
		{
			Component obj = __result;
			AudioSource val = (AudioSource)(object)((obj is AudioSource) ? obj : null);
			if (val != null)
			{
				AudioSourceAdditionalData.GetOrCreate(val);
			}
		}
	}
	[HarmonyPatch(typeof(Logger))]
	internal static class LoggerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("LogMessage")]
		private static void ReenableAndSaveConfigs(object data)
		{
			if (data is string text && text == "Chainloader startup complete")
			{
				loaforcsSoundAPI.Logger.LogInfo((object)"Starting Sound-pack loading pipeline");
				SoundPackLoadPipeline.StartPipeline();
			}
		}
	}
	internal static class PatchConfig
	{
		public enum Backend
		{
			HarmonyX,
			NativeBackend
		}

		private const string ExperimentsHeader = "Experiments";

		internal static bool AudioClipSpoofing { get; private set; }

		internal static bool UEFOneShotWorkaround { get; private set; }

		internal static Backend PreferredBackend { get; private set; }

		internal static void Bind(ConfigFile file)
		{
			AudioClipSpoofing = file.Bind<bool>("Advanced", "AudioClipSpoofing", true, "Should SoundAPI spoof the return value of AudioSource.clip? This improves compatibility in most edge cases.").Value;
			PreferredBackend = file.Bind<Backend>("Advanced", "PreferredBackend", Backend.NativeBackend, "What backend should SoundAPI try to use? You should only use this option if you know what it means. Note: NativeBackend needs to be supported on a per unity version basis, if the current version is not supported it will fallback to the old HarmonyX backend automatically.").Value;
			UEFOneShotWorkaround = file.Bind<bool>("Experiments", "UEFOneShotWorkaround", false, "update_every_frame by default does not work on `.PlayOneshot()`. This experiment works around the issue by instead playing the clip on a duplicate AudioSource, allowing UEF to work as intended.").Value;
		}
	}
}
namespace loaforcsSoundAPI.Core.Patches.Native
{
	internal static class AudioSourceNativePatch
	{
		[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
		private delegate void PlayDelegate(IntPtr self, double delay);

		[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
		private delegate void RemoveFromManagerDelegate(IntPtr self);

		private static PlayDelegate _origPlay;

		private static RemoveFromManagerDelegate _origRemoveFromManager;

		internal static void Init(NativeOffsets offsets)
		{
			_origPlay = NativeBackend.PatchNative<PlayDelegate>(offsets.AudioSource_Play, Play);
			if (offsets.AudioSource_RemoveFromManager.HasValue)
			{
				_origRemoveFromManager = NativeBackend.PatchNative<RemoveFromManagerDelegate>(offsets.AudioSource_RemoveFromManager.Value, PatchedRemoveFromManager);
				return;
			}
			loaforcsSoundAPI.Logger.LogWarning((object)"No RemoveFromManager offset for this unity version, falling back.");
			SceneManager.sceneLoaded += delegate
			{
				SoundAPIAudioManager.RunCleanup();
			};
		}

		private static void PatchedRemoveFromManager(IntPtr self)
		{
			AudioSource scriptingWrapper = NativeBackend.GetScriptingWrapper<AudioSource>(self);
			if (AudioSourceAdditionalData.TryGet(scriptingWrapper, out var data))
			{
				Debuggers.NativeBackend?.Log("AudioSource::RemoveFromManager() cleaned up an audio source");
				SoundAPIAudioManager.Remove(data);
			}
			_origRemoveFromManager(self);
		}

		private static void Play(IntPtr self, double delay)
		{
			AudioSource scriptingWrapper = NativeBackend.GetScriptingWrapper<AudioSource>(self);
			Debuggers.NativeBackend?.Log($"native detour source = {scriptingWrapper} (gameobject: {((Object)((Component)scriptingWrapper).gameObject).name})");
			AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(scriptingWrapper);
			if (SoundReplacementHandler.TryReplaceAudio(orCreate.Source, orCreate.OriginalClip, out var replacement))
			{
				if (!Object.op_Implicit((Object)(object)replacement))
				{
					return;
				}
				orCreate.RealClip = replacement;
			}
			Debuggers.NativeBackend?.Log($"AudioSource::Play() with native detour. IntPtr self = {self}");
			_origPlay(self, delay);
		}
	}
	internal static class NativeBackend
	{
		internal static readonly IntPtr BaseAddress = GetUnityPlayerModule().BaseAddress;

		private static NativeBackendSettings[] _allSettings = new NativeBackendSettings[4]
		{
			new NativeBackendSettings("2022.3.9f1", new NativeOffsets(12188608)),
			new NativeBackendSettings("2022.3.62f2", new NativeOffsets(12373984, 12387760)),
			new NativeBackendSettings("2022.3.60f1", new NativeOffsets(12369632)),
			new NativeBackendSettings("6000.3.15f1", new NativeOffsets(12650320))
		};

		[UsedImplicitly]
		private static List<NativeDetour> _allDetours = new List<NativeDetour>();

		internal static bool Enabled { get; private set; }

		internal static RuntimePlatform Platform => Application.platform;

		internal static bool TryGetSettings(out NativeBackendSettings settings)
		{
			settings = _allSettings.FirstOrDefault((NativeBackendSettings it) => it.CurrentVersionMatches);
			return settings != null;
		}

		internal static IEnumerable<string> SupportedUnityVersions()
		{
			return _allSettings.Select((NativeBackendSettings it) => it.UnityVersion);
		}

		private static void Init(NativeBackendSettings settings)
		{
			Enabled = true;
			AudioSourceNativePatch.Init(settings.WindowsReleaseOffsets);
		}

		internal static bool TryInit()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			if (!TryGetSettings(out var settings))
			{
				loaforcsSoundAPI.Logger.LogWarning((object)("Native backend is not yet supported for unity version: " + Application.unityVersion));
				return false;
			}
			if ((int)Platform != 2)
			{
				loaforcsSoundAPI.Logger.LogWarning((object)"Native backend is not yet supported on other platforms than Windows. (Proton, etc. may be a workaround?)");
				return false;
			}
			Init(settings);
			return true;
		}

		internal static T PatchNative<T>(int offset, T patch) where T : Delegate
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			IntPtr intPtr = BaseAddress + offset;
			IntPtr functionPointerForDelegate = Marshal.GetFunctionPointerForDelegate(patch);
			NativeDetour val = new NativeDetour(intPtr, functionPointerForDelegate);
			_allDetours.Add(val);
			return val.GenerateTrampoline<T>();
		}

		private static ProcessModule GetUnityPlayerModule()
		{
			ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
			for (int i = 0; i < modules.Count; i++)
			{
				ProcessModule processModule = modules[i];
				if (processModule.ModuleName.Contains("UnityPlayer"))
				{
					return processModule;
				}
			}
			return null;
		}

		internal unsafe static int GetInstanceID(IntPtr obj)
		{
			if (Object.OffsetOfInstanceIDInCPlusPlusObject == -1)
			{
				Object.OffsetOfInstanceIDInCPlusPlusObject = Object.GetOffsetOfInstanceIDInCPlusPlusObject();
			}
			return *(int*)(void*)(obj + Object.OffsetOfInstanceIDInCPlusPlusObject);
		}

		internal unsafe static IntPtr GetGCHandle(IntPtr obj)
		{
			int num = 24;
			return *(IntPtr*)(void*)(obj + num);
		}

		internal static T GetScriptingWrapper<T>(IntPtr self) where T : Object
		{
			if (GetGCHandle(self) != IntPtr.Zero)
			{
				IntPtr gCHandle = GetGCHandle(self);
				return (T)GCHandle.FromIntPtr(gCHandle).Target;
			}
			Debuggers.NativeBackend?.Log("gc handle was zero");
			int instanceID = GetInstanceID(self);
			Debuggers.NativeBackend?.Log($"instance id = {instanceID}");
			Object val = Resources.InstanceIDToObject(instanceID);
			Debuggers.NativeBackend?.Log($"obj = {val}");
			return (T)(object)val;
		}
	}
	public record NativeBackendSettings(string UnityVersion, NativeOffsets WindowsReleaseOffsets)
	{
		public bool CurrentVersionMatches => Application.unityVersion == UnityVersion;
	}
	public record NativeOffsets(int AudioSource_Play, int? AudioSource_RemoveFromManager = null);
}
namespace loaforcsSoundAPI.Core.Patches.Harmony
{
	internal static class HarmonyBackend
	{
		internal static void Init(Harmony harmony)
		{
			harmony.PatchAll(typeof(HarmonyBackend));
			UnityObjectPatch.Init(harmony);
			SceneManager.sceneLoaded += delegate(Scene scene, LoadSceneMode _)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				SoundAPIAudioManager.RunCleanup();
				AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true);
				foreach (AudioSource val in array)
				{
					if (!(((Component)val).gameObject.scene != scene))
					{
						CheckAudioSource(val);
					}
				}
			};
		}

		internal static void CheckAudioSource(AudioSource source)
		{
			AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(source);
			if (source.playOnAwake && ((Behaviour)source).isActiveAndEnabled && Object.op_Implicit((Object)(object)orCreate.RealClip))
			{
				source.Play();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(AudioSource), "Play", new Type[] { })]
		[HarmonyPatch(typeof(AudioSource), "Play", new Type[] { typeof(ulong) })]
		[HarmonyPatch(typeof(AudioSource), "Play", new Type[] { typeof(double) })]
		public static bool Play(AudioSource __instance)
		{
			Debuggers.SoundReplacementHandler?.Log("HarmonyX Backend: AudioSource.Play patch");
			AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(__instance);
			if (SoundReplacementHandler.TryReplaceAudio(__instance, orCreate.OriginalClip, out var replacement))
			{
				if ((Object)(object)replacement == (Object)null)
				{
					return false;
				}
				orCreate.RealClip = replacement;
			}
			return true;
		}
	}
	internal static class UnityObjectPatch
	{
		private static void InstantiatePatch(Object __result)
		{
			Debuggers.AudioSourceAdditionalData?.Log("aghuobr: " + __result.name);
			GameObject val = (GameObject)(object)((__result is GameObject) ? __result : null);
			if (val != null)
			{
				CheckInstantiationRecursively(val);
			}
		}

		internal static void Init(Harmony harmony)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			HarmonyMethod val = new HarmonyMethod(typeof(UnityObjectPatch).GetMethod("InstantiatePatch", BindingFlags.Static | BindingFlags.NonPublic));
			MethodInfo[] methods = typeof(Object).GetMethods();
			foreach (MethodInfo methodInfo in methods)
			{
				if (!(methodInfo.Name != "Instantiate"))
				{
					Debuggers.AudioSourceAdditionalData?.Log($"patching {methodInfo}");
					if (methodInfo.IsGenericMethod)
					{
						harmony.Patch((MethodBase)methodInfo.MakeGenericMethod(typeof(Object)), (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					else
					{
						harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
			}
		}

		private static void CheckInstantiationRecursively(GameObject gameObject)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			AudioSource[] components = gameObject.GetComponents<AudioSource>();
			foreach (AudioSource source in components)
			{
				HarmonyBackend.CheckAudioSource(source);
			}
			foreach (Transform item in gameObject.transform)
			{
				Transform val = item;
				CheckInstantiationRecursively(((Component)val).gameObject);
			}
		}
	}
}
namespace loaforcsSoundAPI.Core.Networking
{
	public abstract class NetworkAdapter
	{
		public abstract string Name { get; }

		public abstract void OnRegister();
	}
}
namespace loaforcsSoundAPI.Core.JSON
{
	public static class JSONDataLoader
	{
		private class MatchesJSONConverter : JsonConverter
		{
			public override bool CanConvert(Type objectType)
			{
				return objectType == typeof(List<string>);
			}

			public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Invalid comparison between Unknown and I4
				JToken val = JToken.Load(reader);
				if ((int)val.Type == 2)
				{
					return val.ToObject<List<string>>();
				}
				return new List<string> { ((object)val).ToString() };
			}

			public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, value);
			}
		}

		private class IncludePrivatePropertiesContractResolver : DefaultContractResolver
		{
			internal IncludePrivatePropertiesContractResolver()
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Expected O, but got Unknown
				((DefaultContractResolver)this).NamingStrategy = (NamingStrategy)new SnakeCaseNamingStrategy();
			}

			protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				JsonProperty val = ((DefaultContractResolver)this).CreateProperty(member, memberSerialization);
				if (!val.Writable && member is PropertyInfo propertyInfo)
				{
					val.Writable = propertyInfo.GetSetMethod(nonPublic: true) != null;
				}
				return val;
			}
		}

		private class ConditionConverter : JsonConverter<Condition>
		{
			public override Condition ReadJson(JsonReader reader, Type objectType, Condition existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				JObject val = JObject.Load(reader);
				string text = ((object)val["type"])?.ToString();
				if (string.IsNullOrEmpty(text))
				{
					return new InvalidCondition(null);
				}
				Condition condition = SoundPackDataHandler.CreateCondition(text);
				if (condition == null)
				{
					return null;
				}
				serializer.Populate(((JToken)val).CreateReader(), (object)condition);
				if (condition.Constant == true)
				{
					if (!condition.Evaluate(DefaultConditionContext.DEFAULT))
					{
						return ConstantCondition.FALSE;
					}
					return ConstantCondition.TRUE;
				}
				return condition;
			}

			public override void WriteJson(JsonWriter writer, Condition value, JsonSerializer serializer)
			{
				throw new NotImplementedException("no.");
			}
		}

		private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings
		{
			ContractResolver = (IContractResolver)(object)new IncludePrivatePropertiesContractResolver(),
			Converters = new List<JsonConverter>(2)
			{
				(JsonConverter)(object)new MatchesJSONConverter(),
				(JsonConverter)(object)new ConditionConverter()
			}
		};

		public static T LoadFromFile<T>(string path)
		{
			//IL_0061: Expected O, but got Unknown
			string text = File.ReadAllText(path);
			try
			{
				T val = JsonConvert.DeserializeObject<T>(text, _settings);
				if (val is IFilePathAware filePathAware)
				{
					filePathAware.FilePath = path;
				}
				if (val is Conditional { Condition: not null } conditional)
				{
					conditional.Condition.Parent = conditional;
					conditional.Condition.OnRegistered();
				}
				return val;
			}
			catch (JsonReaderException ex)
			{
				JsonReaderException ex2 = ex;
				loaforcsSoundAPI.Logger.LogError((object)$"Failed to read json file: 'plugins{Path.DirectorySeparatorChar}{Path.GetRelativePath(Paths.PluginPath, path)}'");
				loaforcsSoundAPI.Logger.LogError((object)((Exception)(object)ex2).Message);
				string[] array = text.Split("\n");
				int num = int.MaxValue;
				for (int i = Mathf.Max(0, ex2.LineNumber - 3); i < Mathf.Min(array.Length, ex2.LineNumber + 3); i++)
				{
					int num2 = array[i].TakeWhile(char.IsWhiteSpace).Count();
					num = Mathf.Min(num, num2);
				}
				for (int j = Mathf.Max(0, ex2.LineNumber - 3); j < Mathf.Min(array.Length, ex2.LineNumber + 3); j++)
				{
					string text2 = $"{(j + 1).ToString(),-5}|  " + array[j].Substring(Mathf.Min(array[j].Length, num)).TrimEnd();
					if (j + 1 == ex2.LineNumber)
					{
						text2 += " // <- HERE";
					}
					loaforcsSoundAPI.Logger.LogError((object)text2);
				}
			}
			return default(T);
		}
	}
}
namespace loaforcsSoundAPI.Core.Data
{
	public interface IFilePathAware
	{
		string FilePath { get; internal set; }
	}
	public interface IValidatable
	{
		public enum ResultType
		{
			WARN,
			FAIL
		}

		public class ValidationResult
		{
			public ResultType Status { get; private set; }

			public string Reason { get; private set; }

			public ValidationResult(ResultType resultType, string reason = null)
			{
				Status = resultType;
				Reason = reason ?? string.Empty;
				base..ctor();
			}
		}

		private static readonly StringBuilder _stringBuilder = new StringBuilder();

		List<ValidationResult> Validate();

		internal static bool LogAndCheckValidationResult(string context, List<ValidationResult> results, ManualLogSource logger)
		{
			if (results.Count == 0)
			{
				return true;
			}
			int num = 0;
			int num2 = 0;
			foreach (ValidationResult result in results)
			{
				switch (result.Status)
				{
				case ResultType.WARN:
					num++;
					break;
				case ResultType.FAIL:
					num2++;
					break;
				default:
					throw new ArgumentOutOfRangeException();
				}
			}
			_stringBuilder.Clear();
			if (num2 != 0)
			{
				_stringBuilder.Append(num2);
				_stringBuilder.Append(" fail(s)");
			}
			if (num != 0)
			{
				if (num2 != 0)
				{
					_stringBuilder.Append(" and ");
				}
				_stringBuilder.Append(num);
				_stringBuilder.Append(" warning(s)");
			}
			_stringBuilder.Append(" while ");
			_stringBuilder.Append(context);
			_stringBuilder.Append(": ");
			if (num2 != 0)
			{
				logger.LogError((object)_stringBuilder);
			}
			else
			{
				logger.LogWarning((object)_stringBuilder);
			}
			foreach (ValidationResult result2 in results)
			{
				switch (result2.Status)
				{
				case ResultType.WARN:
					logger.LogWarning((object)("WARN: " + result2.Reason));
					break;
				case ResultType.FAIL:
					logger.LogError((object)("FAIL: " + result2.Reason));
					break;
				default:
					throw new ArgumentOutOfRangeException();
				}
			}
			return num2 == 0;
		}
	}
}

modules/MenuLib.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using MenuLib.MonoBehaviors;
using MenuLib.Structs;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[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("MenuLib")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.6.2")]
[assembly: AssemblyInformationalVersion("1.0.0+d52e9f03e8700cd64446dc607921da11bd0b4e60")]
[assembly: AssemblyProduct("MenuLib")]
[assembly: AssemblyTitle("MenuLib")]
[assembly: AssemblyVersion("2.6.2.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 MenuLib
{
	[BepInPlugin("nickklmao.menulib", "Menu Lib", "2.6.2")]
	internal sealed class Entry : BaseUnityPlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static Action<Action<MenuPageMain>, MenuPageMain> <0>__MenuPageMain_StartHook;

			public static Action<Action<MenuPageSettings>, MenuPageSettings> <1>__MenuPageSettings_StartHook;

			public static Action<Action<MenuPageColor>, MenuPageColor> <2>__MenuPageColor_StartHook;

			public static Action<Action<MenuPageEsc>, MenuPageEsc> <3>__MenuPageEsc_StartHook;

			public static Action<Action<MenuPageRegions>, MenuPageRegions> <4>__MenuPageRegions_StartHook;

			public static Action<Action<MenuPageServerList>, MenuPageServerList> <5>__MenuPageServerList_StartHook;

			public static Action<Action<MenuPageLobby>, MenuPageLobby> <6>__MenuPageLobby_StartHook;

			public static Manipulator <7>__SemiFunc_UIMouseHoverILHook;

			public static Manipulator <8>__MenuPage_StateClosingILHook;

			public static Manipulator <9>__ChatManager_StateInactiveILHook;
		}

		private const string MOD_NAME = "Menu Lib";

		internal static readonly ManualLogSource logger = Logger.CreateLogSource("Menu Lib");

		private static void MenuPageMain_StartHook(Action<MenuPageMain> orig, MenuPageMain self)
		{
			orig(self);
			MenuAPI.mainMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void MenuPageSettings_StartHook(Action<MenuPageSettings> orig, MenuPageSettings self)
		{
			orig(self);
			MenuAPI.settingsMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void MenuPageColor_StartHook(Action<MenuPageColor> orig, MenuPageColor self)
		{
			orig(self);
			MenuAPI.colorMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void MenuPageEsc_StartHook(Action<MenuPageEsc> orig, MenuPageEsc self)
		{
			orig(self);
			MenuAPI.escapeMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void MenuPageRegions_StartHook(Action<MenuPageRegions> orig, MenuPageRegions self)
		{
			orig(self);
			MenuAPI.regionSelectionMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void MenuPageServerList_StartHook(Action<MenuPageServerList> orig, MenuPageServerList self)
		{
			orig(self);
			MenuAPI.serverListMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void MenuPageLobby_StartHook(Action<MenuPageLobby> orig, MenuPageLobby self)
		{
			orig(self);
			MenuAPI.lobbyMenuBuilderDelegate?.Invoke(((Component)self).transform);
		}

		private static void SemiFunc_UIMouseHoverILHook(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			RectTransform val3 = default(RectTransform);
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchBrfalse(instruction, ref val3) && ILPatternMatchingExt.MatchLdarg(val3.Target, 6)
			});
			val.Index += 2;
			val.RemoveRange(27);
			val.Emit(OpCodes.Ldloc_0);
			val.EmitDelegate<Func<MenuScrollBox, Vector2, bool>>((Func<MenuScrollBox, Vector2, bool>)delegate(MenuScrollBox menuScrollBox, Vector2 vector)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Expected O, but got Unknown
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				val3 = (RectTransform)((Transform)menuScrollBox.scroller).parent;
				float y = ((Transform)val3).position.y;
				float num = y + val3.sizeDelta.y;
				return vector.y > y && vector.y < num;
			});
			ILLabel val2 = val.DefineLabel();
			val.Emit(OpCodes.Brtrue_S, (object)val2);
			val.Emit(OpCodes.Ldc_I4_0);
			val.Emit(OpCodes.Ret);
			val.MarkLabel(val2);
		}

		private static void MenuPage_StateClosingILHook(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchLdfld<MenuPage>(instruction, "stateStart")
			});
			val.Index += 2;
			val.Emit(OpCodes.Ldarg_0);
			val.EmitDelegate<Action<MenuPage>>((Action<MenuPage>)delegate(MenuPage menuPage)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				if (MenuAPI.customMenuPages.TryGetValue(menuPage, out var value))
				{
					RectTransform val2 = (RectTransform)((Component)menuPage).transform;
					Vector2 val3 = Vector2.op_Implicit(((Transform)val2).position);
					Rect rect = val2.rect;
					float num = 0f - ((Rect)(ref rect)).height;
					rect = value.rectTransform.rect;
					val3.y = num - ((Rect)(ref rect)).height;
					REPOReflection.menuPage_AnimateAwayPosition.SetValue(menuPage, val3);
				}
			});
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchCall<Object>(instruction, "Destroy")
			});
			val.Index -= 5;
			val.RemoveRange(6);
			val.Emit(OpCodes.Ldarg_0);
			val.EmitDelegate<Action<MenuPage>>((Action<MenuPage>)delegate(MenuPage menuPage)
			{
				if (MenuAPI.customMenuPages.TryGetValue(menuPage, out var value) && (value.isCachedPage || !value.pageWasActivatedOnce))
				{
					((Behaviour)menuPage).enabled = false;
				}
				else
				{
					MenuManager.instance.PageRemove(menuPage);
					Object.Destroy((Object)(object)((Component)menuPage).gameObject);
				}
			});
		}

		private static void MenuScrollBox_UpdateILHook(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			val.GotoNext(new Func<Instruction, bool>[3]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchLdarg(instruction, 0),
				(Instruction instruction) => ILPatternMatchingExt.MatchLdarg(instruction, 0),
				(Instruction instruction) => ILPatternMatchingExt.MatchLdfld<MenuScrollBox>(instruction, "scrollHandleTargetPosition")
			});
			int index = val.Index;
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchCall<Mathf>(instruction, "Lerp")
			});
			val.GotoPrev(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchStfld<MenuScrollBox>(instruction, "scrollHandleTargetPosition")
			});
			int index2 = val.Index;
			val.Index = index;
			val.RemoveRange(index2 - index + 1);
			ILLabel val2 = val.MarkLabel();
			val.GotoPrev(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => instruction.OpCode == OpCodes.Brfalse_S
			});
			val.Remove();
			val.Emit(OpCodes.Brfalse_S, (object)val2);
			val.Emit(OpCodes.Ldarg_0);
			val.Emit(OpCodes.Ldarg_0);
			val.Emit<MenuScrollBox>(OpCodes.Ldfld, "parentPage");
			val.EmitDelegate<Action<MenuScrollBox, MenuPage>>((Action<MenuScrollBox, MenuPage>)delegate(MenuScrollBox menuScrollBox, MenuPage menuPage)
			{
				//IL_0087: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				float num = SemiFunc.InputMovementY() / 20f;
				float num2 = SemiFunc.InputScrollY();
				float num5;
				if (MenuAPI.customMenuPages.TryGetValue(menuPage, out var value))
				{
					float? scrollSpeed = value.scrollView.scrollSpeed;
					if (scrollSpeed.HasValue)
					{
						float valueOrDefault = scrollSpeed.GetValueOrDefault();
						valueOrDefault *= 10f;
						float num3 = Mathf.Abs((float)REPOReflection.menuScrollBox_ScrollerEndPosition.GetValue(menuScrollBox) - (float)REPOReflection.menuScrollBox_ScrollerStartPosition.GetValue(menuScrollBox));
						float num4 = (num + (float)Math.Sign(num2)) * valueOrDefault / num3;
						Rect rect = menuScrollBox.scrollBarBackground.rect;
						num5 = num4 * ((Rect)(ref rect)).height;
						goto IL_00c1;
					}
				}
				float num6 = (float)REPOReflection.menuScrollBox_ScrollHeight.GetValue(menuScrollBox);
				num5 = num / (num6 * 0.01f) + num2 / (num6 * 0.01f);
				goto IL_00c1;
				IL_00c1:
				float num7 = (float)REPOReflection.menuScrollBox_ScrollHandleTargetPosition.GetValue(menuScrollBox);
				REPOReflection.menuScrollBox_ScrollHandleTargetPosition.SetValue(menuScrollBox, num7 + num5);
			});
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchStfld<MenuScrollBox>(instruction, "scrollAmount")
			});
			val.Index -= 13;
			val.RemoveRange(14);
			val.EmitDelegate<Action<MenuScrollBox>>((Action<MenuScrollBox>)delegate(MenuScrollBox instance)
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Expected O, but got Unknown
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				Rect rect;
				float num2;
				if (MenuAPI.customMenuPages.ContainsKey((MenuPage)REPOReflection.menuScrollBox_ParentPage.GetValue(instance)))
				{
					float num = ((Transform)instance.scrollHandle).localPosition.y + instance.scrollHandle.sizeDelta.y / 2f;
					rect = instance.scrollBarBackground.rect;
					num2 = num / ((Rect)(ref rect)).height;
				}
				else
				{
					float y = ((Transform)instance.scrollHandle).localPosition.y;
					rect = instance.scrollBarBackground.rect;
					num2 = y / ((Rect)(ref rect)).height * 1.1f;
				}
				REPOReflection.menuScrollBox_ScrollAmount.SetValue(instance, num2);
			});
		}

		private static void ChatManager_StateInactiveILHook(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			val.GotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction instruction) => ILPatternMatchingExt.MatchStfld<ChatManager>(instruction, "chatActive")
			});
			ILLabel val2 = val.DefineLabel();
			val.Emit<REPOInputStringSystem>(OpCodes.Ldsfld, "hasAnyFocus");
			val.Emit(OpCodes.Brfalse_S, (object)val2);
			val.Emit(OpCodes.Ret);
			val.MarkLabel(val2);
		}

		private void Awake()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Expected O, but got Unknown
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Expected O, but got Unknown
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected O, but got Unknown
			logger.LogDebug((object)"Hooking `MenuPageMain.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageMain), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageMain>, MenuPageMain>(MenuPageMain_StartHook));
			logger.LogDebug((object)"Hooking `MenuPageSettings.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageSettings), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageSettings>, MenuPageSettings>(MenuPageSettings_StartHook));
			logger.LogDebug((object)"Hooking `MenuPageColor.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageColor), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageColor>, MenuPageColor>(MenuPageColor_StartHook));
			logger.LogDebug((object)"Hooking `MenuPageEsc.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageEsc), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageEsc>, MenuPageEsc>(MenuPageEsc_StartHook));
			logger.LogDebug((object)"Hooking `MenuPageRegions.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageRegions), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageRegions>, MenuPageRegions>(MenuPageRegions_StartHook));
			logger.LogDebug((object)"Hooking `MenuPageServerList.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageServerList), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageServerList>, MenuPageServerList>(MenuPageServerList_StartHook));
			logger.LogDebug((object)"Hooking `MenuPageLobby.Start`");
			new Hook((MethodBase)AccessTools.Method(typeof(MenuPageLobby), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageLobby>, MenuPageLobby>(MenuPageLobby_StartHook));
			logger.LogDebug((object)"Hooking `SemiFunc.UIMouseHover`");
			MethodInfo methodInfo = AccessTools.Method(typeof(SemiFunc), "UIMouseHover", (Type[])null, (Type[])null);
			object obj = <>O.<7>__SemiFunc_UIMouseHoverILHook;
			if (obj == null)
			{
				Manipulator val = SemiFunc_UIMouseHoverILHook;
				<>O.<7>__SemiFunc_UIMouseHoverILHook = val;
				obj = (object)val;
			}
			new ILHook((MethodBase)methodInfo, (Manipulator)obj);
			logger.LogDebug((object)"Hooking `MenuPage.StateClosing`");
			MethodInfo methodInfo2 = AccessTools.Method(typeof(MenuPage), "StateClosing", (Type[])null, (Type[])null);
			object obj2 = <>O.<8>__MenuPage_StateClosingILHook;
			if (obj2 == null)
			{
				Manipulator val2 = MenuPage_StateClosingILHook;
				<>O.<8>__MenuPage_StateClosingILHook = val2;
				obj2 = (object)val2;
			}
			new ILHook((MethodBase)methodInfo2, (Manipulator)obj2);
			logger.LogDebug((object)"Hooking `ChatManager.StateInactive`");
			MethodInfo methodInfo3 = AccessTools.Method(typeof(ChatManager), "StateInactive", (Type[])null, (Type[])null);
			object obj3 = <>O.<9>__ChatManager_StateInactiveILHook;
			if (obj3 == null)
			{
				Manipulator val3 = ChatManager_StateInactiveILHook;
				<>O.<9>__ChatManager_StateInactiveILHook = val3;
				obj3 = (object)val3;
			}
			new ILHook((MethodBase)methodInfo3, (Manipulator)obj3);
		}
	}
	public static class MenuAPI
	{
		public delegate void BuilderDelegate(Transform parent);

		internal static BuilderDelegate mainMenuBuilderDelegate;

		internal static BuilderDelegate settingsMenuBuilderDelegate;

		internal static BuilderDelegate colorMenuBuilderDelegate;

		internal static BuilderDelegate lobbyMenuBuilderDelegate;

		internal static BuilderDelegate escapeMenuBuilderDelegate;

		internal static BuilderDelegate regionSelectionMenuBuilderDelegate;

		internal static BuilderDelegate serverListMenuBuilderDelegate;

		internal static readonly Dictionary<MenuPage, REPOPopupPage> customMenuPages = new Dictionary<MenuPage, REPOPopupPage>();

		private static MenuButtonPopUp menuButtonPopup;

		public static void AddElementToMainMenu(BuilderDelegate builderDelegate)
		{
			mainMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(mainMenuBuilderDelegate, builderDelegate);
		}

		public static void AddElementToSettingsMenu(BuilderDelegate builderDelegate)
		{
			settingsMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(settingsMenuBuilderDelegate, builderDelegate);
		}

		public static void AddElementToColorMenu(BuilderDelegate builderDelegate)
		{
			colorMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(colorMenuBuilderDelegate, builderDelegate);
		}

		public static void AddElementToLobbyMenu(BuilderDelegate builderDelegate)
		{
			lobbyMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(lobbyMenuBuilderDelegate, builderDelegate);
		}

		public static void AddElementToEscapeMenu(BuilderDelegate builderDelegate)
		{
			escapeMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(escapeMenuBuilderDelegate, builderDelegate);
		}

		public static void AddElementToRegionSelectionMenu(BuilderDelegate builderDelegate)
		{
			regionSelectionMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(regionSelectionMenuBuilderDelegate, builderDelegate);
		}

		public static void AddElementToServerListMenu(BuilderDelegate builderDelegate)
		{
			serverListMenuBuilderDelegate = (BuilderDelegate)Delegate.Combine(serverListMenuBuilderDelegate, builderDelegate);
		}

		public static void CloseAllPagesAddedOnTop()
		{
			MenuManager.instance.PageCloseAllAddedOnTop();
		}

		public static void OpenPopup(string header, Color headerColor, string content, Action onLeftClicked, Action onRightClicked = null)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)menuButtonPopup))
			{
				menuButtonPopup = ((Component)MenuManager.instance).gameObject.AddComponent<MenuButtonPopUp>();
			}
			menuButtonPopup.option1Event = new UnityEvent();
			menuButtonPopup.option2Event = new UnityEvent();
			if (onLeftClicked != null)
			{
				menuButtonPopup.option1Event.AddListener(new UnityAction(onLeftClicked.Invoke));
			}
			if (onRightClicked != null)
			{
				menuButtonPopup.option2Event.AddListener(new UnityAction(onRightClicked.Invoke));
			}
			MenuManager.instance.PagePopUpTwoOptions(menuButtonPopup, header, (LocalizedAsset)null, headerColor, content, (LocalizedAsset)null, "Yes", (LocalizedAsset)null, "No", (LocalizedAsset)null, true);
		}

		public static REPOButton CreateREPOButton(string text, Action onClick, Transform parent, Vector2 localPosition = default(Vector2))
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.buttonTemplate, parent);
			((Object)obj).name = "Button - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOButton rEPOButton = ((Component)obj).gameObject.AddComponent<REPOButton>();
			((TMP_Text)rEPOButton.labelTMP).text = text;
			rEPOButton.onClick = onClick;
			return rEPOButton;
		}

		public static REPOToggle CreateREPOToggle(string text, Action<bool> onToggle, Transform parent, Vector2 localPosition = default(Vector2), string leftButtonText = "ON", string rightButtonText = "OFF", bool defaultValue = false)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.toggleTemplate, parent);
			((Object)obj).name = "Toggle - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOToggle rEPOToggle = ((Component)obj).gameObject.AddComponent<REPOToggle>();
			((TMP_Text)rEPOToggle.labelTMP).text = text;
			((TMP_Text)rEPOToggle.leftButtonTMP).text = leftButtonText;
			((TMP_Text)rEPOToggle.rightButtonTMP).text = rightButtonText;
			rEPOToggle.onToggle = onToggle;
			rEPOToggle.SetState(defaultValue, invokeCallback: false);
			return rEPOToggle;
		}

		public static REPOInputField CreateREPOInputField(string labelText, Action<string> onValueChanged, Transform parent, Vector2 localPosition = default(Vector2), bool onlyNotifyOnSubmit = false, string placeholder = "", string defaultValue = "")
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.toggleTemplate, parent);
			((Object)obj).name = "Input Field - " + labelText;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOInputField rEPOInputField = ((Component)obj).gameObject.AddComponent<REPOInputField>();
			((TMP_Text)rEPOInputField.labelTMP).text = labelText;
			rEPOInputField.inputStringSystem.onValueChanged = onValueChanged;
			rEPOInputField.inputStringSystem.onlyNotifyOnSubmit = onlyNotifyOnSubmit;
			rEPOInputField.inputStringSystem.placeholder = placeholder;
			rEPOInputField.inputStringSystem.SetValue(defaultValue, notify: false);
			return rEPOInputField;
		}

		public static REPOSlider CreateREPOSlider(string text, string description, Action<float> onValueChanged, Transform parent, Vector2 localPosition = default(Vector2), float min = 0f, float max = 1f, int precision = 2, float defaultValue = 0f, string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.sliderTemplate, parent);
			((Object)obj).name = "Float Slider - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider rEPOSlider = ((Component)obj).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)rEPOSlider.labelTMP).text = text;
			((TMP_Text)rEPOSlider.descriptionTMP).text = description;
			rEPOSlider.onValueChanged = onValueChanged;
			rEPOSlider.min = min;
			rEPOSlider.max = max;
			rEPOSlider.precision = precision;
			rEPOSlider.prefix = prefix;
			rEPOSlider.postfix = postfix;
			rEPOSlider.barBehavior = barBehavior;
			rEPOSlider.SetValue(defaultValue, invokeCallback: false);
			return rEPOSlider;
		}

		public static REPOSlider CreateREPOSlider(string text, string description, Action<int> onValueChanged, Transform parent, Vector2 localPosition = default(Vector2), int min = 0, int max = 1, int defaultValue = 0, string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.sliderTemplate, parent);
			((Object)obj).name = "Int Slider - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider rEPOSlider = ((Component)obj).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)rEPOSlider.labelTMP).text = text;
			((TMP_Text)rEPOSlider.descriptionTMP).text = description;
			rEPOSlider.onValueChanged = delegate(float f)
			{
				onValueChanged(Convert.ToInt32(f));
			};
			rEPOSlider.min = min;
			rEPOSlider.max = max;
			rEPOSlider.precision = 0;
			rEPOSlider.prefix = prefix;
			rEPOSlider.postfix = postfix;
			rEPOSlider.barBehavior = barBehavior;
			rEPOSlider.SetValue(defaultValue, invokeCallback: false);
			return rEPOSlider;
		}

		public static REPOSlider CreateREPOSlider(string text, string description, Action<string> onOptionChanged, Transform parent, string[] stringOptions, string defaultOption, Vector2 localPosition = default(Vector2), string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = Object.Instantiate<RectTransform>(REPOTemplates.sliderTemplate, parent);
			((Object)val).name = "Option Slider - " + text;
			((Transform)val).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider repoSlider = ((Component)val).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)repoSlider.labelTMP).text = text;
			((TMP_Text)repoSlider.descriptionTMP).text = description;
			repoSlider.onValueChanged = delegate(float f)
			{
				onOptionChanged(repoSlider.stringOptions.ElementAtOrDefault(Convert.ToInt32(f)) ?? repoSlider.stringOptions.FirstOrDefault());
			};
			repoSlider.stringOptions = stringOptions;
			repoSlider.prefix = prefix;
			repoSlider.postfix = postfix;
			repoSlider.barBehavior = barBehavior;
			int num = Array.IndexOf(stringOptions, defaultOption);
			if (num == -1)
			{
				num = 0;
			}
			repoSlider.SetValue(num, invokeCallback: false);
			return repoSlider;
		}

		public static REPOSlider CreateREPOSlider(string text, string description, Action<int> onOptionChanged, Transform parent, string[] stringOptions, string defaultOption, Vector2 localPosition = default(Vector2), string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.sliderTemplate, parent);
			((Object)obj).name = "Option Slider - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider rEPOSlider = ((Component)obj).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)rEPOSlider.labelTMP).text = text;
			((TMP_Text)rEPOSlider.descriptionTMP).text = description;
			rEPOSlider.onValueChanged = delegate(float f)
			{
				onOptionChanged(Convert.ToInt32(f));
			};
			rEPOSlider.stringOptions = stringOptions;
			rEPOSlider.prefix = prefix;
			rEPOSlider.postfix = postfix;
			rEPOSlider.barBehavior = barBehavior;
			int num = Array.IndexOf(stringOptions, defaultOption);
			if (num == -1)
			{
				num = 0;
			}
			rEPOSlider.SetValue(num, invokeCallback: false);
			return rEPOSlider;
		}

		public static REPOSlider CreateREPOBigSlider(string text, string description, Action<float> onValueChanged, Transform parent, Vector2 localPosition = default(Vector2), float min = 0f, float max = 1f, int precision = 2, float defaultValue = 0f, string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.bigSliderTemplate, parent);
			((Object)obj).name = "Float Slider - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider rEPOSlider = ((Component)obj).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)rEPOSlider.labelTMP).text = text;
			((TMP_Text)rEPOSlider.descriptionTMP).text = description;
			rEPOSlider.onValueChanged = onValueChanged;
			rEPOSlider.min = min;
			rEPOSlider.max = max;
			rEPOSlider.precision = precision;
			rEPOSlider.prefix = prefix;
			rEPOSlider.postfix = postfix;
			rEPOSlider.barBehavior = barBehavior;
			rEPOSlider.SetValue(defaultValue, invokeCallback: false);
			return rEPOSlider;
		}

		public static REPOSlider CreateREPOBigSlider(string text, string description, Action<int> onValueChanged, Transform parent, Vector2 localPosition = default(Vector2), int min = 0, int max = 1, int defaultValue = 0, string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.bigSliderTemplate, parent);
			((Object)obj).name = "Int Slider - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider rEPOSlider = ((Component)obj).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)rEPOSlider.labelTMP).text = text;
			((TMP_Text)rEPOSlider.descriptionTMP).text = description;
			rEPOSlider.onValueChanged = delegate(float f)
			{
				onValueChanged(Convert.ToInt32(f));
			};
			rEPOSlider.min = min;
			rEPOSlider.max = max;
			rEPOSlider.precision = 0;
			rEPOSlider.prefix = prefix;
			rEPOSlider.postfix = postfix;
			rEPOSlider.barBehavior = barBehavior;
			rEPOSlider.SetValue(defaultValue, invokeCallback: false);
			return rEPOSlider;
		}

		public static REPOSlider CreateREPOBigSlider(string text, string description, Action<string> onOptionChanged, Transform parent, string[] stringOptions, string defaultOption, Vector2 localPosition = default(Vector2), string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = Object.Instantiate<RectTransform>(REPOTemplates.bigSliderTemplate, parent);
			((Object)val).name = "Option Slider - " + text;
			((Transform)val).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider repoSlider = ((Component)val).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)repoSlider.labelTMP).text = text;
			((TMP_Text)repoSlider.descriptionTMP).text = description;
			repoSlider.onValueChanged = delegate(float f)
			{
				onOptionChanged(repoSlider.stringOptions.ElementAtOrDefault(Convert.ToInt32(f)) ?? repoSlider.stringOptions.FirstOrDefault());
			};
			repoSlider.stringOptions = stringOptions;
			repoSlider.prefix = prefix;
			repoSlider.postfix = postfix;
			repoSlider.barBehavior = barBehavior;
			int num = Array.IndexOf(stringOptions, defaultOption);
			if (num == -1)
			{
				num = 0;
			}
			repoSlider.SetValue(num, invokeCallback: false);
			return repoSlider;
		}

		public static REPOSlider CreateREPOBigSlider(string text, string description, Action<int> onOptionChanged, Transform parent, string[] stringOptions, string defaultOption, Vector2 localPosition = default(Vector2), string prefix = "", string postfix = "", REPOSlider.BarBehavior barBehavior = REPOSlider.BarBehavior.UpdateWithValue)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.bigSliderTemplate, parent);
			((Object)obj).name = "Option Slider - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOSlider rEPOSlider = ((Component)obj).gameObject.AddComponent<REPOSlider>();
			((TMP_Text)rEPOSlider.labelTMP).text = text;
			((TMP_Text)rEPOSlider.descriptionTMP).text = description;
			rEPOSlider.onValueChanged = delegate(float f)
			{
				onOptionChanged(Convert.ToInt32(f));
			};
			rEPOSlider.stringOptions = stringOptions;
			rEPOSlider.prefix = prefix;
			rEPOSlider.postfix = postfix;
			rEPOSlider.barBehavior = barBehavior;
			int num = Array.IndexOf(stringOptions, defaultOption);
			if (num == -1)
			{
				num = 0;
			}
			rEPOSlider.SetValue(num, invokeCallback: false);
			return rEPOSlider;
		}

		public static REPOLabel CreateREPOLabel(string text, Transform parent, Vector2 localPosition = default(Vector2))
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.labelTemplate, parent);
			((Object)obj).name = "Label - " + text;
			((Transform)obj).localPosition = Vector2.op_Implicit(localPosition);
			REPOLabel rEPOLabel = ((Component)obj).gameObject.AddComponent<REPOLabel>();
			((TMP_Text)rEPOLabel.labelTMP).text = text;
			return rEPOLabel;
		}

		public static REPOSpacer CreateREPOSpacer(Transform parent, Vector2 localPosition = default(Vector2), Vector2 size = default(Vector2))
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)new GameObject("Spacer", new Type[1] { typeof(RectTransform) }).transform;
			((Transform)val).SetParent(parent);
			REPOSpacer result = ((Component)val).gameObject.AddComponent<REPOSpacer>();
			((Transform)val).localPosition = Vector2.op_Implicit(localPosition);
			val.sizeDelta = size;
			return result;
		}

		[Obsolete("Switch to the overload with the 'shouldCachePage' argument!")]
		public static REPOPopupPage CreateREPOPopupPage(string headerText, REPOPopupPage.PresetSide presetSide, bool pageDimmerVisibility = false, float spacing = 0f)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			return CreateREPOPopupPage(headerText, pageDimmerVisibility, spacing, (presetSide == REPOPopupPage.PresetSide.Left) ? ((Vector2?)null) : new Vector2?(new Vector2(40f, 0f)));
		}

		[Obsolete("Switch to the overload with the 'shouldCachePage' argument!")]
		public static REPOPopupPage CreateREPOPopupPage(string headerText, bool pageDimmerVisibility = false, float spacing = 0f, Vector2? localPosition = null)
		{
			return CreateREPOPopupPage(headerText, shouldCachePage: false, pageDimmerVisibility, spacing, localPosition);
		}

		public static REPOPopupPage CreateREPOPopupPage(string headerText, REPOPopupPage.PresetSide presetSide, bool shouldCachePage, bool pageDimmerVisibility = false, float spacing = 0f)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return CreateREPOPopupPage(headerText, shouldCachePage, pageDimmerVisibility, spacing, (presetSide == REPOPopupPage.PresetSide.Left) ? ((Vector2?)null) : new Vector2?(new Vector2(40f, 0f)));
		}

		public static REPOPopupPage CreateREPOPopupPage(string headerText, bool shouldCachePage, bool pageDimmerVisibility = false, float spacing = 0f, Vector2? localPosition = null)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = Object.Instantiate<RectTransform>(REPOTemplates.popupPageTemplate, ((Component)MenuHolder.instance).transform);
			((Object)obj).name = "Menu Page " + headerText;
			((Transform)obj).localPosition = ((Transform)REPOTemplates.popupPageTemplate).localPosition;
			REPOPopupPage rEPOPopupPage = ((Component)obj).gameObject.AddComponent<REPOPopupPage>();
			((Transform)rEPOPopupPage.rectTransform).localPosition = Vector2.op_Implicit((Vector2)(((??)localPosition) ?? new Vector2(-280f, 0f)));
			((TMP_Text)rEPOPopupPage.headerTMP).text = headerText;
			rEPOPopupPage.isCachedPage = shouldCachePage;
			rEPOPopupPage.pageDimmerVisibility = pageDimmerVisibility;
			rEPOPopupPage.scrollView.spacing = spacing;
			return rEPOPopupPage;
		}

		public static REPOAvatarPreview CreateREPOAvatarPreview(Transform parent, Vector2 localPosition = default(Vector2), bool enableBackgroundImage = false, Color? backgroundImageColor = null)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			Transform obj = Object.Instantiate<Transform>(REPOTemplates.avatarPreviewTemplate, parent);
			((Object)obj).name = "Player Avatar Preview";
			REPOAvatarPreview rEPOAvatarPreview = ((Component)obj).gameObject.AddComponent<REPOAvatarPreview>();
			((Transform)rEPOAvatarPreview.rectTransform).localPosition = Vector2.op_Implicit(localPosition);
			rEPOAvatarPreview.enableBackgroundImage = enableBackgroundImage;
			rEPOAvatarPreview.backgroundImageColor = (Color)(((??)backgroundImageColor) ?? Color.white);
			rEPOAvatarPreview.previewSize = new Vector2(184f, 345f);
			return rEPOAvatarPreview;
		}

		public static REPOObjectPreview CreateREPOObjectPreview(Transform parent, GameObject previewObject, Vector2 localPosition = default(Vector2), bool enableBackgroundImage = false, Color? backgroundImageColor = null)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			Transform obj = Object.Instantiate<Transform>(REPOTemplates.avatarPreviewTemplate, parent);
			((Object)obj).name = "Object Preview";
			REPOObjectPreview rEPOObjectPreview = ((Component)obj).gameObject.AddComponent<REPOObjectPreview>();
			((Transform)rEPOObjectPreview.rectTransform).localPosition = Vector2.op_Implicit(localPosition);
			rEPOObjectPreview.enableBackgroundImage = enableBackgroundImage;
			rEPOObjectPreview.backgroundImageColor = (Color)(((??)backgroundImageColor) ?? Color.white);
			rEPOObjectPreview.previewObject = previewObject;
			rEPOObjectPreview.previewSize = new Vector2(184f, 345f);
			return rEPOObjectPreview;
		}

		internal static void OpenMenuPage(MenuPage menuPage, bool pageOnTop, bool resetPosition = true)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			object? value = REPOReflection.menuManager_CurrentMenuPage.GetValue(MenuManager.instance);
			MenuPage val = (MenuPage)((value is MenuPage) ? value : null);
			List<MenuPage> list = REPOReflection.menuManager_AddedPagesOnTop.GetValue(MenuManager.instance) as List<MenuPage>;
			if (pageOnTop && !Object.op_Implicit((Object)(object)val))
			{
				pageOnTop = false;
			}
			if (pageOnTop)
			{
				if (list == null || list.Contains(val))
				{
					return;
				}
			}
			else if (Object.op_Implicit((Object)(object)val))
			{
				REPOReflection.menuManager_PageInactiveAdd.Invoke(MenuManager.instance, new object[1] { val });
				val.PageStateSet((PageState)3);
			}
			((Component)menuPage).transform.SetAsLastSibling();
			((Behaviour)menuPage).enabled = true;
			if (resetPosition)
			{
				menuPage.ResetPage();
			}
			menuPage.PageStateSet((PageState)0);
			MenuManager.instance.PageAdd(menuPage);
			((MonoBehaviour)menuPage).StartCoroutine(REPOReflection.menuPage_LateStart.Invoke(menuPage, null) as IEnumerator);
			REPOReflection.menuPage_AddedPageOnTop.SetValue(menuPage, pageOnTop);
			if (!pageOnTop)
			{
				MenuManager.instance.PageSetCurrent(menuPage.menuPageIndex, menuPage);
				REPOReflection.menuPage_PageIsOnTopOfOtherPage.SetValue(menuPage, true);
				REPOReflection.menuPage_PageUnderThisPage.SetValue(menuPage, val);
			}
			else
			{
				REPOReflection.menuPage_ParentPage.SetValue(menuPage, val);
				list.Add(menuPage);
			}
		}

		internal static void CloseMenuPage(MenuPage menuPage, bool closePagesAddedOnTop)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (closePagesAddedOnTop)
			{
				CloseAllPagesAddedOnTop();
			}
			menuPage.PageStateSet((PageState)2);
			object? value = REPOReflection.menuPage_PageUnderThisPage.GetValue(menuPage);
			MenuPage val = (MenuPage)((value is MenuPage) ? value : null);
			if (val != null)
			{
				MenuManager.instance.PageSetCurrent(val.menuPageIndex, val);
			}
		}
	}
	public static class REPOReflection
	{
		public static readonly FieldInfo menuManager_CurrentMenuPage = AccessTools.Field(typeof(MenuManager), "currentMenuPage");

		public static readonly FieldInfo menuManager_AddedPagesOnTop = AccessTools.Field(typeof(MenuManager), "addedPagesOnTop");

		public static readonly FieldInfo menuPage_AddedPageOnTop = AccessTools.Field(typeof(MenuPage), "addedPageOnTop");

		public static readonly FieldInfo menuPage_PageUnderThisPage = AccessTools.Field(typeof(MenuPage), "pageUnderThisPage");

		public static readonly FieldInfo menuPage_ParentPage = AccessTools.Field(typeof(MenuPage), "parentPage");

		public static readonly FieldInfo menuPage_PageIsOnTopOfOtherPage = AccessTools.Field(typeof(MenuPage), "pageIsOnTopOfOtherPage");

		public static readonly FieldInfo menuPage_ScrollBoxes = AccessTools.Field(typeof(MenuPage), "scrollBoxes");

		public static readonly FieldInfo menuPage_CurrentPageState = AccessTools.Field(typeof(MenuPage), "currentPageState");

		public static readonly FieldInfo menuPage_AnimateAwayPosition = AccessTools.Field(typeof(MenuPage), "animateAwayPosition");

		public static readonly FieldInfo menuButton_ParentPage = AccessTools.Field(typeof(MenuButton), "parentPage");

		public static readonly FieldInfo menuButton_MenuScrollBox = AccessTools.Field(typeof(MenuButton), "menuScrollBox");

		public static readonly FieldInfo menuScrollBox_ScrollerEndPosition = AccessTools.Field(typeof(MenuScrollBox), "scrollerEndPosition");

		public static readonly FieldInfo menuScrollBox_ScrollerStartPosition = AccessTools.Field(typeof(MenuScrollBox), "scrollerStartPosition");

		public static readonly FieldInfo menuScrollBox_ScrollHandleTargetPosition = AccessTools.Field(typeof(MenuScrollBox), "scrollHandleTargetPosition");

		public static readonly FieldInfo menuScrollBox_ScrollHeight = AccessTools.Field(typeof(MenuScrollBox), "scrollHeight");

		public static readonly FieldInfo menuScrollBox_ScrollAmount = AccessTools.Field(typeof(MenuScrollBox), "scrollAmount");

		public static readonly FieldInfo menuScrollBox_ParentPage = AccessTools.Field(typeof(MenuScrollBox), "parentPage");

		public static readonly MethodInfo menuManager_PageInactiveAdd = AccessTools.Method(typeof(MenuManager), "PageInactiveAdd", (Type[])null, (Type[])null);

		public static readonly MethodInfo menuPage_LateStart = AccessTools.Method(typeof(MenuPage), "LateStart", (Type[])null, (Type[])null);
	}
	internal static class REPOTemplates
	{
		internal static readonly RectTransform pageDimmerTemplate;

		internal static readonly RectTransform simplePageTemplate;

		internal static readonly RectTransform buttonTemplate;

		internal static readonly RectTransform popupPageTemplate;

		internal static readonly RectTransform toggleTemplate;

		internal static readonly RectTransform sliderTemplate;

		internal static readonly RectTransform bigSliderTemplate;

		internal static readonly RectTransform labelTemplate;

		internal static readonly Transform avatarPreviewTemplate;

		static REPOTemplates()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected I4, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Invalid comparison between Unknown and I4
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			MenuManager instance = MenuManager.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				throw new NullReferenceException("Error fetching templates... Ensure you're not creating UI elements too early, use \"MenuAPI.AddElementTo...\"");
			}
			foreach (MenuPages menuPage in instance.menuPages)
			{
				Transform transform = menuPage.menuPage.transform;
				MenuPageIndex menuPageIndex = menuPage.menuPageIndex;
				switch ((int)menuPageIndex)
				{
				default:
					if ((int)menuPageIndex == 21)
					{
						bigSliderTemplate = (RectTransform)transform.Find("Scroll Box/Mask/Scroller").Find("Slider - Text to Speech Language");
					}
					break;
				case 0:
					simplePageTemplate = (RectTransform)transform;
					buttonTemplate = (RectTransform)((Transform)simplePageTemplate).Find("LeftTransform/Buttons/Menu Button - Quit game");
					break;
				case 2:
					pageDimmerTemplate = (RectTransform)transform.GetChild(0);
					break;
				case 4:
					popupPageTemplate = (RectTransform)transform;
					break;
				case 5:
				{
					Transform obj = transform.Find("Menu Scroll Box/Mask/Scroller");
					toggleTemplate = (RectTransform)obj.Find("Bool Setting - Push to Talk");
					sliderTemplate = (RectTransform)obj.Find("Slider - Text To speech");
					break;
				}
				case 6:
					labelTemplate = (RectTransform)transform.Find("Scroll Box/Mask/Scroller").Find("Header Movement");
					break;
				case 1:
					avatarPreviewTemplate = transform.Find("Menu Element Player Avatar");
					break;
				case 3:
					break;
				}
			}
		}
	}
}
namespace MenuLib.Structs
{
	public struct Padding
	{
		public float left;

		public float top;

		public float right;

		public float bottom;

		public Padding(float left, float top, float right, float bottom)
		{
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}
	}
}
namespace MenuLib.MonoBehaviors
{
	public sealed class REPOAvatarPreview : REPOElement
	{
		private PlayerAvatarMenu playerAvatarMenu;

		private Image backgroundImage;

		private RectTransform renderTextureRectTransform;

		public bool enableBackgroundImage
		{
			get
			{
				return ((Behaviour)backgroundImage).enabled;
			}
			set
			{
				((Behaviour)backgroundImage).enabled = value;
			}
		}

		public Color backgroundImageColor
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return ((Graphic)backgroundImage).color;
			}
			set
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				((Graphic)backgroundImage).color = value;
			}
		}

		public Vector2 previewSize
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return base.rectTransform.sizeDelta;
			}
			set
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				Vector2 val;
				if (value.x > value.y)
				{
					val = value;
					val.y = value.x / (8f / 15f);
					value = val;
				}
				else
				{
					val = value;
					val.x = value.y * (8f / 15f);
					value = val;
				}
				RectTransform obj = renderTextureRectTransform;
				val = (base.rectTransform.sizeDelta = value);
				obj.sizeDelta = val;
				((Transform)renderTextureRectTransform).localPosition = Vector3.zero;
			}
		}

		public PlayerAvatarVisuals playerAvatarVisuals { get; private set; }

		public Transform rigTransform => playerAvatarVisuals.meshParent.transform;

		private void Awake()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			LocalizationChangedEvent[] componentsInChildren = ((Component)this).GetComponentsInChildren<LocalizationChangedEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].localizedAsset = null;
			}
			base.rectTransform = ((Component)this).gameObject.AddComponent<RectTransform>();
			base.rectTransform.pivot = Vector2.right;
			RectTransform obj = base.rectTransform;
			Vector2 anchorMin = (base.rectTransform.anchorMax = Vector2.zero);
			obj.anchorMin = anchorMin;
			renderTextureRectTransform = (RectTransform)((Transform)base.rectTransform).GetChild(1);
			((Transform)renderTextureRectTransform).localPosition = Vector3.zero;
			playerAvatarMenu = ((Component)this).GetComponentInChildren<PlayerAvatarMenuHover>().playerAvatarMenu;
			playerAvatarVisuals = ((Component)playerAvatarMenu).GetComponentInChildren<PlayerAvatarVisuals>();
			backgroundImage = ((Component)this).gameObject.AddComponent<Image>();
			((Behaviour)backgroundImage).enabled = false;
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)playerAvatarMenu))
			{
				if (Object.op_Implicit((Object)(object)playerAvatarMenu.cameraAndStuff))
				{
					Object.Destroy((Object)(object)((Component)playerAvatarMenu.cameraAndStuff).gameObject);
				}
				Object.Destroy((Object)(object)((Component)playerAvatarMenu).gameObject);
			}
		}
	}
	public sealed class REPOButton : REPOElement
	{
		public MenuButton menuButton;

		public TextMeshProUGUI labelTMP;

		[Obsolete("Update the button clicked event using the 'onClick' field rather than through the button")]
		public Button button;

		public Action onClick;

		public Vector2? overrideButtonSize;

		private string previousText;

		private float previousFontSize;

		private float previousFontSizeMin;

		private float previousFontSizeMax;

		private Vector2? previousOverrideButtonSize;

		public Vector2 GetLabelSize()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return ((TMP_Text)labelTMP).GetPreferredValues();
		}

		private void Awake()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			LocalizationChangedEvent[] componentsInChildren = ((Component)this).GetComponentsInChildren<LocalizationChangedEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].localizedAsset = null;
			}
			Transform transform = ((Component)this).transform;
			base.rectTransform = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			button = ((Component)this).GetComponent<Button>();
			menuButton = ((Component)this).GetComponent<MenuButton>();
			labelTMP = ((Component)this).GetComponentInChildren<TextMeshProUGUI>();
			button.onClick = new ButtonClickedEvent();
			((UnityEvent)button.onClick).AddListener((UnityAction)delegate
			{
				onClick?.Invoke();
			});
			Object.Destroy((Object)(object)((Component)this).GetComponent<MenuButtonPopUp>());
		}

		private void Update()
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (((TMP_Text)labelTMP).text == previousText)
			{
				Vector2? val = overrideButtonSize;
				Vector2? val2 = previousOverrideButtonSize;
				if (val.HasValue == val2.HasValue && (!val.HasValue || val.GetValueOrDefault() == val2.GetValueOrDefault()) && Math.Abs(((TMP_Text)labelTMP).fontSize - previousFontSize) < float.Epsilon && Math.Abs(((TMP_Text)labelTMP).fontSizeMin - previousFontSizeMin) < float.Epsilon && Math.Abs(((TMP_Text)labelTMP).fontSizeMax - previousFontSizeMax) < float.Epsilon)
				{
					return;
				}
			}
			base.rectTransform.sizeDelta = (Vector2)(((??)overrideButtonSize) ?? GetLabelSize());
			previousText = ((TMP_Text)labelTMP).text;
			previousOverrideButtonSize = overrideButtonSize;
			previousFontSize = ((TMP_Text)labelTMP).fontSize;
			previousFontSizeMin = ((TMP_Text)labelTMP).fontSizeMin;
			previousFontSizeMax = ((TMP_Text)labelTMP).fontSizeMax;
		}

		private void OnTransformParentChanged()
		{
			REPOReflection.menuButton_ParentPage.SetValue(menuButton, ((Component)this).GetComponentInParent<MenuPage>());
			REPOReflection.menuButton_MenuScrollBox.SetValue(menuButton, ((Component)this).GetComponentInParent<MenuScrollBox>());
		}
	}
	public class REPOElement : MonoBehaviour
	{
		private REPOScrollViewElement _repoScrollViewElement;

		public RectTransform rectTransform { get; protected set; }

		public REPOScrollViewElement repoScrollViewElement
		{
			get
			{
				if (Object.op_Implicit((Object)(object)_repoScrollViewElement))
				{
					return _repoScrollViewElement;
				}
				return _repoScrollViewElement = ((Component)this).GetComponent<REPOScrollViewElement>();
			}
		}
	}
	public sealed class REPOInputField : REPOElement
	{
		public TextMeshProUGUI labelTMP;

		public REPOInputStringSystem inputStringSystem;

		private RectTransform inputAreaRectTransform;

		private MenuPage menuPage;

		private MenuScrollBox menuScrollBox;

		private string menuID;

		public Vector2 GetLabelSize()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return ((TMP_Text)labelTMP).GetPreferredValues();
		}

		private void Awake()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: 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_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0364: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0376: Unknown result type (might be due to invalid IL or missing references)
			//IL_0378: Unknown result type (might be due to invalid IL or missing references)
			LocalizationChangedEvent[] componentsInChildren = ((Component)this).GetComponentsInChildren<LocalizationChangedEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].localizedAsset = null;
			}
			Transform transform = ((Component)this).transform;
			base.rectTransform = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			menuPage = ((Component)this).GetComponentInParent<MenuPage>();
			menuScrollBox = ((Component)this).GetComponentInParent<MenuScrollBox>();
			menuID = SemiFunc.MenuGetSelectableID(((Component)this).gameObject);
			labelTMP = ((Component)this).GetComponentInChildren<TextMeshProUGUI>();
			RectTransform obj = base.rectTransform;
			obj.sizeDelta -= new Vector2(0f, 2f);
			RectTransform obj2 = ((TMP_Text)labelTMP).rectTransform;
			obj2.sizeDelta -= new Vector2(0f, 2f);
			Vector3 val = Vector3.left * 5.3f;
			Vector3 up = Vector3.up;
			Transform obj3 = ((Component)this).transform.Find("SliderBG");
			obj3.localPosition += val + up;
			Transform obj4 = ((Component)this).transform.Find("RawImage");
			obj4.localPosition += val + up;
			RectTransform obj5 = ((TMP_Text)labelTMP).rectTransform;
			((Transform)obj5).localPosition = ((Transform)obj5).localPosition + (val + up);
			RectTransform val2 = (RectTransform)((Component)this).transform.Find("RawImage (1) Left");
			((Transform)val2).localPosition = ((Component)this).transform.Find("RawImage").localPosition;
			val2.sizeDelta = new Vector2(148f, 21f);
			TextMeshProUGUI val3 = null;
			for (int j = 0; j < ((Component)this).transform.childCount; j++)
			{
				Transform child = ((Component)this).transform.GetChild(j);
				switch (((Object)child).name)
				{
				case "Option Box":
				case "Option Box Behind":
				case "RawImage (1) Right":
					Object.Destroy((Object)(object)((Component)child).gameObject);
					break;
				case "Button BUTTON":
					if (!Object.op_Implicit((Object)(object)val3))
					{
						val3 = ((Component)((Component)child).GetComponent<MenuButton>()).GetComponentInChildren<TextMeshProUGUI>();
						((TMP_Text)val3).transform.SetParent(child.parent);
					}
					Object.Destroy((Object)(object)((Component)child).gameObject);
					break;
				}
			}
			((TMP_Text)val3).rectTransform.pivot = Vector2.zero;
			((TMP_Text)val3).rectTransform.anchorMin = Vector2.zero;
			((TMP_Text)val3).rectTransform.anchorMax = Vector2.one;
			((TMP_Text)val3).fontStyle = (FontStyles)0;
			((TMP_Text)val3).enableAutoSizing = false;
			((TMP_Text)val3).alignment = (TextAlignmentOptions)513;
			((TMP_Text)val3).margin = new Vector4(2f, 2f, 0f, 0f);
			TextMeshProUGUI obj6 = val3;
			TextMeshProUGUI obj7 = val3;
			float num = (((TMP_Text)val3).fontSize = 18f);
			float fontSizeMax = (((TMP_Text)obj7).fontSizeMin = num);
			((TMP_Text)obj6).fontSizeMax = fontSizeMax;
			GameObject val4 = new GameObject("Input Area");
			val4.transform.parent = ((Component)this).transform;
			inputAreaRectTransform = val4.AddComponent<RectTransform>();
			inputAreaRectTransform.sizeDelta = new Vector2(146.5f, 20f);
			inputAreaRectTransform.pivot = Vector2.zero;
			((Transform)inputAreaRectTransform).localPosition = new Vector3(108f, 1.5f, 0f) + val;
			((Component)inputAreaRectTransform).gameObject.AddComponent<RectMask2D>();
			((TMP_Text)val3).transform.SetParent((Transform)(object)inputAreaRectTransform);
			Transform transform2 = ((TMP_Text)val3).transform;
			Vector2 val5 = (((TMP_Text)val3).rectTransform.sizeDelta = Vector2.op_Implicit(Vector3.zero));
			transform2.localPosition = Vector2.op_Implicit(val5);
			Object.Destroy((Object)(object)((Component)this).GetComponent<MenuSettingElement>());
			Object.Destroy((Object)(object)((Component)this).GetComponent<AudioButtonPushToTalk>());
			inputStringSystem = ((Component)this).gameObject.AddComponent<REPOInputStringSystem>();
			inputStringSystem.inputTMP = (TMP_Text)(object)val3;
			inputStringSystem.maskRectTransform = inputAreaRectTransform;
		}

		private void Update()
		{
			inputStringSystem.SetHovering(SemiFunc.UIMouseHover(menuPage, inputAreaRectTransform, menuID, 2f, 2f, menuScrollBox, (ScrollRect)null));
			if (Mouse.current.leftButton.wasPressedThisFrame)
			{
				inputStringSystem.isFocused = inputStringSystem.isHovering;
			}
		}

		private void OnTransformParentChanged()
		{
			menuScrollBox = ((Component)this).GetComponentInParent<MenuScrollBox>();
		}
	}
	public sealed class REPOInputStringSystem : MonoBehaviour
	{
		public struct Colors
		{
			public Color focusedColor;

			public Color hoverColor;

			public Color unfocusedColor;

			public Color placeholderColor;

			public Color characterAddedColor;

			public Color characterRemovedColor;

			public Colors()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: 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_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				focusedColor = Color.white;
				hoverColor = Color.white;
				unfocusedColor = new Color(0.5f, 0.5f, 0.5f);
				placeholderColor = new Color(1f, 0.6f, 0.4f);
				characterAddedColor = new Color(0.5f, 1f, 0.5f);
				characterRemovedColor = new Color(1f, 0.5f, 0.5f);
			}
		}

		public static bool hasAnyFocus;

		public TMP_Text inputTMP;

		public RectTransform maskRectTransform;

		public Action<string> onValueChanged;

		public Colors colors = new Colors();

		public string placeholder = string.Empty;

		public bool onlyNotifyOnSubmit;

		public bool disableMovement = true;

		private string previousValue;

		private float timeSinceCharacterAdded = 1f;

		private float timeSinceCharacterRemoved = 1f;

		private bool pressedSubmit;

		private bool _isFocused;

		public string currentValue { get; private set; }

		public bool isHovering { get; private set; }

		public bool isFocused
		{
			get
			{
				return _isFocused;
			}
			set
			{
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				if (!value)
				{
					if (_isFocused)
					{
						MoveTMP(reset: true);
					}
				}
				else if (!isFocused)
				{
					if (IsTMPInMask())
					{
						MoveTMP(reset: true);
					}
					else
					{
						float num = 0f - inputTMP.GetPreferredValues(currentValue + "<b>|</b>").x;
						Rect rect = maskRectTransform.rect;
						MoveTMP(reset: true, num + ((Rect)(ref rect)).width - 6f);
					}
					((SemiUI)ChatUI.instance).Hide();
				}
				hasAnyFocus = (_isFocused = value);
			}
		}

		private bool shouldUsePlaceholder => string.IsNullOrEmpty(currentValue);

		public void SetValue(string value, bool notify)
		{
			string text = (currentValue = value);
			previousValue = text;
			if (notify)
			{
				onValueChanged?.Invoke(value);
			}
		}

		public void SetHovering(bool value)
		{
			if (value && !isHovering)
			{
				MenuManager.instance.MenuEffectHover(SemiFunc.MenuGetPitchFromYPos(inputTMP.rectTransform), -1f);
			}
			isHovering = value;
		}

		private void Update()
		{
			if (!Object.op_Implicit((Object)(object)inputTMP))
			{
				return;
			}
			if (disableMovement && isFocused)
			{
				InputManager instance = InputManager.instance;
				if (instance != null)
				{
					instance.DisableMovement(0.1f);
				}
			}
			HandleInput();
			UpdateColors();
			if (pressedSubmit)
			{
				isFocused = false;
				pressedSubmit = false;
				if (onlyNotifyOnSubmit)
				{
					onValueChanged?.Invoke(currentValue);
				}
			}
			if (!onlyNotifyOnSubmit && previousValue != currentValue)
			{
				onValueChanged?.Invoke(currentValue);
			}
			if (isFocused)
			{
				inputTMP.text = currentValue;
				if (timeSinceCharacterAdded < 0.5f || timeSinceCharacterRemoved < 0.5f || Mathf.Sin(Time.time * 10f) > 0f)
				{
					TMP_Text obj = inputTMP;
					obj.text += "<b>|</b>";
				}
			}
			else
			{
				inputTMP.text = (shouldUsePlaceholder ? placeholder : currentValue);
			}
			previousValue = currentValue;
		}

		private void OnDestroy()
		{
			hasAnyFocus = false;
		}

		private void HandleInput()
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			if (timeSinceCharacterAdded < 1f)
			{
				timeSinceCharacterAdded += Time.deltaTime;
			}
			if (timeSinceCharacterRemoved < 1f)
			{
				timeSinceCharacterRemoved += Time.deltaTime;
			}
			if (!isFocused)
			{
				return;
			}
			string previousText = currentValue;
			if (Keyboard.current.ctrlKey.isPressed)
			{
				if (((ButtonControl)Keyboard.current.cKey).wasPressedThisFrame)
				{
					GUIUtility.systemCopyBuffer = currentValue;
				}
				else if (((ButtonControl)Keyboard.current.xKey).wasPressedThisFrame)
				{
					GUIUtility.systemCopyBuffer = currentValue;
					currentValue = null;
					timeSinceCharacterRemoved = 0f;
					MoveTMP(reset: true);
				}
				else if (((ButtonControl)Keyboard.current.vKey).wasPressedThisFrame)
				{
					currentValue += GUIUtility.systemCopyBuffer.Replace("\n", string.Empty);
					timeSinceCharacterAdded = 0f;
					if (IsTMPInMask())
					{
						MoveTMP(reset: true);
						return;
					}
					float num = 0f - inputTMP.GetPreferredValues(currentValue + "<b>|</b>").x;
					Rect rect = maskRectTransform.rect;
					MoveTMP(reset: true, num + ((Rect)(ref rect)).width - 6f);
				}
				return;
			}
			string inputString = Input.inputString;
			if (!(inputString == "\b"))
			{
				if (inputString == "\r")
				{
					pressedSubmit = true;
				}
				else if (!string.IsNullOrEmpty(inputString))
				{
					currentValue += inputString;
					timeSinceCharacterAdded = 0f;
					if (IsTMPInMask())
					{
						MoveTMP(reset: true);
					}
					else
					{
						MoveTMP(reset: false, 0f - CalculateTMPDifference(previousText, currentValue));
					}
				}
			}
			else if (currentValue.Length > 0)
			{
				currentValue = currentValue.Remove(currentValue.Length - 1, 1);
				timeSinceCharacterRemoved = 0f;
				if (IsTMPInMask())
				{
					MoveTMP(reset: true);
				}
				else
				{
					MoveTMP(reset: false, 0f - CalculateTMPDifference(previousText, currentValue));
				}
			}
		}

		private void UpdateColors()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (timeSinceCharacterAdded < 0.1f)
			{
				((Graphic)inputTMP).color = colors.characterAddedColor;
			}
			else if (timeSinceCharacterRemoved < 0.1f)
			{
				((Graphic)inputTMP).color = colors.characterRemovedColor;
			}
			else if (isHovering)
			{
				((Graphic)inputTMP).color = colors.hoverColor;
			}
			else if (isFocused)
			{
				((Graphic)inputTMP).color = colors.focusedColor;
			}
			else
			{
				((Graphic)inputTMP).color = (shouldUsePlaceholder ? colors.placeholderColor : colors.unfocusedColor);
			}
		}

		private void MoveTMP(bool reset, float moveBy = 0f)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (reset)
			{
				inputTMP.transform.localPosition = Vector3.zero;
			}
			if (moveBy != 0f)
			{
				Transform transform = inputTMP.transform;
				transform.localPosition += Vector3.right * moveBy;
			}
		}

		private float CalculateTMPDifference(string previousText, string newText)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return inputTMP.GetPreferredValues(newText).x - inputTMP.GetPreferredValues(previousText).x;
		}

		private bool IsTMPInMask()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			float x = inputTMP.GetPreferredValues(currentValue).x;
			Rect rect = maskRectTransform.rect;
			return x < ((Rect)(ref rect)).width - 6f;
		}
	}
	public sealed class REPOLabel : REPOElement
	{
		public TextMeshProUGUI labelTMP;

		private void Awake()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			LocalizationChangedEvent[] componentsInChildren = ((Component)this).GetComponentsInChildren<LocalizationChangedEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].localizedAsset = null;
			}
			base.rectTransform = (RectTransform)((Component)this).transform;
			labelTMP = ((Component)this).GetComponentInChildren<TextMeshProUGUI>();
			Vector2 sizeDelta = (((TMP_Text)labelTMP).rectTransform.pivot = (base.rectTransform.pivot = Vector2.zero));
			sizeDelta = (((TMP_Text)labelTMP).rectTransform.anchorMin = (((TMP_Text)labelTMP).rectTransform.anchorMax = Vector2.zero));
			RectTransform obj = ((TMP_Text)labelTMP).rectTransform;
			RectTransform obj2 = base.rectTransform;
			((Vector2)(ref sizeDelta))..ctor(200f, 30f);
			obj2.sizeDelta = sizeDelta;
			obj.sizeDelta = sizeDelta;
			((TMP_Text)labelTMP).fontSize = 30f;
			((TMP_Text)labelTMP).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)labelTMP).alignment = (TextAlignmentOptions)513;
			((TMP_Text)labelTMP).margin = Vector4.zero;
		}

		private void Start()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			((Transform)((TMP_Text)labelTMP).rectTransform).localPosition = Vector2.op_Implicit(Vector2.zero);
		}
	}
	public sealed class REPOObjectPreview : REPOElement
	{
		private PlayerAvatarMenuHover playerAvatarMenuHover;

		private Image backgroundImage;

		private RectTransform renderTextureRectTransform;

		private GameObject _previewObject;

		public GameObject previewObject
		{
			get
			{
				return _previewObject;
			}
			set
			{
				if (!((Object)(object)_previewObject == (Object)(object)value))
				{
					UpdatePreviewGameObject(value);
					_previewObject = value;
				}
			}
		}

		public bool enableBackgroundImage
		{
			get
			{
				return ((Behaviour)backgroundImage).enabled;
			}
			set
			{
				((Behaviour)backgroundImage).enabled = value;
			}
		}

		public Color backgroundImageColor
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return ((Graphic)backgroundImage).color;
			}
			set
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				((Graphic)backgroundImage).color = value;
			}
		}

		public Vector2 previewSize
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return base.rectTransform.sizeDelta;
			}
			set
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				Vector2 val;
				if (value.x > value.y)
				{
					val = value;
					val.y = value.x / (8f / 15f);
					value = val;
				}
				else
				{
					val = value;
					val.x = value.y * (8f / 15f);
					value = val;
				}
				RectTransform obj = renderTextureRectTransform;
				val = (base.rectTransform.sizeDelta = value);
				obj.sizeDelta = val;
				((Transform)renderTextureRectTransform).localPosition = Vector3.zero;
			}
		}

		private void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			base.rectTransform = ((Component)this).gameObject.AddComponent<RectTransform>();
			base.rectTransform.pivot = Vector2.right;
			RectTransform obj = base.rectTransform;
			Vector2 anchorMin = (base.rectTransform.anchorMax = Vector2.zero);
			obj.anchorMin = anchorMin;
			renderTextureRectTransform = (RectTransform)((Transform)base.rectTransform).GetChild(1);
			((Transform)renderTextureRectTransform).localPosition = Vector3.zero;
			playerAvatarMenuHover = ((Component)this).GetComponentInChildren<PlayerAvatarMenuHover>();
			((Component)playerAvatarMenuHover.playerAvatarMenu.cameraAndStuff).GetComponentInChildren<Camera>().farClipPlane = 100f;
			backgroundImage = ((Component)this).gameObject.AddComponent<Image>();
			((Behaviour)backgroundImage).enabled = false;
		}

		private void Start()
		{
			Transform transform = ((Component)playerAvatarMenuHover.playerAvatarMenu).transform;
			for (int i = 0; i < 3; i++)
			{
				Object.Destroy((Object)(object)((Component)transform.GetChild(i)).gameObject);
			}
		}

		private void OnDestroy()
		{
			if (!Object.op_Implicit((Object)(object)playerAvatarMenuHover) || !Object.op_Implicit((Object)(object)playerAvatarMenuHover.playerAvatarMenu))
			{
				return;
			}
			PlayerAvatarMenu playerAvatarMenu = playerAvatarMenuHover.playerAvatarMenu;
			if (Object.op_Implicit((Object)(object)playerAvatarMenu))
			{
				Transform cameraAndStuff = playerAvatarMenu.cameraAndStuff;
				if (Object.op_Implicit((Object)(object)cameraAndStuff))
				{
					Object.Destroy((Object)(object)((Component)cameraAndStuff).gameObject);
				}
				Object.Destroy((Object)(object)((Component)playerAvatarMenu).gameObject);
			}
		}

		private void UpdatePreviewGameObject(GameObject previewGameObject)
		{
			if (Object.op_Implicit((Object)(object)previewObject))
			{
				Object.Destroy((Object)(object)previewObject);
			}
			previewGameObject.transform.SetParent(((Component)playerAvatarMenuHover.playerAvatarMenu).transform, false);
			Rigidbody component = previewGameObject.GetComponent<Rigidbody>();
			if (component != null)
			{
				component.automaticInertiaTensor = false;
			}
		}
	}
	public sealed class REPOPopupPage : MonoBehaviour
	{
		public enum PresetSide
		{
			Left,
			Right
		}

		public delegate RectTransform ScrollViewBuilderDelegate(Transform scrollView);

		public delegate bool ShouldCloseMenuDelegate();

		public RectTransform rectTransform;

		public RectTransform maskRectTransform;

		public RectTransform scrollBarRectTransform;

		public MenuPage menuPage;

		public TextMeshProUGUI headerTMP;

		public MenuScrollBox menuScrollBox;

		public REPOScrollView scrollView;

		[Obsolete("Use onEscapePressed instead.")]
		public bool closeMenuOnEscape = true;

		public ShouldCloseMenuDelegate onEscapePressed;

		internal bool pageWasActivatedOnce;

		private bool hasStarted;

		private GameObject pageDimmerGameObject;

		private RawImage pageDimmerRawImage;

		private RectTransform scrollBarFillRectTransform;

		private RectTransform scrollBarOutlineRectTransform;

		private Vector2 defaultMaskSizeDelta;

		private Vector2 defaultMaskPosition;

		private Padding _maskPadding;

		public bool pageDimmerVisibility
		{
			get
			{
				return pageDimmerGameObject.gameObject.activeSelf;
			}
			set
			{
				pageDimmerGameObject.gameObject.SetActive(value);
			}
		}

		public bool isCachedPage { get; internal set; }

		public float pageDimmerOpacity
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				return ((Graphic)pageDimmerRawImage).color.a;
			}
			set
			{
				//IL_000c: 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_001a: Unknown result type (might be due to invalid IL or missing references)
				RawImage obj = pageDimmerRawImage;
				Color color = ((Graphic)pageDimmerRawImage).color;
				color.a = value;
				((Graphic)obj).color = color;
			}
		}

		public Padding maskPadding
		{
			get
			{
				return _maskPadding;
			}
			set
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				Vector2 sizeDelta = defaultMaskSizeDelta;
				Vector2 val = defaultMaskPosition;
				sizeDelta.x -= value.left + value.right;
				sizeDelta.y -= value.top + value.bottom;
				if (value.left != 0f)
				{
					val.x += value.left;
				}
				if (value.bottom != 0f)
				{
					val.y += value.bottom;
				}
				maskRectTransform.sizeDelta = sizeDelta;
				((Transform)maskRectTransform).localPosition = Vector2.op_Implicit(val);
				_maskPadding = value;
				UpdateScrollBarPosition();
			}
		}

		public void OpenPage(bool openOnTop)
		{
			MenuAPI.OpenMenuPage(menuPage, openOnTop, hasStarted);
			pageWasActivatedOnce = true;
			scrollView.UpdateElements();
		}

		public void ClosePage(bool closePagesAddedOnTop)
		{
			MenuAPI.CloseMenuPage(menuPage, closePagesAddedOnTop);
		}

		public void AddElement(MenuAPI.BuilderDelegate builderDelegate)
		{
			builderDelegate?.Invoke(((Component)this).transform);
		}

		public void AddElement(RectTransform elementRectTransform, Vector2 localPosition = default(Vector2))
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			((Transform)elementRectTransform).SetParent(((Component)this).transform);
			((Transform)elementRectTransform).localPosition = Vector2.op_Implicit(localPosition);
		}

		public void AddElementToScrollView(ScrollViewBuilderDelegate scrollViewBuilderDelegate, float topPadding = 0f, float bottomPadding = 0f)
		{
			object obj;
			if (scrollViewBuilderDelegate == null)
			{
				obj = null;
			}
			else
			{
				RectTransform obj2 = scrollViewBuilderDelegate((Transform)(object)menuScrollBox.scroller);
				obj = ((obj2 != null) ? ((Component)obj2).gameObject.AddComponent<REPOScrollViewElement>() : null);
			}
			REPOScrollViewElement rEPOScrollViewElement = (REPOScrollViewElement)obj;
			if (rEPOScrollViewElement != null)
			{
				rEPOScrollViewElement.onSettingChanged = scrollView.UpdateElements;
				rEPOScrollViewElement.topPadding = topPadding;
				rEPOScrollViewElement.bottomPadding = bottomPadding;
			}
		}

		public void AddElementToScrollView(RectTransform elementRectTransform, Vector2 localPosition = default(Vector2), float topPadding = 0f, float bottomPadding = 0f)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			REPOScrollViewElement rEPOScrollViewElement = ((Component)elementRectTransform).gameObject.AddComponent<REPOScrollViewElement>();
			if (rEPOScrollViewElement != null)
			{
				rEPOScrollViewElement.onSettingChanged = scrollView.UpdateElements;
				((Transform)elementRectTransform).SetParent((Transform)(object)menuScrollBox.scroller);
				((Transform)elementRectTransform).localPosition = Vector2.op_Implicit(localPosition);
				rEPOScrollViewElement.topPadding = topPadding;
				rEPOScrollViewElement.bottomPadding = bottomPadding;
			}
		}

		private void Awake()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Expected O, but got Unknown
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Expected O, but got Unknown
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Expected O, but got Unknown
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Expected O, but got Unknown
			LocalizationChangedEvent[] componentsInChildren = ((Component)this).GetComponentsInChildren<LocalizationChangedEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].localizedAsset = null;
			}
			menuPage = ((Component)this).GetComponent<MenuPage>();
			headerTMP = ((Component)this).GetComponentInChildren<TextMeshProUGUI>();
			menuScrollBox = ((Component)this).GetComponentInChildren<MenuScrollBox>();
			rectTransform = (RectTransform)new GameObject("Page Content", new Type[1] { typeof(RectTransform) }).transform;
			((Transform)rectTransform).SetParent(((Component)this).transform);
			((Component)this).transform.Find("Panel").SetParent((Transform)(object)rectTransform);
			((TMP_Text)headerTMP).transform.parent.SetParent((Transform)(object)rectTransform);
			((Component)menuScrollBox).transform.SetParent((Transform)(object)rectTransform);
			((TMP_Text)headerTMP).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)headerTMP).overflowMode = (TextOverflowModes)1;
			pageDimmerGameObject = ((Component)Object.Instantiate<RectTransform>(REPOTemplates.pageDimmerTemplate, ((Component)this).transform)).gameObject;
			pageDimmerGameObject.transform.SetAsFirstSibling();
			pageDimmerRawImage = pageDimmerGameObject.GetComponentInChildren<RawImage>();
			menuPage.menuPageIndex = (MenuPageIndex)(-1);
			RectTransform scroller = menuScrollBox.scroller;
			for (int j = 2; j < ((Transform)scroller).childCount; j++)
			{
				Object.Destroy((Object)(object)((Component)((Transform)scroller).GetChild(j)).gameObject);
			}
			scrollView = ((Component)scroller).gameObject.AddComponent<REPOScrollView>();
			scrollView.popupPage = this;
			maskRectTransform = (RectTransform)((Transform)scroller).parent;
			defaultMaskSizeDelta = maskRectTransform.sizeDelta;
			defaultMaskPosition = Vector2.op_Implicit(((Transform)maskRectTransform).localPosition);
			menuScrollBox.scroller.sizeDelta = maskRectTransform.sizeDelta;
			scrollBarRectTransform = (RectTransform)menuScrollBox.scrollBar.transform;
			scrollBarFillRectTransform = (RectTransform)((Transform)scrollBarRectTransform).Find("Scroll Bar Bg (2)");
			scrollBarOutlineRectTransform = (RectTransform)((Transform)scrollBarRectTransform).Find("Scroll Bar Bg (1)");
			maskPadding = new Padding(0f, 0f, 0f, 25f);
			Object.Destroy((Object)(object)((Component)this).GetComponent<MenuPageSettingsPage>());
			MenuAPI.customMenuPages.Add(menuPage, this);
		}

		private void Start()
		{
			//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)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			hasStarted = true;
			REPOReflection.menuScrollBox_ScrollerEndPosition.SetValue(menuScrollBox, 0);
			RectTransform scroller = menuScrollBox.scroller;
			Vector3 localPosition = ((Transform)menuScrollBox.scroller).localPosition;
			localPosition.y = 0f;
			((Transform)scroller).localPosition = localPosition;
			REPOReflection.menuPage_ScrollBoxes.SetValue(menuPage, 2);
			if (!pageWasActivatedOnce)
			{
				menuPage.PageStateSet((PageState)2);
			}
			scrollView.SetScrollPosition(0f);
		}

		private void Update()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			if (closeMenuOnEscape)
			{
				PageState val = (PageState)REPOReflection.menuPage_CurrentPageState.GetValue(menuPage);
				if (SemiFunc.InputDown((InputKey)18) && (int)val != 2 && (onEscapePressed == null || onEscapePressed()))
				{
					ClosePage(closePagesAddedOnTop: false);
				}
			}
		}

		private void OnDestroy()
		{
			MenuAPI.customMenuPages.Remove(menuPage);
		}

		private void UpdateScrollBarPosition()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)scrollBarRectTransform))
			{
				RectTransform obj = scrollBarRectTransform;
				Vector3 localPosition = ((Transform)scrollBarRectTransform).localPosition;
				localPosition.y = ((Transform)maskRectTransform).localPosition.y;
				((Transform)obj).localPosition = localPosition;
				Vector2 sizeDelta = scrollBarRectTransform.sizeDelta;
				sizeDelta.y = maskRectTransform.sizeDelta.y;
				RectTransform scrollBarBackground = menuScrollBox.scrollBarBackground;
				RectTransform obj2 = scrollBarFillRectTransform;
				Vector2 val = (scrollBarRectTransform.sizeDelta = sizeDelta);
				Vector2 sizeDelta2 = (obj2.sizeDelta = val);
				scrollBarBackground.sizeDelta = sizeDelta2;
				scrollBarOutlineRectTransform.sizeDelta = sizeDelta + new Vector2(4f, 4f);
			}
		}
	}
	public sealed class REPOScrollView : MonoBehaviour
	{
		public REPOPopupPage popupPage;

		public float? scrollSpeed;

		private REPOScrollViewElement[] scrollViewElements = Array.Empty<REPOScrollViewElement>();

		private float _spacing;

		public float spacing
		{
			get
			{
				return _spacing;
			}
			set
			{
				if (!(Math.Abs(_spacing - value) < float.Epsilon))
				{
					_spacing = value;
					UpdateElements();
				}
			}
		}

		public void UpdateElements()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: 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_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			scrollViewElements = ((Component)this).GetComponentsInChildren<REPOScrollViewElement>(true);
			float num = 0f;
			float num2 = popupPage.maskRectTransform.sizeDelta.y;
			REPOScrollViewElement[] array = scrollV

modules/REPOConfig.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using MenuLib;
using MenuLib.MonoBehaviors;
using MenuLib.Structs;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using REPOConfig.Extensions;
using REPOConfig.Strategies;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

[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("REPOConfig")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.0")]
[assembly: AssemblyInformationalVersion("1.3.0+af7f5a2b546cb0511d5cad2bad1e47e7fd1895c4")]
[assembly: AssemblyProduct("REPOConfig")]
[assembly: AssemblyTitle("REPOConfig")]
[assembly: AssemblyVersion("1.3.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 REPOConfig
{
	internal class ConfigEntryStore
	{
		internal Dictionary<ConfigEntryBase, object> ChangedEntryValues { get; } = new Dictionary<ConfigEntryBase, object>();

		internal Dictionary<ConfigEntryBase, object> OriginalEntryValues { get; } = new Dictionary<ConfigEntryBase, object>();
	}
	internal sealed class ConfigMenu
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<IConfigEntryStrategy, Type> <>9__5_0;

			public static Func<IConfigEntryStrategy, IConfigEntryStrategy> <>9__5_1;

			public static BuilderDelegate <>9__6_0;

			public static BuilderDelegate <>9__6_1;

			public static Action <>9__7_4;

			public static Action <>9__7_8;

			public static Action <>9__8_3;

			public static ShouldCloseMenuDelegate <>9__8_5;

			public static Action <>9__8_10;

			public static BuilderDelegate <>9__8_6;

			public static ScrollViewBuilderDelegate <>9__8_9;

			public static Func<ConfigEntryBase, string> <>9__9_0;

			public static ScrollViewBuilderDelegate <>9__9_2;

			public static Func<PluginInfo, string> <>9__11_0;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, ConfigEntryBase> <>9__11_1;

			internal Type <CreateStrategiesDictionary>b__5_0(IConfigEntryStrategy s)
			{
				return s.TargetType;
			}

			internal IConfigEntryStrategy <CreateStrategiesDictionary>b__5_1(IConfigEntryStrategy s)
			{
				return s;
			}

			internal void <Initialize>b__6_0(Transform parent)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				((TMP_Text)MenuAPI.CreateREPOButton("Mods", (Action)CreateModMenu, parent, new Vector2(152f, 60f)).labelTMP).fontSize = 28f;
			}

			internal void <Initialize>b__6_1(Transform parent)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				MenuAPI.CreateREPOButton("Mods", (Action)CreateModMenu, parent, new Vector2(126f, 65f));
			}

			internal void <CreateModMenu>b__7_4()
			{
				hasPopupMenuOpened = false;
			}

			internal void <CreateModMenu>b__7_8()
			{
				hasPopupMenuOpened = false;
			}

			internal void <CreateModList>b__8_3()
			{
				hasPopupMenuOpened = false;
			}

			internal bool <CreateModList>b__8_5()
			{
				if (!hasPopupMenuOpened)
				{
					return configEntryStore.ChangedEntryValues.Count == 0;
				}
				return false;
			}

			internal void <CreateModList>b__8_6(Transform mainPageParent)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				MenuAPI.CreateREPOButton("Save Changes", (Action)delegate
				{
					KeyValuePair<ConfigEntryBase, object>[] array = configEntryStore.ChangedEntryValues.ToArray();
					configEntryStore.ChangedEntryValues.Clear();
					KeyValuePair<ConfigEntryBase, object>[] array2 = array;
					for (int i = 0; i < array2.Length; i++)
					{
						KeyValuePair<ConfigEntryBase, object> keyValuePair = array2[i];
						var (val2, obj2) = (KeyValuePair<ConfigEntryBase, object>)(ref keyValuePair);
						object value = (val2.BoxedValue = obj2);
						configEntryStore.OriginalEntryValues[val2] = value;
					}
				}, mainPageParent, new Vector2(370f, 18f));
			}

			internal void <CreateModList>b__8_10()
			{
				KeyValuePair<ConfigEntryBase, object>[] array = configEntryStore.ChangedEntryValues.ToArray();
				configEntryStore.ChangedEntryValues.Clear();
				KeyValuePair<ConfigEntryBase, object>[] array2 = array;
				for (int i = 0; i < array2.Length; i++)
				{
					KeyValuePair<ConfigEntryBase, object> keyValuePair = array2[i];
					var (val2, obj2) = (KeyValuePair<ConfigEntryBase, object>)(ref keyValuePair);
					object value = (val2.BoxedValue = obj2);
					configEntryStore.OriginalEntryValues[val2] = value;
				}
			}

			internal RectTransform <CreateModList>b__8_9(Transform scrollView)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(0f, 10f);
				return ((REPOElement)MenuAPI.CreateREPOSpacer(scrollView, default(Vector2), val)).rectTransform;
			}

			internal string <CreateModEntries>b__9_0(ConfigEntryBase entry)
			{
				return entry.Definition.Section;
			}

			internal RectTransform <CreateModEntries>b__9_2(Transform scrollView)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(0f, 20f);
				return ((REPOElement)MenuAPI.CreateREPOSpacer(scrollView, default(Vector2), val)).rectTransform;
			}

			internal string <GetModConfigEntries>b__11_0(PluginInfo p)
			{
				return p.Metadata.Name;
			}

			internal ConfigEntryBase <GetModConfigEntries>b__11_1(KeyValuePair<ConfigDefinition, ConfigEntryBase> configEntry)
			{
				return configEntry.Value;
			}
		}

		private static readonly ConfigEntryStore configEntryStore = new ConfigEntryStore();

		private static readonly IDictionary<Type, IConfigEntryStrategy> configEntryStrategies = CreateStrategiesDictionary();

		internal static REPOButton lastClickedModButton;

		private static readonly List<REPOButton> currentModButtons = new List<REPOButton>();

		private static bool hasPopupMenuOpened;

		private static Dictionary<Type, IConfigEntryStrategy> CreateStrategiesDictionary()
		{
			return new List<IConfigEntryStrategy>(4)
			{
				new StringConfigEntryStrategy(configEntryStore),
				new BooleanConfigEntryStrategy(configEntryStore),
				new IntConfigEntryStrategy(configEntryStore),
				new FloatConfigEntryStrategy(configEntryStore)
			}.ToDictionary((IConfigEntryStrategy s) => s.TargetType, (IConfigEntryStrategy s) => s);
		}

		internal static void Initialize()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			object obj = <>c.<>9__6_0;
			if (obj == null)
			{
				BuilderDelegate val = delegate(Transform parent)
				{
					//IL_002b: Unknown result type (might be due to invalid IL or missing references)
					((TMP_Text)MenuAPI.CreateREPOButton("Mods", (Action)CreateModMenu, parent, new Vector2(152f, 60f)).labelTMP).fontSize = 28f;
				};
				<>c.<>9__6_0 = val;
				obj = (object)val;
			}
			MenuAPI.AddElementToLobbyMenu((BuilderDelegate)obj);
			object obj2 = <>c.<>9__6_1;
			if (obj2 == null)
			{
				BuilderDelegate val2 = delegate(Transform parent)
				{
					//IL_002b: Unknown result type (might be due to invalid IL or missing references)
					MenuAPI.CreateREPOButton("Mods", (Action)CreateModMenu, parent, new Vector2(126f, 65f));
				};
				<>c.<>9__6_1 = val2;
				obj2 = (object)val2;
			}
			MenuAPI.AddElementToEscapeMenu((BuilderDelegate)obj2);
		}

		internal static void CreateModMenu()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			configEntryStore.ChangedEntryValues.Clear();
			lastClickedModButton = null;
			REPOPopupPage repoPopupPage = MenuAPI.CreateREPOPopupPage("Mods", (PresetSide)0, false, true, 0f);
			repoPopupPage.scrollView.scrollSpeed = 3f;
			REPOPopupPage obj = repoPopupPage;
			Padding maskPadding = repoPopupPage.maskPadding;
			maskPadding.top = 35f;
			obj.maskPadding = maskPadding;
			REPOPopupPage obj2 = repoPopupPage;
			obj2.onEscapePressed = (ShouldCloseMenuDelegate)Delegate.Combine((Delegate?)(object)obj2.onEscapePressed, (Delegate?)(ShouldCloseMenuDelegate)delegate
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				if (hasPopupMenuOpened)
				{
					return false;
				}
				if (configEntryStore.ChangedEntryValues.Count == 0)
				{
					return true;
				}
				MenuAPI.OpenPopup("Unsaved Changes", Color.red, "You have unsaved changes, are you sure you want to exit?", (Action)delegate
				{
					repoPopupPage.ClosePage(true);
					configEntryStore.ChangedEntryValues.Clear();
					hasPopupMenuOpened = false;
				}, (Action)delegate
				{
					hasPopupMenuOpened = false;
				});
				hasPopupMenuOpened = true;
				return false;
			});
			repoPopupPage.AddElement((BuilderDelegate)delegate(Transform parent)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				((Component)MenuAPI.CreateREPOInputField("Mod Search", (Action<string>)delegate(string s)
				{
					string text = (string.IsNullOrEmpty(s) ? null : s.ToLower().Trim());
					foreach (REPOButton currentModButton in currentModButtons)
					{
						((REPOElement)currentModButton).repoScrollViewElement.visibility = text == null || ((TMP_Text)currentModButton.labelTMP).text.ToLower().Contains(text);
					}
					repoPopupPage.scrollView.SetScrollPosition(0f);
				}, parent, new Vector2(83f, 272f), false, "", "")).transform.localScale = Vector3.one * 0.95f;
			});
			CreateModList(repoPopupPage);
			repoPopupPage.AddElement((BuilderDelegate)delegate(Transform parent)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				MenuAPI.CreateREPOButton("Back", (Action)delegate
				{
					//IL_002a: Unknown result type (might be due to invalid IL or missing references)
					if (configEntryStore.ChangedEntryValues.Count == 0 || hasPopupMenuOpened)
					{
						repoPopupPage.ClosePage(true);
					}
					else
					{
						MenuAPI.OpenPopup("Unsaved Changes", Color.red, "You have unsaved changes, are you sure you want to exit?", (Action)delegate
						{
							repoPopupPage.ClosePage(true);
							configEntryStore.ChangedEntryValues.Clear();
							hasPopupMenuOpened = false;
						}, (Action)delegate
						{
							hasPopupMenuOpened = false;
						});
						hasPopupMenuOpened = true;
					}
				}, parent, new Vector2(66f, 18f));
			});
			repoPopupPage.OpenPage(false);
		}

		private static void CreateModList(REPOPopupPage mainModPage)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			currentModButtons.Clear();
			foreach (KeyValuePair<string, ConfigEntryBase[]> modConfigEntry in GetModConfigEntries())
			{
				var (modName, configEntryBases) = (KeyValuePair<string, ConfigEntryBase[]>)(ref modConfigEntry);
				mainModPage.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform parent)
				{
					//IL_0018: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0055: Unknown result type (might be due to invalid IL or missing references)
					//IL_005a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0067: Unknown result type (might be due to invalid IL or missing references)
					REPOButton modButton = MenuAPI.CreateREPOButton(modName, (Action)null, parent, default(Vector2));
					((TMP_Text)modButton.labelTMP).fontStyle = (FontStyles)0;
					if (modName.Length > 24)
					{
						REPOButton obj = modButton;
						Vector2 labelSize = modButton.GetLabelSize();
						labelSize.x = 250f;
						obj.overrideButtonSize = labelSize;
						REPOTextScroller val = ((Component)modButton.labelTMP).gameObject.AddComponent<REPOTextScroller>();
						val.maxCharacters = 24;
						((MonoBehaviour)MenuManager.instance).StartCoroutine(val.Animate());
					}
					BuilderDelegate val4 = default(BuilderDelegate);
					modButton.onClick = delegate
					{
						//IL_0030: Unknown result type (might be due to invalid IL or missing references)
						if (!((Object)(object)lastClickedModButton == (Object)(object)modButton))
						{
							if (configEntryStore.ChangedEntryValues.Count == 0)
							{
								OpenPage();
							}
							else
							{
								MenuAPI.OpenPopup("Unsaved Changes", Color.red, "You have unsaved changes, are you sure you want to exit?", (Action)delegate
								{
									configEntryStore.ChangedEntryValues.Clear();
									OpenPage();
									hasPopupMenuOpened = false;
								}, (Action)delegate
								{
									hasPopupMenuOpened = false;
								});
								hasPopupMenuOpened = true;
							}
						}
					};
					currentModButtons.Add(modButton);
					return ((REPOElement)modButton).rectTransform;
					void OpenPage()
					{
						//IL_0064: Unknown result type (might be due to invalid IL or missing references)
						//IL_0069: Unknown result type (might be due to invalid IL or missing references)
						//IL_006f: Expected O, but got Unknown
						//IL_008e: Unknown result type (might be due to invalid IL or missing references)
						//IL_0093: Unknown result type (might be due to invalid IL or missing references)
						//IL_0099: Expected O, but got Unknown
						//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
						//IL_00e9: Expected O, but got Unknown
						//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
						//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
						//IL_00bd: Expected O, but got Unknown
						//IL_00c2: Expected O, but got Unknown
						//IL_0103: Unknown result type (might be due to invalid IL or missing references)
						//IL_0108: Unknown result type (might be due to invalid IL or missing references)
						//IL_010e: Expected O, but got Unknown
						MenuAPI.CloseAllPagesAddedOnTop();
						REPOPopupPage modPage = MenuAPI.CreateREPOPopupPage(modName, (PresetSide)1, false, false, 5f);
						modPage.scrollView.scrollSpeed = 3f;
						REPOPopupPage obj2 = modPage;
						object obj3 = <>c.<>9__8_5;
						if (obj3 == null)
						{
							ShouldCloseMenuDelegate val2 = () => !hasPopupMenuOpened && configEntryStore.ChangedEntryValues.Count == 0;
							<>c.<>9__8_5 = val2;
							obj3 = (object)val2;
						}
						obj2.onEscapePressed = (ShouldCloseMenuDelegate)obj3;
						REPOPopupPage obj4 = modPage;
						object obj5 = <>c.<>9__8_6;
						if (obj5 == null)
						{
							BuilderDelegate val3 = delegate(Transform mainPageParent)
							{
								//IL_002f: Unknown result type (might be due to invalid IL or missing references)
								MenuAPI.CreateREPOButton("Save Changes", (Action)delegate
								{
									KeyValuePair<ConfigEntryBase, object>[] array2 = configEntryStore.ChangedEntryValues.ToArray();
									configEntryStore.ChangedEntryValues.Clear();
									KeyValuePair<ConfigEntryBase, object>[] array3 = array2;
									for (int i = 0; i < array3.Length; i++)
									{
										KeyValuePair<ConfigEntryBase, object> keyValuePair2 = array3[i];
										var (val9, obj11) = (KeyValuePair<ConfigEntryBase, object>)(ref keyValuePair2);
										object value = (val9.BoxedValue = obj11);
										configEntryStore.OriginalEntryValues[val9] = value;
									}
								}, mainPageParent, new Vector2(370f, 18f));
							};
							<>c.<>9__8_6 = val3;
							obj5 = (object)val3;
						}
						obj4.AddElement((BuilderDelegate)obj5);
						REPOPopupPage obj6 = modPage;
						BuilderDelegate obj7 = val4;
						if (obj7 == null)
						{
							BuilderDelegate val5 = delegate(Transform mainPageParent)
							{
								//IL_002f: Unknown result type (might be due to invalid IL or missing references)
								MenuAPI.CreateREPOButton("Revert", (Action)delegate
								{
									if (configEntryStore.ChangedEntryValues.Count != 0)
									{
										configEntryStore.ChangedEntryValues.Clear();
										OpenPage();
									}
								}, mainPageParent, new Vector2(585f, 18f));
							};
							BuilderDelegate val6 = val5;
							val4 = val5;
							obj7 = val6;
						}
						obj6.AddElement(obj7);
						modPage.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform scrollView)
						{
							//IL_0036: Unknown result type (might be due to invalid IL or missing references)
							//IL_003c: Unknown result type (might be due to invalid IL or missing references)
							//IL_0054: Unknown result type (might be due to invalid IL or missing references)
							//IL_0059: Unknown result type (might be due to invalid IL or missing references)
							//IL_0062: Unknown result type (might be due to invalid IL or missing references)
							//IL_0078: Unknown result type (might be due to invalid IL or missing references)
							//IL_007d: Unknown result type (might be due to invalid IL or missing references)
							REPOButton val8 = MenuAPI.CreateREPOButton("Reset To Default", (Action)delegate
							{
								//IL_0059: Unknown result type (might be due to invalid IL or missing references)
								MenuAPI.OpenPopup("Reset " + modName + "'" + (modName.ToLower().EndsWith('s') ? string.Empty : "s") + " settings?", Color.red, "Are you sure you want to reset all settings back to default?", (Action)ResetToDefault, (Action)null);
							}, scrollView, default(Vector2));
							RectTransform rectTransform = ((REPOElement)val8).rectTransform;
							Rect rect = modPage.maskRectTransform.rect;
							((Transform)rectTransform).localPosition = Vector2.op_Implicit(new Vector2((((Rect)(ref rect)).width - val8.GetLabelSize().x) * 0.5f, 0f));
							return ((REPOElement)val8).rectTransform;
						}, 0f, 0f);
						REPOPopupPage obj8 = modPage;
						object obj9 = <>c.<>9__8_9;
						if (obj9 == null)
						{
							ScrollViewBuilderDelegate val7 = delegate(Transform scrollView)
							{
								//IL_0014: Unknown result type (might be due to invalid IL or missing references)
								//IL_001a: Unknown result type (might be due to invalid IL or missing references)
								//IL_001b: Unknown result type (might be due to invalid IL or missing references)
								Vector2 val8 = default(Vector2);
								((Vector2)(ref val8))..ctor(0f, 10f);
								return ((REPOElement)MenuAPI.CreateREPOSpacer(scrollView, default(Vector2), val8)).rectTransform;
							};
							<>c.<>9__8_9 = val7;
							obj9 = (object)val7;
						}
						obj8.AddElementToScrollView((ScrollViewBuilderDelegate)obj9, 0f, 0f);
						CreateModEntries(modPage, configEntryBases);
						modPage.OpenPage(true);
						lastClickedModButton = modButton;
					}
					void ResetToDefault()
					{
						ConfigEntryBase[] array2 = configEntryBases;
						foreach (ConfigEntryBase obj2 in array2)
						{
							obj2.BoxedValue = obj2.DefaultValue;
						}
						configEntryStore.ChangedEntryValues.Clear();
						OpenPage();
					}
				}, 0f, 0f);
			}
		}

		private static void CreateModEntries(REPOPopupPage modPage, ConfigEntryBase[] configEntryBases)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			foreach (IGrouping<string, ConfigEntryBase> group in from val2 in configEntryBases
				group val2 by val2.Definition.Section)
			{
				modPage.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform scrollView)
				{
					//IL_0013: Unknown result type (might be due to invalid IL or missing references)
					//IL_0019: Unknown result type (might be due to invalid IL or missing references)
					REPOLabel obj2 = MenuAPI.CreateREPOLabel(FixNaming(group.Key), scrollView, default(Vector2));
					((TMP_Text)obj2.labelTMP).fontStyle = (FontStyles)1;
					return ((REPOElement)obj2).rectTransform;
				}, 0f, 0f);
				foreach (ConfigEntryBase entry in group)
				{
					string modName = FixNaming(entry.Definition.Key);
					configEntryStore.OriginalEntryValues.Remove(entry);
					configEntryStore.OriginalEntryValues.Add(entry, entry.BoxedValue);
					if (configEntryStrategies.TryGetValue(entry.SettingType, out var strategy))
					{
						modPage.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform scrollView) => strategy.Execute(scrollView, modName, entry)), 0f, 0f);
					}
					else if (entry.SettingType.IsSubclassOf(typeof(Enum)))
					{
						HandleEnumEntry(modPage, modName, entry);
					}
				}
				object obj = <>c.<>9__9_2;
				if (obj == null)
				{
					ScrollViewBuilderDelegate val = delegate(Transform scrollView)
					{
						//IL_0014: Unknown result type (might be due to invalid IL or missing references)
						//IL_001a: Unknown result type (might be due to invalid IL or missing references)
						//IL_001b: Unknown result type (might be due to invalid IL or missing references)
						Vector2 val2 = default(Vector2);
						((Vector2)(ref val2))..ctor(0f, 20f);
						return ((REPOElement)MenuAPI.CreateREPOSpacer(scrollView, default(Vector2), val2)).rectTransform;
					};
					<>c.<>9__9_2 = val;
					obj = (object)val;
				}
				modPage.AddElementToScrollView((ScrollViewBuilderDelegate)obj, 0f, 0f);
			}
		}

		private static void HandleEnumEntry(REPOPopupPage modPage, string modName, ConfigEntryBase entry)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			Type enumType = entry.SettingType;
			string[] values = Enum.GetNames(enumType);
			modPage.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform scrollView)
			{
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				REPOSlider val = MenuAPI.CreateREPOSlider(modName, string.Empty, (Action<int>)delegate(int i)
				{
					object obj = Enum.Parse(enumType, values[i]);
					if (configEntryStore.OriginalEntryValues.TryGetValue(entry, out var value) && obj == value)
					{
						configEntryStore.ChangedEntryValues.Remove(entry);
					}
					else
					{
						configEntryStore.ChangedEntryValues[entry] = obj;
					}
				}, scrollView, values, entry.BoxedValue.ToString(), default(Vector2), "", "", (BarBehavior)0);
				TextMeshProUGUI descriptionTMP = val.descriptionTMP;
				TextMeshProUGUI labelTMP = val.labelTMP;
				FontStyles fontStyle = (FontStyles)0;
				((TMP_Text)labelTMP).fontStyle = (FontStyles)0;
				((TMP_Text)descriptionTMP).fontStyle = fontStyle;
				return ((REPOElement)val).rectTransform;
			}, 0f, 0f);
		}

		private static Dictionary<string, ConfigEntryBase[]> GetModConfigEntries()
		{
			Dictionary<string, ConfigEntryBase[]> dictionary = new Dictionary<string, ConfigEntryBase[]>();
			foreach (PluginInfo item in Chainloader.PluginInfos.Values.OrderBy((PluginInfo p) => p.Metadata.Name))
			{
				List<ConfigEntryBase> list = new List<ConfigEntryBase>();
				foreach (ConfigEntryBase item2 in ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)item.Instance.Config).Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> configEntry) => configEntry.Value))
				{
					if (!item2.HasTag("HideFromREPOConfig") && !item2.HasTag("HideREPOConfig"))
					{
						list.Add(item2);
					}
				}
				if (list.Count > 0)
				{
					dictionary.TryAdd(FixNaming(item.Metadata.Name), list.ToArray());
				}
			}
			return dictionary;
		}

		private static string FixNaming(string input)
		{
			input = Regex.Replace(input, "([a-z])([A-Z])", "$1 $2");
			input = Regex.Replace(input, "([A-Z])([A-Z][a-z])", "$1 $2");
			input = Regex.Replace(input, "\\s+", " ");
			input = Regex.Replace(input, "([A-Z]\\.)\\s([A-Z]\\.)", "$1$2");
			return input.Trim();
		}
	}
	[BepInPlugin("nickklmao.repoconfig", "REPOConfig", "1.3.0")]
	[BepInDependency("nickklmao.menulib", "2.6.0")]
	internal sealed class Entry : BaseUnityPlugin
	{
		private const string MOD_NAME = "REPOConfig";

		internal static readonly ManualLogSource logger = Logger.CreateLogSource("REPOConfig");

		private static ConfigEntry<bool> showInGame;

		private static void MenuPageMain_StartHook(Action<MenuPageMain> orig, MenuPageMain self)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)self).transform.Find("LeftTransform/Buttons");
			if (!Object.op_Implicit((Object)(object)((Component)val).GetComponent<VerticalLayoutGroup>()))
			{
				VerticalLayoutGroup obj = ComponentHolderProtocol.AddComponent<VerticalLayoutGroup>((Object)(object)val);
				((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = false;
				((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = false;
			}
			REPOButton val2 = MenuAPI.CreateREPOButton("Mods", (Action)ConfigMenu.CreateModMenu, val, new Vector2(0f, 0f));
			List<Transform> list = (from Transform transform in (IEnumerable)val
				where ((Object)transform).name.Contains("Menu Button")
				orderby transform.localPosition.y descending
				select transform).ToList();
			list.Insert(list.Count - 1, ((Component)val2).transform);
			Transform val3 = list[list.Count - 1];
			((Component)val2).transform.SetSiblingIndex(val3.GetSiblingIndex());
			float num = 230f;
			foreach (Transform item in list)
			{
				Vector3 localPosition = item.localPosition;
				localPosition.y = num;
				item.localPosition = localPosition;
				num -= 30f;
			}
			orig(self);
		}

		private void Awake()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			showInGame = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Show In Game", true, new ConfigDescription(string.Empty, (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" }));
			if (showInGame.Value)
			{
				logger.LogDebug((object)"Hooking `MenuPageMain.Start`");
				new Hook((MethodBase)AccessTools.Method(typeof(MenuPageMain), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageMain>, MenuPageMain>(MenuPageMain_StartHook));
				ConfigMenu.Initialize();
			}
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	[Obsolete("This attribute is not used and will be removed eventually.")]
	public class REPOConfigEntryAttribute : Attribute
	{
		public REPOConfigEntryAttribute(string displayName)
		{
		}

		public REPOConfigEntryAttribute(string displayName, int min, int max, string prefix = "", string postfix = "")
		{
		}

		public REPOConfigEntryAttribute(string displayName, float min, float max, string prefix = "", string postfix = "")
		{
		}

		public REPOConfigEntryAttribute(string displayName, float min, float max, int precision = 2, string prefix = "", string postfix = "")
		{
		}

		public REPOConfigEntryAttribute(string displayName, string prefix = "", string postfix = "")
		{
		}

		public REPOConfigEntryAttribute(string displayName, params string[] customOptions)
		{
		}
	}
}
namespace REPOConfig.Strategies
{
	internal class BooleanConfigEntryStrategy : ConfigEntryStrategy<bool>
	{
		internal BooleanConfigEntryStrategy(ConfigEntryStore configEntryStore)
			: base(configEntryStore)
		{
		}

		protected override RectTransform Execute(Transform scrollView, string modName, ConfigEntry<bool> entry)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			Action<bool> obj = delegate(bool b)
			{
				if (base.ConfigEntryStore.OriginalEntryValues.TryGetValue((ConfigEntryBase)(object)entry, out var value2) && b == (bool)value2)
				{
					base.ConfigEntryStore.ChangedEntryValues.Remove((ConfigEntryBase)(object)entry);
				}
				else
				{
					base.ConfigEntryStore.ChangedEntryValues[(ConfigEntryBase)(object)entry] = b;
				}
			};
			bool value = entry.Value;
			REPOToggle obj2 = MenuAPI.CreateREPOToggle(modName, obj, scrollView, default(Vector2), "ON", "OFF", value);
			((TMP_Text)obj2.labelTMP).fontStyle = (FontStyles)0;
			return ((REPOElement)obj2).rectTransform;
		}
	}
	internal abstract class ConfigEntryStrategy<T> : IConfigEntryStrategy
	{
		public Type TargetType { get; } = typeof(T);

		protected ConfigEntryStore ConfigEntryStore { get; }

		protected ConfigEntryStrategy(ConfigEntryStore configEntryStore)
		{
			ConfigEntryStore = configEntryStore;
		}

		public RectTransform Execute(Transform scrollView, string modName, ConfigEntryBase entry)
		{
			return Execute(scrollView, modName, (ConfigEntry<T>)(object)entry);
		}

		protected abstract RectTransform Execute(Transform scrollView, string modName, ConfigEntry<T> entry);
	}
	internal interface IConfigEntryStrategy
	{
		Type TargetType { get; }

		RectTransform Execute(Transform scrollView, string modName, ConfigEntryBase entry);
	}
	internal class FloatConfigEntryStrategy : ConfigEntryStrategy<float>
	{
		internal FloatConfigEntryStrategy(ConfigEntryStore configEntryStore)
			: base(configEntryStore)
		{
		}

		protected override RectTransform Execute(Transform scrollView, string modName, ConfigEntry<float> entry)
		{
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			int precision = 2;
			float num;
			float num2;
			if (((ConfigEntryBase)entry).Description.AcceptableValues is AcceptableValueRange<float> val)
			{
				num = val.MinValue;
				num2 = val.MaxValue;
				precision = Mathf.Max(new int[4]
				{
					num.GetDecimalPlaces(),
					num2.GetDecimalPlaces(),
					((float)((ConfigEntryBase)entry).DefaultValue).GetDecimalPlaces(),
					2
				});
			}
			else
			{
				float num3 = Math.Abs(entry.Value);
				num = ((num3 == 0f) ? (0f - (num2 = 100f)) : (((double)num3 <= 0.001) ? (0f - (num2 = 10f)) : (((double)num3 <= 0.01) ? (0f - (num2 = 50f)) : ((!(num3 <= 100f)) ? (0f - (num2 = num3 * 2f)) : (0f - (num2 = num3 * 3f))))));
			}
			float result = 0f;
			int num4;
			if (((ConfigEntryBase)(object)entry).TryGetTagValue("REPOConfigStep", out var value) && float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
			{
				num4 = ((result > 0f) ? 1 : 0);
				if (num4 != 0)
				{
					precision = Mathf.Max(precision, result.GetDecimalPlaces());
				}
			}
			else
			{
				num4 = 0;
			}
			string empty = string.Empty;
			Action<float> obj = delegate(float f)
			{
				f = (float)Math.Round(f, precision);
				if (base.ConfigEntryStore.OriginalEntryValues.TryGetValue((ConfigEntryBase)(object)entry, out var value3) && Math.Abs(f - (float)value3) < float.Epsilon)
				{
					base.ConfigEntryStore.ChangedEntryValues.Remove((ConfigEntryBase)(object)entry);
				}
				else
				{
					base.ConfigEntryStore.ChangedEntryValues[(ConfigEntryBase)(object)entry] = f;
				}
			};
			float value2 = entry.Value;
			float num5 = num;
			float num6 = num2;
			int num7 = precision;
			REPOSlider val2 = MenuAPI.CreateREPOSlider(modName, empty, obj, scrollView, default(Vector2), num5, num6, num7, value2, "", "", (BarBehavior)0);
			TextMeshProUGUI descriptionTMP = val2.descriptionTMP;
			TextMeshProUGUI labelTMP = val2.labelTMP;
			FontStyles fontStyle = (FontStyles)0;
			((TMP_Text)labelTMP).fontStyle = (FontStyles)0;
			((TMP_Text)descriptionTMP).fontStyle = fontStyle;
			if (num4 != 0)
			{
				val2.precisionDecimal = result;
			}
			return ((REPOElement)val2).rectTransform;
		}
	}
	internal class IntConfigEntryStrategy : ConfigEntryStrategy<int>
	{
		internal IntConfigEntryStrategy(ConfigEntryStore configEntryStore)
			: base(configEntryStore)
		{
		}

		protected override RectTransform Execute(Transform scrollView, string modName, ConfigEntry<int> entry)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			int num;
			int num2;
			int num4;
			if (((ConfigEntryBase)entry).Description.AcceptableValues is AcceptableValueRange<int> val)
			{
				num = val.MinValue;
				num2 = val.MaxValue;
			}
			else
			{
				int num3 = Math.Abs(entry.Value);
				num4 = ((num3 > 100) ? (-(num2 = num3 * 2)) : ((num3 != 0) ? (-(num2 = num3 * 3)) : (-(num2 = 100))));
				num = num4;
			}
			string empty = string.Empty;
			Action<int> obj = delegate(int i)
			{
				if (base.ConfigEntryStore.OriginalEntryValues.TryGetValue((ConfigEntryBase)(object)entry, out var value2) && i == (int)value2)
				{
					base.ConfigEntryStore.ChangedEntryValues.Remove((ConfigEntryBase)(object)entry);
				}
				else
				{
					base.ConfigEntryStore.ChangedEntryValues[(ConfigEntryBase)(object)entry] = i;
				}
			};
			num4 = entry.Value;
			int num5 = num;
			int num6 = num2;
			REPOSlider val2 = MenuAPI.CreateREPOSlider(modName, empty, obj, scrollView, default(Vector2), num5, num6, num4, "", "", (BarBehavior)0);
			TextMeshProUGUI descriptionTMP = val2.descriptionTMP;
			TextMeshProUGUI labelTMP = val2.labelTMP;
			FontStyles fontStyle = (FontStyles)0;
			((TMP_Text)labelTMP).fontStyle = (FontStyles)0;
			((TMP_Text)descriptionTMP).fontStyle = fontStyle;
			if (((ConfigEntryBase)(object)entry).TryGetTagValue("REPOConfigStep", out var value) && int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && result > 0)
			{
				val2.precisionDecimal = result;
			}
			return ((REPOElement)val2).rectTransform;
		}
	}
	internal class StringConfigEntryStrategy : ConfigEntryStrategy<string>
	{
		internal StringConfigEntryStrategy(ConfigEntryStore configEntryStore)
			: base(configEntryStore)
		{
		}

		protected override RectTransform Execute(Transform scrollView, string modName, ConfigEntry<string> entry)
		{
			if (!(((ConfigEntryBase)entry).Description.AcceptableValues is AcceptableValueList<string> acceptableValueList))
			{
				return HandleStringEntry(scrollView, modName, entry);
			}
			return HandleListEntry(scrollView, modName, entry, acceptableValueList);
		}

		private RectTransform HandleStringEntry(Transform scrollView, string modName, ConfigEntry<string> entry)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			string text = (string)((ConfigEntryBase)entry).DefaultValue;
			REPOInputField val = MenuAPI.CreateREPOInputField(modName, (Action<string>)delegate(string s)
			{
				if (base.ConfigEntryStore.OriginalEntryValues.TryGetValue((ConfigEntryBase)(object)entry, out var value) && s == (string)value)
				{
					base.ConfigEntryStore.ChangedEntryValues.Remove((ConfigEntryBase)(object)entry);
				}
				else
				{
					base.ConfigEntryStore.ChangedEntryValues[(ConfigEntryBase)(object)entry] = s;
				}
			}, scrollView, Vector2.zero, false, (!string.IsNullOrEmpty(text)) ? text : "<NONE>", entry.Value);
			TextMeshProUGUI labelTMP = val.labelTMP;
			TMP_Text inputTMP = val.inputStringSystem.inputTMP;
			FontStyles fontStyle = (FontStyles)0;
			inputTMP.fontStyle = (FontStyles)0;
			((TMP_Text)labelTMP).fontStyle = fontStyle;
			return ((REPOElement)val).rectTransform;
		}

		private RectTransform HandleListEntry(Transform scrollView, string modName, ConfigEntry<string> entry, AcceptableValueList<string> acceptableValueList)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			REPOSlider val = MenuAPI.CreateREPOSlider(modName, string.Empty, (Action<string>)delegate(string s)
			{
				if (base.ConfigEntryStore.OriginalEntryValues.TryGetValue((ConfigEntryBase)(object)entry, out var value) && s == (string)value)
				{
					base.ConfigEntryStore.ChangedEntryValues.Remove((ConfigEntryBase)(object)entry);
				}
				else
				{
					base.ConfigEntryStore.ChangedEntryValues[(ConfigEntryBase)(object)entry] = s;
				}
			}, scrollView, acceptableValueList.AcceptableValues, entry.Value, default(Vector2), "", "", (BarBehavior)0);
			TextMeshProUGUI descriptionTMP = val.descriptionTMP;
			TextMeshProUGUI labelTMP = val.labelTMP;
			FontStyles fontStyle = (FontStyles)0;
			((TMP_Text)labelTMP).fontStyle = (FontStyles)0;
			((TMP_Text)descriptionTMP).fontStyle = fontStyle;
			return ((REPOElement)val).rectTransform;
		}
	}
}
namespace REPOConfig.Extensions
{
	internal static class ConfigEntryBaseExtensions
	{
		internal const string HIDE_TAG = "HideFromREPOConfig";

		internal const string LEGACY_HIDE_TAG = "HideREPOConfig";

		internal const string STEP_TAG = "REPOConfigStep";

		internal static bool HasTag(this ConfigEntryBase entry, string tag)
		{
			ConfigDescription description = entry.Description;
			if (description == null)
			{
				return false;
			}
			return description.Tags?.Contains(tag) == true;
		}

		internal static bool TryGetTagValue(this ConfigEntryBase entry, string tag, out string value)
		{
			string prefix = tag + "=";
			ConfigDescription description = entry.Description;
			object obj;
			if (description == null)
			{
				obj = null;
			}
			else
			{
				object[] tags = description.Tags;
				if (tags == null)
				{
					obj = null;
				}
				else
				{
					string? text = tags.OfType<string>().FirstOrDefault((string t) => t.StartsWith(prefix));
					if (text == null)
					{
						obj = null;
					}
					else
					{
						string text2 = text;
						int length = prefix.Length;
						obj = text2.Substring(length, text2.Length - length).Trim();
					}
				}
			}
			value = (string)obj;
			return !string.IsNullOrEmpty(value);
		}
	}
	internal static class FloatExtensions
	{
		internal static int GetDecimalPlaces(this float value)
		{
			string text = value.ToString(CultureInfo.InvariantCulture);
			int num = text.IndexOf('.');
			if (num != -1)
			{
				string text2 = text;
				int num2 = num + 1;
				return text2.Substring(num2, text2.Length - num2).Length;
			}
			return 0;
		}
	}
}

modules/RepoHUDTweaks.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
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.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GoopUpgrades;
using HarmonyLib;
using Omni.WalkieTalkie;
using Photon.Pun;
using RepoHUDTweaks.compatibilityPatches;
using RepoHUDTweaks.patches;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("RepoHUDTweaks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RepoHUDTweaks")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("537e4ad8-2470-446c-9fa9-0ebfd7b9dd00")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace RepoHUDTweaks
{
	public class Helpers
	{
		public static string ToHex(Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ColorUtility.ToHtmlStringRGB(color);
		}

		public static string ToHexAlpha(Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ColorUtility.ToHtmlStringRGBA(color);
		}

		public static Color ToColor(string hex, Color fallback)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Color result = default(Color);
			if (ColorUtility.TryParseHtmlString(hex, ref result))
			{
				return result;
			}
			return fallback;
		}

		public static Color ToColor(string hex, string fallback)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Color result = default(Color);
			if (ColorUtility.TryParseHtmlString(hex, ref result))
			{
				return result;
			}
			return ToColor(fallback, Color.white);
		}
	}
	[BepInPlugin("Swaggies.PlayerTweaks", "PlayerTweaks", "0.5.1")]
	public class Plugin : BaseUnityPlugin
	{
		private const string _guid = "Swaggies.PlayerTweaks";

		private const string _name = "PlayerTweaks";

		public const string _ver = "0.5.1";

		private readonly Harmony harmony = new Harmony("Swaggies.PlayerTweaks");

		public static ManualLogSource loggy;

		public static ConfigFile globalConfig;

		public static ConfigFile configToUse;

		public static ConfigEntry<bool> UseGlobalConfig;

		public static ConfigEntry<bool> SaveToGlobalConfig;

		public static ConfigEntry<string> HealthPlusSignColor;

		public static ConfigEntry<string> HealthColor;

		public static ConfigEntry<string> HealthMaxColor;

		public static ConfigEntry<bool> HealthMaxMatchSlash;

		public static ConfigEntry<bool> HealthPlusSignAsHealthBar;

		public static ConfigEntry<string> HealthLabel;

		public static ConfigEntry<string> StaminaZapSignColor;

		public static ConfigEntry<string> StaminaColor;

		public static ConfigEntry<string> StaminaMaxColor;

		public static ConfigEntry<bool> StaminaMaxMatchSlash;

		public static ConfigEntry<bool> StaminaZapSignAsStaminaBar;

		public static ConfigEntry<bool> ScaleUpStamina;

		public static ConfigEntry<string> StaminaLabel;

		public static ConfigEntry<int> TumbleUIFrameRate;

		public static ConfigEntry<int> TumbleUIInSpeed;

		public static ConfigEntry<int> TumbleUIOutSpeed;

		public static ConfigEntry<string> TumbleUIColorExitLight;

		public static ConfigEntry<string> TumbleUIColorExitDark;

		public static ConfigEntry<string> TumbleUIColorStunnedLight;

		public static ConfigEntry<string> TumbleUIColorStunnedDark;

		public static ConfigEntry<string> TumbleWingUIWingColor;

		public static ConfigEntry<string> TumbleWingUIHolderColor;

		public static ConfigEntry<string> TumbleWingUIBarColorStart;

		public static ConfigEntry<string> TumbleWingUIBarColorEnd;

		public static ConfigEntry<string> HaulUIColor;

		public static ConfigEntry<string> HaulUIDollarSignColor;

		public static ConfigEntry<string> HaulUISlashColor;

		public static ConfigEntry<string> GoalUIColor;

		public static ConfigEntry<string> GoalUISlashColor;

		public static ConfigEntry<bool> WASDCancelsTumbleImmediately;

		public static ConfigEntry<bool> SpaceToExitCrouch;

		public static ConfigEntry<bool> SprintToExitCrouch;

		public static ConfigEntry<string> AimColorDefault;

		public static ConfigEntry<string> AimColorGrabbable;

		public static ConfigEntry<string> AimColorGrab;

		public static ConfigEntry<string> AimColorRotate;

		public static ConfigEntry<string> AimColorClimbable;

		public static ConfigEntry<string> AimColorClimb;

		public static ConfigEntry<string> AimColorDisabled;

		public static ConfigEntry<string> HurtVignetteColor;

		public static ConfigEntry<bool> HurtVignetteHealthBased;

		public static ConfigEntry<float> HurtVignetteHealthBasedScaleMax;

		public static ConfigEntry<float> HurtVignetteHealthBasedScaleMin;

		public static ConfigEntry<bool> HurtVignetteWhileDead;

		public static ConfigEntry<bool> HurtVignetteAtMaxHealth;

		public static ConfigEntry<bool> WorldSpaceValueUIEnablePatch;

		public static ConfigEntry<string> WorldSpaceValueUIColorMax;

		public static ConfigEntry<string> WorldSpaceValueUIColorMed;

		public static ConfigEntry<string> WorldSpaceValueUIColorMin;

		public static ConfigEntry<string> WorldSpaceValueUIColorCost;

		public static ConfigEntry<float> WorldSpaceValueUICountUpTime;

		public static ConfigEntry<float> WorldSpaceValueUICountDownTime;

		public static ConfigEntry<bool> WSUIVL_EnablePatch;

		public static ConfigEntry<bool> WSUIVL_AlwaysDisplayWhenPossible;

		public static ConfigEntry<float> WSUIVL_Scale0;

		public static ConfigEntry<float> WSUIVL_Scale1000;

		public static ConfigEntry<float> WSUIVL_Scale5000;

		public static ConfigEntry<float> WSUIVL_Scale10000;

		public static ConfigEntry<float> WSUIVL_Scale50000;

		public static ConfigEntry<float> WSUIVL_Timer0;

		public static ConfigEntry<float> WSUIVL_Timer1000;

		public static ConfigEntry<float> WSUIVL_Timer5000;

		public static ConfigEntry<float> WSUIVL_Timer10000;

		public static ConfigEntry<float> WSUIVL_Timer50000;

		public static ConfigEntry<string> WSUIVL_Color0;

		public static ConfigEntry<string> WSUIVL_Color1000;

		public static ConfigEntry<string> WSUIVL_Color5000;

		public static ConfigEntry<string> WSUIVL_Color10000;

		public static ConfigEntry<string> WSUIVL_Color50000;

		public static ConfigEntry<bool> WSUIVL_InterpolateScale;

		public static ConfigEntry<bool> WSUIVL_InterpolateTimer;

		public static ConfigEntry<bool> WSUIVL_InterpolateColor;

		public static ConfigEntry<bool> ItemInfoUIShowValuableNames;

		public static ConfigEntry<bool> ItemInfoUIShowValuableValues;

		public static ConfigEntry<bool> ItemInfoUIShowItemBattery;

		public static ConfigEntry<string> ItemInfoUIGradStart;

		public static ConfigEntry<string> ItemInfoUIGradEnd;

		public static ConfigEntry<string> ItemInfoUIGradEnemyStart;

		public static ConfigEntry<string> ItemInfoUIGradEnemyEnd;

		public static ConfigEntry<bool> OverchargeUIShowLegacy;

		public static ConfigEntry<string> OverchargeUILegacySignColor;

		public static ConfigEntry<string> OverchargeUILegacyColor;

		public static ConfigEntry<string> OverchargeUILegacyMaxColor;

		public static ConfigEntry<bool> OverchargeUILegacyMatchSlash;

		public static ConfigEntry<bool> OverchargeUILegacySignAsBar;

		public static ConfigEntry<string> OverchargeUIRoundBarColor;

		public static ConfigEntry<string> OverchargeUILegacyLabel;

		public static ConfigEntry<string> MapObjectValuableColor;

		public static ConfigEntry<string> MapObjectItemColor;

		public static ConfigEntry<string> MapObjectDeathHeadColor;

		public static ConfigEntry<string> MapObjectDoorColor;

		public static ConfigEntry<string> MapObjectPlayerColor;

		public static ConfigEntry<string> MapObjectBacktrackColorStart;

		public static ConfigEntry<string> MapObjectBacktrackColorEnd;

		public static ConfigEntry<string> MapWallColor;

		public static ConfigEntry<string> MapFloorColor;

		public static ConfigEntry<string> MapStairsColor;

		public static ConfigEntry<string> MapInactiveWallColor;

		public static ConfigEntry<string> MapInactiveFloorColor;

		public static ConfigEntry<string> MapTruckWallColor;

		public static ConfigEntry<string> MapTruckFloorColor;

		public static ConfigEntry<string> MapUsedWallColor;

		public static ConfigEntry<string> MapUsedFloorColor;

		public static ConfigEntry<string> MapUnexploredOutlineColor;

		public static ConfigEntry<string> MapUnexploredColor;

		public static ConfigEntry<string> MapUnexploredGraphicColor;

		public static ConfigEntry<string> MapBackgroundColor;

		public static ConfigEntry<string> MapAmbientColor;

		public static ConfigEntry<string> VehicleSpeedColor;

		public static ConfigEntry<string> VehicleSpeedLeadingZeroColor;

		public static ConfigEntry<string> VehicleSpeedLabelColor;

		public static ConfigEntry<string> VehicleDollarSignColor;

		public static ConfigEntry<string> VehicleDollarValueColor;

		public static ConfigEntry<string> VehicleDollarValueLeadingZeroColor;

		public static ConfigEntry<string> InventorySlotBgColor;

		public static ConfigEntry<string> InventorySlotNumColor;

		public static ConfigEntry<string> InventorySlotNumOccupiedColor;

		public static ConfigEntry<string> CurrencyUIColor;

		public static ConfigEntry<string> MissionUIColor;

		public static ConfigEntry<string> ToggleMuteUIColor;

		public static ConfigEntry<string> BigMessageUIColor;

		public static ConfigEntry<string> UpgradeNameColor;

		public static ConfigEntry<string> UpgradeValueColor;

		public static ConfigEntry<string> GoopUpgrades_ShieldSignColor;

		public static ConfigEntry<string> GoopUpgrades_ShieldColor;

		public static ConfigEntry<string> GoopUpgrades_ShieldMaxColor;

		public static ConfigEntry<bool> GoopUpgrades_ShieldMaxMatchSlash;

		public static ConfigEntry<bool> GoopUpgrades_ShieldPlusSignAsShieldBar;

		public static ConfigEntry<string> GoopUpgrades_ShieldLabel;

		private string GlobalConfigFile => Paths.ConfigPath + "/Swaggies.PlayerTweaks.Global.cfg";

		private string GlobalLocalConfigFile => Application.persistentDataPath + "/Swaggies.PlayerTweaks.GlobalFile.cfg";

		private void Awake()
		{
			loggy = Logger.CreateLogSource("Swaggies.PlayerTweaks");
			loggy.LogMessage((object)"PlayerTweaks's up and runnin' (0.5.1)");
			harmony.PatchAll(typeof(AimPatch));
			harmony.PatchAll(typeof(EnergyUIPatch));
			harmony.PatchAll(typeof(GoalUIPatch));
			harmony.PatchAll(typeof(HaulUIPatch));
			harmony.PatchAll(typeof(HealthUIPatch));
			harmony.PatchAll(typeof(HurtVignettePatch));
			harmony.PatchAll(typeof(PlayerControllerPatch));
			harmony.PatchAll(typeof(TumbleUIPatch));
			harmony.PatchAll(typeof(WorldSpaceUIValuePatch));
			harmony.PatchAll(typeof(WorldSpaceUIValueLostPatch));
			harmony.PatchAll(typeof(PhysGrabObjectImpactDetectorPatch));
			harmony.PatchAll(typeof(TumbleWingsUIPatch));
			harmony.PatchAll(typeof(PhysGrabberPatch));
			harmony.PatchAll(typeof(OverchargeRoundBarUIPatch));
			harmony.PatchAll(typeof(OverchargeUIPatch));
			harmony.PatchAll(typeof(ItemInfoUIPatch));
			harmony.PatchAll(typeof(MapPatch));
			harmony.PatchAll(typeof(DirtFinderPatches));
			harmony.PatchAll(typeof(VehicleUIPatch));
			harmony.PatchAll(typeof(CurrencyUIPatch));
			harmony.PatchAll(typeof(InventorySpotPatch));
			harmony.PatchAll(typeof(DirtFinderCounterPatch));
			harmony.PatchAll(typeof(MissionUIPatch));
			harmony.PatchAll(typeof(ToggleMuteUIPatch));
			harmony.PatchAll(typeof(BigMessageUIPatch));
			harmony.PatchAll(typeof(StatsUIPatch));
			if (Enumerable.Contains(Chainloader.PluginInfos.Keys, "omni.repo.walkietalkie"))
			{
				harmony.PatchAll(typeof(WalkieTalkieCompatibilityPatch));
			}
			SetupConfig();
			ConfigHealth();
			ConfigStamina();
			ConfigTumble();
			ConfigTumbleWings();
			ConfigHaul();
			ConfigGoal();
			ConfigControls();
			ConfigAim();
			ConfigHurtVignette();
			ConfigWorldSpaceUIValue();
			ConfigWorldSpaceUIValueLost();
			ConfigItemInfoUI();
			ConfigOverchargeUI();
			ConfigMap();
			ConfigVehicleUI();
			ConfigInventoryUI();
			ConfigMiscUI();
			if (Enumerable.Contains(Chainloader.PluginInfos.Keys, "GoopSwagger.GoopUpgrades"))
			{
				harmony.PatchAll(typeof(GoopUpgradesCompatibilityPatch));
				ConfigGoopUpgrades();
			}
		}

		private void SetupConfig()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_001e: Expected O, but got Unknown
			ConfigFile val = new ConfigFile(GlobalConfigFile, true);
			ConfigFile val2 = new ConfigFile(GlobalLocalConfigFile, true);
			globalConfig = val;
			UseGlobalConfig = globalConfig.Bind<bool>("Global Config", "Use Global Config", false, "Whether to use your global configuration file (if it exists). When checked, will ignore the config file in this specific modpack, and instead uses your own.");
			SaveToGlobalConfig = globalConfig.Bind<bool>("Global Config", "Save This Config to Global Config", false, "Whether to copy this config to your global config. This will overwrite it, be careful! Will automatically uncheck after saving.");
			if (SaveToGlobalConfig.Value)
			{
				((ConfigEntryBase)SaveToGlobalConfig).BoxedValue = false;
				globalConfig.Save();
				OverwriteGlobalSave();
			}
			configToUse = (UseGlobalConfig.Value ? val2 : ((BaseUnityPlugin)this).Config);
		}

		private void OverwriteGlobalSave()
		{
			if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
			{
				loggy.LogWarning((object)"Could not overwrite global config as main config doesn't exist.");
				return;
			}
			if (!File.Exists(GlobalLocalConfigFile))
			{
				loggy.LogMessage((object)("Creating global config file at " + GlobalLocalConfigFile + "."));
				File.Create(GlobalLocalConfigFile);
			}
			loggy.LogMessage((object)"Copying config to global config.");
			File.Copy(((BaseUnityPlugin)this).Config.ConfigFilePath, GlobalLocalConfigFile, overwrite: true);
		}

		private void ConfigHealth()
		{
			HealthPlusSignColor = configToUse.Bind<string>("Health UI", "Plus Sign Color", "#56ff6d", "The color of the plus sign");
			HealthColor = configToUse.Bind<string>("Health UI", "Health Color", "#56ff6d", "The color of the current health number");
			HealthMaxColor = configToUse.Bind<string>("Health UI", "Max Health Color", "#008b20", "The color of the max health number");
			HealthMaxMatchSlash = configToUse.Bind<bool>("Health UI", "Use Same Color for Max and Current HP", false, "If the max health number and current health number use the same color (true in vanilla)");
			HealthPlusSignAsHealthBar = configToUse.Bind<bool>("Health UI", "Use Plus Sign as Health Bar", true, "If the plus sign should be used as a health bar");
			HealthLabel = configToUse.Bind<string>("Health UI", "Health Label", "", "A text label appended to the max health number. For example, using \"HP\" would make health show up as \"100 /100HP\" in-game.");
		}

		private void ConfigStamina()
		{
			StaminaZapSignColor = configToUse.Bind<string>("Stamina UI", "Zap Sign Color", "#fcff00", "The color of the energy sign");
			StaminaColor = configToUse.Bind<string>("Stamina UI", "Stamina Color", "#fcff00", "The color of the current stamina number");
			StaminaMaxColor = configToUse.Bind<string>("Stamina UI", "Max Stamina Color", "#ffa500", "The color of the max stamina number");
			StaminaMaxMatchSlash = configToUse.Bind<bool>("Stamina UI", "Use Same Color for Max and Current Stam", false, "If the max stamina number and current stamina number use the same color (true in vanilla)");
			StaminaZapSignAsStaminaBar = configToUse.Bind<bool>("Stamina UI", "Use Zap Sign as Stamina Bar", true, "If the zap sign should be used as a stamina bar");
			ScaleUpStamina = configToUse.Bind<bool>("Stamina UI", "Upscale Stamina", false, "Multiplies the stamina number by 2.5, making it start at 100 with each upgrade adding 25. Does NOT affect how much stamina you ACTUALLY have, this is only a visual change.");
			StaminaLabel = configToUse.Bind<string>("Stamina UI", "Stamina Label", "", "A text label appended to the max stamina number. For example, using \"ST\" would make stamina show up as \"40 /40ST\" in-game.");
		}

		private void ConfigTumble()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			TumbleUIFrameRate = configToUse.Bind<int>("Tumble UI", "Border Animation Frame Rate", 60, new ConfigDescription("The frame rate of the Tumble UI appearing and disappearing (vanilla default is 12.5)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 120), Array.Empty<object>()));
			TumbleUIInSpeed = configToUse.Bind<int>("Tumble UI", "Border Fade-In Speed", 8, new ConfigDescription("How quickly the Tumble UI appears when beginning a tumble (affected by frame rate, vanilla default is 30)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 100), Array.Empty<object>()));
			TumbleUIOutSpeed = configToUse.Bind<int>("Tumble UI", "Border Fade-Out Speed", 10, new ConfigDescription("How quickly the Tumble UI disappears when getting up from a tumble (affected by frame rate, vanilla default is 80)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 100), Array.Empty<object>()));
			TumbleUIColorExitLight = configToUse.Bind<string>("Tumble UI", "Border Color Light", "#ffb20050", "The lighter color of the border when you're able to exit a tumble.");
			TumbleUIColorExitDark = configToUse.Bind<string>("Tumble UI", "Border Color Dark", "#ffb20032", "The darker color of the border when you're able to exit a tumble.");
			TumbleUIColorStunnedLight = configToUse.Bind<string>("Tumble UI", "Border Color Light (Stunned)", "#ff000050", "The lighter color of the border when you're stunned.");
			TumbleUIColorStunnedDark = configToUse.Bind<string>("Tumble UI", "Border Color Dark (Stunned)", "#ff000032", "The darker color of the border when you're stunned.");
		}

		private void ConfigTumbleWings()
		{
			TumbleWingUIWingColor = configToUse.Bind<string>("Tumble Wings UI", "Wing Color", "#0065ff", "Color of the wings in the UI (does not affect in-world wings)");
			TumbleWingUIHolderColor = configToUse.Bind<string>("Tumble Wings UI", "Bar Holder Color", "#00beff", "Color of the bar holder (edges)");
			TumbleWingUIBarColorStart = configToUse.Bind<string>("Tumble Wings UI", "Bar Color (full)", "#00bbff", "Color of the bar when full");
			TumbleWingUIBarColorEnd = configToUse.Bind<string>("Tumble Wings UI", "Bar Color (empty)", "#00bbff", "Color of the bar when empty");
		}

		private void ConfigHaul()
		{
			HaulUIColor = configToUse.Bind<string>("Haul UI", "Color", "#c9e9e6", "Color for haul UI");
			HaulUIDollarSignColor = configToUse.Bind<string>("Haul UI", "Dollar Sign Color", "#558b2f", "Color of the dollar sign in the haul UI");
			HaulUISlashColor = configToUse.Bind<string>("Haul UI", "Slash Color", "#616161", "Color for the slash in the haul UI");
		}

		private void ConfigGoal()
		{
			GoalUIColor = configToUse.Bind<string>("Goal UI", "Color", "#ff5f00", "Color for goal UI");
			GoalUISlashColor = configToUse.Bind<string>("Goal UI", "Slash Color", "#7d250b", "Color for the slash in the goal UI");
		}

		private void ConfigControls()
		{
			WASDCancelsTumbleImmediately = configToUse.Bind<bool>("Controls", "WASD Cancels Tumble Immediately", false, "If using WASD does NOT wait for you to stop moving before making you get up from a tumble");
			SpaceToExitCrouch = configToUse.Bind<bool>("Controls", "Jumping Exits Crouch", false, "If jumping automatically uncrouches you");
			SprintToExitCrouch = configToUse.Bind<bool>("Controls", "Sprinting Exits Crouch", false, "If trying to sprint while crouched will automatically uncrouch you");
		}

		private void ConfigAim()
		{
			AimColorDefault = configToUse.Bind<string>("Crosshair", "Default Color", "#ffffff32", "Color for default crosshair");
			AimColorGrabbable = configToUse.Bind<string>("Crosshair", "Object Hover Color", "#fff700ff", "Color for hovering over a grabbable object");
			AimColorGrab = configToUse.Bind<string>("Crosshair", "Object Grab Color", "#ffffff1e", "Color for holding an object");
			AimColorRotate = configToUse.Bind<string>("Crosshair", "Object Rotate Color", "#ffffff1e", "Color for rotating an object");
			AimColorClimbable = configToUse.Bind<string>("Crosshair", "Climb Hover Color", "#005fffff", "Color for hovering over a climbable surface");
			AimColorClimb = configToUse.Bind<string>("Crosshair", "Climb Grab Color", "#005fff49", "Color for climbing");
			AimColorDisabled = configToUse.Bind<string>("Crosshair", "Climb Disabled Color", "#ff000057", "Color for the X when you are unable to climb");
			AimColorDefault.SettingChanged += delegate
			{
				AimPatch.Update();
			};
			AimColorGrabbable.SettingChanged += delegate
			{
				AimPatch.Update();
			};
			AimColorGrab.SettingChanged += delegate
			{
				AimPatch.Update();
			};
			AimColorRotate.SettingChanged += delegate
			{
				AimPatch.Update();
			};
			AimColorClimbable.SettingChanged += delegate
			{
				AimPatch.Update();
			};
			AimColorClimb.SettingChanged += delegate
			{
				AimPatch.Update();
			};
			AimColorDisabled.SettingChanged += delegate
			{
				AimPatch.Update();
			};
		}

		private void ConfigHurtVignette()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			HurtVignetteColor = configToUse.Bind<string>("Hurt Vignette", "Color", "#b20000af", "Color of vignette");
			HurtVignetteHealthBased = configToUse.Bind<bool>("Hurt Vignette", "Health Based", false, "If the vignette should fade in the more your health goes down");
			HurtVignetteHealthBasedScaleMax = configToUse.Bind<float>("Hurt Vignette", "Max Scale", 2f, new ConfigDescription("(IF Health Based IS ENABLED ONLY) The scale of the vignette image when at max health.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 2.5f), Array.Empty<object>()));
			HurtVignetteHealthBasedScaleMin = configToUse.Bind<float>("Hurt Vignette", "Min Scale", 1f, new ConfigDescription("(IF Health Based IS ENABLED ONLY) The scale of the vignette image when at 0 health. Lowering this too far might make the vignette cover the screen a lot!", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			HurtVignetteWhileDead = configToUse.Bind<bool>("Hurt Vignette", "Display While Dead", false, "(IF Health Based IS ENABLED ONLY) If the vignette should remain on screen while you're dead");
			HurtVignetteAtMaxHealth = configToUse.Bind<bool>("Hurt Vignette", "Display at Max Health", false, "(IF Health Based IS ENABLED ONLY) If the vignette should remain on screen even if you're at max health");
			HurtVignetteColor.SettingChanged += delegate
			{
				HurtVignettePatch.SpoofLerp();
			};
		}

		private void ConfigWorldSpaceUIValue()
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			WorldSpaceValueUIEnablePatch = configToUse.Bind<bool>("Value UI", "Enable Patch", true, "Enables the patches for value UI. Disable for any compatibility purposes, disabling this will also disable all options below.");
			WorldSpaceValueUIColorMax = configToUse.Bind<string>("Value UI", "Color (Max Value)", "#00a825", "Color of the value UI when holding a valuable at max value");
			WorldSpaceValueUIColorMed = configToUse.Bind<string>("Value UI", "Color (Med Value)", "#00a825", "Color of the value UI when holding a valuable at about half its original value");
			WorldSpaceValueUIColorMin = configToUse.Bind<string>("Value UI", "Color (Min Value)", "#00a825", "Color of the value UI when holding a valuable at min value (color will interpolate with max value as valuable's value goes down)");
			WorldSpaceValueUIColorCost = configToUse.Bind<string>("Value UI", "Color (Shop Cost)", "#f13337", "Color of the value UI when hovering over/holding a shop item");
			WorldSpaceValueUICountUpTime = configToUse.Bind<float>("Value UI", "Count-Up Speed", 15f, new ConfigDescription("How quickly to interpolate the value counting up. (Set to 0 to instantly change instead of animating.)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
			WorldSpaceValueUICountDownTime = configToUse.Bind<float>("Value UI", "Count-Down Speed", 6f, new ConfigDescription("How quickly to interpolate the value counting down. (Set to 0 to instantly change instead of animating.)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
		}

		private void ConfigWorldSpaceUIValueLost()
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Expected O, but got Unknown
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Expected O, but got Unknown
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Expected O, but got Unknown
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Expected O, but got Unknown
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Expected O, but got Unknown
			WSUIVL_EnablePatch = configToUse.Bind<bool>("Value Lost UI", "Enable Patch", true, "Enables the patches for value lost UI. Disable for any compatibility purposes, disabling this will also disable all options below.");
			WSUIVL_AlwaysDisplayWhenPossible = configToUse.Bind<bool>("Value Lost UI", "Always Display When Possible", false, "Attempts to always show the value lost UI at times when it wouldn't normally show (such as if an item falls into a pit, or is crushed by an extraction point)");
			WSUIVL_Color0 = configToUse.Bind<string>("Value Lost UI", "Color at $0", "#f13337", "Color of the value lost UI at this dollar amount");
			WSUIVL_Scale0 = configToUse.Bind<float>("Value Lost UI", "Text scale at $0", 0.54f, new ConfigDescription("Size multiplier of the value lost UI at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			WSUIVL_Timer0 = configToUse.Bind<float>("Value Lost UI", "Display time at $0", 3f, new ConfigDescription("Time in seconds to display the value lost UI on-screen at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			WSUIVL_Color1000 = configToUse.Bind<string>("Value Lost UI", "Color at $1.000", "#f13337", "Color of the value lost UI at this dollar amount");
			WSUIVL_Scale1000 = configToUse.Bind<float>("Value Lost UI", "Text scale at $1.000", 0.72f, new ConfigDescription("Size multiplier of the value lost UI at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			WSUIVL_Timer1000 = configToUse.Bind<float>("Value Lost UI", "Display time at $1.000", 3f, new ConfigDescription("Time in seconds to display the value lost UI on-screen at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			WSUIVL_Color5000 = configToUse.Bind<string>("Value Lost UI", "Color at $5.000", "#f13337", "Color of the value lost UI at this dollar amount");
			WSUIVL_Scale5000 = configToUse.Bind<float>("Value Lost UI", "Text scale at $5.000", 0.72f, new ConfigDescription("Size multiplier of the value lost UI at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			WSUIVL_Timer5000 = configToUse.Bind<float>("Value Lost UI", "Display time at $5.000", 3f, new ConfigDescription("Time in seconds to display the value lost UI on-screen at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			WSUIVL_Color10000 = configToUse.Bind<string>("Value Lost UI", "Color at $10.000", "#f13337", "Color of the value lost UI at this dollar amount");
			WSUIVL_Scale10000 = configToUse.Bind<float>("Value Lost UI", "Text scale at $10.000", 0.72f, new ConfigDescription("Size multiplier of the value lost UI at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			WSUIVL_Timer10000 = configToUse.Bind<float>("Value Lost UI", "Display time at $10.000", 3f, new ConfigDescription("Time in seconds to display the value lost UI on-screen at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			WSUIVL_Color50000 = configToUse.Bind<string>("Value Lost UI", "Color at $50.000", "#f13337", "Color of the value lost UI at this dollar amount");
			WSUIVL_Scale50000 = configToUse.Bind<float>("Value Lost UI", "Text scale at $50.000", 0.72f, new ConfigDescription("Size multiplier of the value lost UI at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			WSUIVL_Timer50000 = configToUse.Bind<float>("Value Lost UI", "Display time at $50.000", 3f, new ConfigDescription("Time in seconds to display the value lost UI on-screen at this dollar amount", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			WSUIVL_InterpolateColor = configToUse.Bind<bool>("Value Lost UI", "Interpolate Color", false, "Whether to interpolate text color between value breakpoints");
			WSUIVL_InterpolateScale = configToUse.Bind<bool>("Value Lost UI", "Interpolate Scale", false, "Whether to interpolate text size multiplier between value breakpoints");
			WSUIVL_InterpolateTimer = configToUse.Bind<bool>("Value Lost UI", "Interpolate Timer", false, "Whether to interpolate display time between value breakpoints");
		}

		private void ConfigItemInfoUI()
		{
			ItemInfoUIShowValuableNames = configToUse.Bind<bool>("Item Info UI", "Show Names of Valuables", false, "Shows the names of valuables you grab at the bottom of your screen, similar to shop items");
			ItemInfoUIShowValuableValues = configToUse.Bind<bool>("Item Info UI", "Show Value of Valuables", false, "Shows the value of valuables alongside the name if Show Names of Valuables is enabled");
			ItemInfoUIShowItemBattery = configToUse.Bind<bool>("Item Info UI", "Show Battery of Items", false, "Shows the remaining charge of shop items alongside their name");
			ItemInfoUIGradStart = configToUse.Bind<string>("Item Info UI", "Color Gradient (Top)", "#ffff00", "Color 1 for the Item Info UI gradient (applies to the top part of the vertical gradient");
			ItemInfoUIGradEnd = configToUse.Bind<string>("Item Info UI", "Color Gradient (Bottom)", "#ff6300", "Color 2 for the Item Info UI gradient (applies to the bottom part of the vertical gradient");
			ItemInfoUIGradEnemyStart = configToUse.Bind<string>("Item Info UI", "Enemy Color Gradient (Top)", "#ff0000", "Color 1 for the Item Info UI gradient when grabbing an enemy (applies to the top part of the vertical gradient");
			ItemInfoUIGradEnemyEnd = configToUse.Bind<string>("Item Info UI", "Enemy Color Gradient (Bottom)", "#ff1a00", "Color 2 for the Item Info UI gradient when grabbing an enemy (applies to the bottom part of the vertical gradient");
		}

		private void ConfigOverchargeUI()
		{
			OverchargeUIShowLegacy = configToUse.Bind<bool>("Overcharge UI", "Show Legacy Number", false, "Whether to show the old overcharge UI, represented as a number at the top left of your screen");
			OverchargeUILegacySignColor = configToUse.Bind<string>("Overcharge UI", "Legacy Sign Color", "#ff0000", "Color of the overcharge symbol for the legacy UI");
			OverchargeUILegacyColor = configToUse.Bind<string>("Overcharge UI", "Legacy Color", "#ff0700", "Color of the overcharge number for the legacy UI");
			OverchargeUILegacyMaxColor = configToUse.Bind<string>("Overcharge UI", "Legacy Max Color", "#fc0000", "Color of the overcharge max number for the legacy UI");
			OverchargeUILegacyMatchSlash = configToUse.Bind<bool>("Overcharge UI", "Legacy Use Same Color for Current and Max", true, "If the max number and current number use the same color (true in vanilla)");
			OverchargeUILegacySignAsBar = configToUse.Bind<bool>("Overcharge UI", "Use Legacy Sign as Overcharge Meter", true, "If the overcharge symbol should be used as a meter");
			OverchargeUIRoundBarColor = configToUse.Bind<string>("Overcharge UI", "Round Bar Color", "#ff00004b", "Color of the standard ring UI");
			OverchargeUILegacyLabel = configToUse.Bind<string>("Overcharge UI", "Legacy Label", "", "A text label appended to the max overcharge number. For example, using \"OC\" would make overcharge show up as \"50 /100OC\" in-game.");
		}

		private void ConfigMap()
		{
			MapObjectValuableColor = configToUse.Bind<string>("Map Objects", "Valuable Object Color", "#ffd300", "Color of the valuable dots on the map.");
			MapObjectItemColor = configToUse.Bind<string>("Map Objects", "Item Object Color", "#00ffeb", "Color of the shop item dots on the map.");
			MapObjectDeathHeadColor = configToUse.Bind<string>("Map Objects", "Death Head Color", "#ff000e", "Color of the death head dots on the map.");
			MapObjectPlayerColor = configToUse.Bind<string>("Map Objects", "Player Color", "#72ff79", "Color of the main player arrow on the map.");
			MapObjectDoorColor = configToUse.Bind<string>("Map Objects", "Door Color", "#45ff50", "Color of the doors on the map.");
			MapObjectBacktrackColorStart = configToUse.Bind<string>("Map Objects", "Backtrack Color", "#ffffff", "Color of the dots on the map that make a path to the current objective.");
			MapObjectBacktrackColorEnd = configToUse.Bind<string>("Map Objects", "Backtrack Fade Color", "#ffffff", "If set to a different color than Backtrack Color, the path dots on the map will fade to THIS color as the dots get further away from the player.");
			MapWallColor = configToUse.Bind<string>("Map Geometry", "Wall Color", "#077600", "Color of walls on the map. (APPLIES ON LEVEL LOAD)");
			MapFloorColor = configToUse.Bind<string>("Map Geometry", "Floor Color", "#004803", "Color of floors on the map. (APPLIES ON LEVEL LOAD)");
			MapStairsColor = configToUse.Bind<string>("Map Geometry", "Stairs Color", "#2aff37", "Color of stairs on the map. (APPLIES ON LEVEL LOAD)");
			MapInactiveWallColor = configToUse.Bind<string>("Map Geometry", "Inactive Wall Color", "#8e4000", "Color of walls for inactive extraction points on the map. (APPLIES ON LEVEL LOAD)");
			MapInactiveFloorColor = configToUse.Bind<string>("Map Geometry", "Inactive Floor Color", "#542400", "Color of floors for inactive extraction points on the map. (APPLIES ON LEVEL LOAD)");
			MapTruckWallColor = configToUse.Bind<string>("Map Geometry", "Truck Wall Color", "#00797d", "Color of truck walls (ALSO USED FOR ACTIVE EXTRACTION POINTS) on the map. (APPLIES ON LEVEL LOAD)");
			MapTruckFloorColor = configToUse.Bind<string>("Map Geometry", "Truck Floor Color", "#005154", "Color of truck floors (ALSO USED FOR ACTIVE EXTRACTION POINTS) on the map. (APPLIES ON LEVEL LOAD)");
			MapUsedWallColor = configToUse.Bind<string>("Map Geometry", "Used Wall Color", "#950001", "Color of walls for completed extraction points on the map. (APPLIES ON LEVEL LOAD)");
			MapUsedFloorColor = configToUse.Bind<string>("Map Geometry", "Used Floor Color", "#4d0005", "Color of floors for completed extraction points on the map. (APPLIES ON LEVEL LOAD)");
			MapUnexploredOutlineColor = configToUse.Bind<string>("Map Geometry", "Unexplored Outline Color", "#008908", "Color of the outlines of unexplored rooms on the map. (APPLIES ON LEVEL LOAD)");
			MapUnexploredColor = configToUse.Bind<string>("Map Geometry", "Unexplored Color", "#000000", "Color of the shaded area for unexplored rooms on the map. (APPLIES ON LEVEL LOAD)");
			MapUnexploredGraphicColor = configToUse.Bind<string>("Map Geometry", "Unexplored Graphic Color", "#00bc09", "Color of the question mark symbol (?) for unexplored rooms on the map. (APPLIES ON LEVEL LOAD)");
			MapAmbientColor = ((BaseUnityPlugin)this).Config.Bind<string>("Map Screen", "Ambient Glow Color", "#00ff19", "The color of the glow that the map screen gives off");
			MapBackgroundColor = ((BaseUnityPlugin)this).Config.Bind<string>("Map Screen", "Screen Backdrop Color", "#004f02", "The color of the background plane behind all of the map objects on the screen");
			MapObjectValuableColor.SettingChanged += delegate
			{
				MapPatch.UpdateAllValuables();
			};
			MapObjectItemColor.SettingChanged += delegate
			{
				MapPatch.UpdateAllItems();
			};
			MapObjectDeathHeadColor.SettingChanged += delegate
			{
				MapPatch.UpdateAllItems();
			};
			MapObjectPlayerColor.SettingChanged += delegate
			{
				DirtFinderPatches.UpdatePlayer();
			};
			MapObjectDoorColor.SettingChanged += delegate
			{
				DirtFinderPatches.UpdateAllDoorTargets();
			};
			MapObjectBacktrackColorStart.SettingChanged += delegate
			{
				DirtFinderPatches.UpdateBacktrack(null);
			};
			MapObjectBacktrackColorEnd.SettingChanged += delegate
			{
				DirtFinderPatches.UpdateBacktrack(null);
			};
			MapBackgroundColor.SettingChanged += delegate
			{
				MapPatch.UpdateBG();
			};
		}

		private void ConfigVehicleUI()
		{
			VehicleSpeedColor = configToUse.Bind<string>("Vehicle UI", "Speed Color", "#ffeb04", "Color for the speedometer.");
			VehicleSpeedLeadingZeroColor = configToUse.Bind<string>("Vehicle UI", "Speed Color (Leading Zeros)", "#4a151080", "Color for the darker leading zeros in the speedometer.");
			VehicleSpeedLabelColor = configToUse.Bind<string>("Vehicle UI", "Speed Label Color", "#ffeb04", "Color for the speedometer label (eg. \"km/h\").");
			VehicleDollarSignColor = configToUse.Bind<string>("Vehicle UI", "Dollar Sign Color", "#558b2f80", "Color for the dollar sign.");
			VehicleDollarValueColor = configToUse.Bind<string>("Vehicle UI", "Dollar Value Color", "#ffff00a6", "Color for the dollar value.");
			VehicleDollarValueLeadingZeroColor = configToUse.Bind<string>("Vehicle UI", "Dollar Value Color (Leading Zeros)", "#4a151080", "Color for the darker leading zeros in the dollar value.");
		}

		private void ConfigInventoryUI()
		{
			InventorySlotBgColor = ((BaseUnityPlugin)this).Config.Bind<string>("Inventory UI", "Background Color", "#00000064", "The background color of inventory slots (recommended to have transparency)");
			InventorySlotNumColor = ((BaseUnityPlugin)this).Config.Bind<string>("Inventory UI", "Slot Number Color", "#5e5e5e", "The color of the slot number for an empty inventory slot");
			InventorySlotNumOccupiedColor = ((BaseUnityPlugin)this).Config.Bind<string>("Inventory UI", "Occupied Slot Number Color", "#ffffff", "The color of the smaller corner slot number for when an item is occupying the slot");
		}

		private void ConfigMiscUI()
		{
			CurrencyUIColor = configToUse.Bind<string>("Misc UI", "Currency UI Color", "#c9e9e6", "Color for your team's current money");
			MissionUIColor = configToUse.Bind<string>("Misc UI", "Mission UI Color", "#ffffff", "Color for the current mission text (the \"FOCUS\" text that displays your objective in the bottom left)");
			ToggleMuteUIColor = configToUse.Bind<string>("Misc UI", "Toggle Mute UI Color", "#ff9400", "Color for the muted mic icon that appears at the bottom right when toggling mute");
			BigMessageUIColor = configToUse.Bind<string>("Misc UI", "Big Message UI Color", "#ffffff", "Color for the big messages that appear at the bottom right (such as \"EXTRACTION POINT COMPLETED\"), this will only take effect if the big message doesn't specify a color on its own (none of the vanilla ones do, but some mods may)");
			UpgradeNameColor = configToUse.Bind<string>("Misc UI", "Upgrade Names Color", "#ff8d00", "Color for the names of upgrades in the upgrades list");
			UpgradeValueColor = configToUse.Bind<string>("Misc UI", "Upgrade Values Color", "#ffffff", "Color for the values (numbers) of upgrades in the upgrades list");
		}

		private void ConfigGoopUpgrades()
		{
			GoopUpgrades_ShieldSignColor = configToUse.Bind<string>("Compatibility - Goop Upgrades", "Shield Sign Color", "#366dff", "The color of the shield sign");
			GoopUpgrades_ShieldColor = configToUse.Bind<string>("Compatibility - Goop Upgrades", "Shield Color", "#366dff", "The color of the current shield number");
			GoopUpgrades_ShieldMaxColor = configToUse.Bind<string>("Compatibility - Goop Upgrades", "Max Shield Color", "#0000ff", "The color of the max shield number");
			GoopUpgrades_ShieldMaxMatchSlash = configToUse.Bind<bool>("Compatibility - Goop Upgrades", "Use Same Color for Max and Current Shield", false, "If the max shield number and current shield number use the same color (true in vanilla)");
			GoopUpgrades_ShieldPlusSignAsShieldBar = configToUse.Bind<bool>("Compatibility - Goop Upgrades", "Use Shield Sign as Shield Bar", true, "If the shield sign should be used as a progress bar");
			GoopUpgrades_ShieldLabel = configToUse.Bind<string>("Compatibility - Goop Upgrades", "Shield Label", "", "A text label appended to the max shield number. For example, using \"SH\" would make shield show up as \"10 /10SH\" in-game.");
		}
	}
	public class UITweak_Health : MonoBehaviour
	{
		public static UITweak_Health instance;

		public const string hexColorPlusSign = "#56ff6d";

		public const string hexColorHealth = "#56ff6d";

		public const string hexColorMaxHealth = "#008b20";

		private const float VISUAL_PLUSSIGN_MIN = 0.03f;

		private const float VISUAL_PLUSSIGN_MAX = 0.98f;

		private HealthUI healthUI;

		private Image plusSign;

		private Image plusSignBackground;

		private TextMeshProUGUI healthText;

		private TextMeshProUGUI healthTextMax;

		private bool initialized;

		private void Start()
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance != (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			instance = this;
			healthUI = ((Component)this).GetComponent<HealthUI>();
			healthText = ((Component)this).GetComponent<TextMeshProUGUI>();
			healthTextMax = ((Component)((Component)this).transform.Find("HealthMax")).GetComponent<TextMeshProUGUI>();
			plusSign = ((Component)((Component)this).transform.Find("Plus")).GetComponent<Image>();
			plusSign.fillAmount = 1f;
			plusSign.fillMethod = (FillMethod)1;
			plusSign.type = (Type)3;
			plusSignBackground = Object.Instantiate<GameObject>(((Component)plusSign).gameObject, ((Component)plusSign).gameObject.transform.parent).GetComponent<Image>();
			((Object)((Component)plusSignBackground).gameObject).name = "Plus Sign Background";
			((Component)plusSignBackground).gameObject.transform.SetSiblingIndex(0);
			((Graphic)plusSignBackground).color = Color.clear;
			initialized = true;
		}

		private void Update()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			if (initialized)
			{
				((TMP_Text)healthText).faceColor = Color32.op_Implicit(Color.white);
				((Graphic)plusSign).color = Helpers.ToColor(Plugin.HealthPlusSignColor.Value, "#56ff6d");
				((Graphic)plusSignBackground).color = ((Graphic)plusSign).color * new Color(1f, 1f, 1f, 0.1f);
				((Graphic)healthTextMax).color = (Plugin.HealthMaxMatchSlash.Value ? Helpers.ToColor(Plugin.HealthColor.Value, "#56ff6d") : Helpers.ToColor(Plugin.HealthMaxColor.Value, "#008b20"));
				((TMP_Text)healthTextMax).text = ((TMP_Text)healthTextMax).text.Replace("#008b20", Plugin.HealthMaxColor.Value);
				if (((SemiUI)healthUI).flashColorTime > 0f)
				{
					((SemiUI)healthUI).originalTextColor = Helpers.ToColor(Plugin.HealthColor.Value, "#56ff6d");
				}
				else
				{
					((Graphic)healthText).color = Helpers.ToColor(Plugin.HealthColor.Value, "#56ff6d");
				}
				if (!Plugin.HealthPlusSignAsHealthBar.Value || !Object.op_Implicit((Object)(object)PlayerAvatar.instance) || !Object.op_Implicit((Object)(object)PlayerAvatar.instance.playerHealth) || PlayerAvatar.instance.isDisabled)
				{
					plusSign.fillAmount = 1f;
					return;
				}
				int health = PlayerAvatar.instance.playerHealth.health;
				int maxHealth = PlayerAvatar.instance.playerHealth.maxHealth;
				plusSign.fillAmount = NormalizeFillAmount((float)health / (float)maxHealth);
			}
		}

		private float NormalizeFillAmount(float amount)
		{
			if (amount <= 0f)
			{
				return 0f;
			}
			if (amount >= 1f)
			{
				return 1f;
			}
			return Mathf.Lerp(0.03f, 0.98f, amount);
		}
	}
	public class UITweak_Inventory : MonoBehaviour
	{
		public const string colorSlotBg = "#00000064";

		public const string colorSlotOccupiedText = "#ffffff";

		public const string colorSlotText = "#5e5e5e";

		public InventorySpot isp;

		public RawImage bg;

		public TextMeshProUGUI num;

		public TextMeshProUGUI numOccupied;

		private void Start()
		{
			isp = ((Component)this).GetComponent<InventorySpot>();
			bg = ((Component)this).GetComponent<RawImage>();
			Transform val = ((Component)this).transform.Find("No Item");
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = ((Component)this).transform.GetChild(1);
			}
			num = ((Component)val).GetComponent<TextMeshProUGUI>();
			Transform val2 = ((Component)this).transform.Find("Numbers");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				val2 = ((Component)this).transform.Find("Numbers (1)");
			}
			if (!Object.op_Implicit((Object)(object)val2))
			{
				val2 = ((Component)this).transform.GetChild(2);
			}
			numOccupied = ((Component)val2).GetComponent<TextMeshProUGUI>();
		}

		private void Update()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)bg))
			{
				((Graphic)bg).color = Helpers.ToColor(Plugin.InventorySlotBgColor.Value, "#00000064");
			}
			if (Object.op_Implicit((Object)(object)num))
			{
				((Graphic)num).color = Helpers.ToColor(Plugin.InventorySlotNumColor.Value, "#5e5e5e");
			}
			if (Object.op_Implicit((Object)(object)numOccupied))
			{
				((Graphic)numOccupied).color = Helpers.ToColor(Plugin.InventorySlotNumOccupiedColor.Value, "#ffffff");
			}
		}
	}
	public class UITweak_Overcharge : MonoBehaviour
	{
		public static UITweak_Overcharge instance;

		public const string colorSign = "#ff0000";

		public const string colorNum = "#ff0700";

		public const string colorMax = "#fc0000";

		public const string colorRoundBar = "#ff00004b";

		private const float VISUAL_SIGN_MIN = 0.03f;

		private const float VISUAL_SIGN_MAX = 0.96f;

		private OverchargeUI overchargeUI;

		private OverchargeRoundBarUI roundBarUI;

		private Image sign;

		private Image signBackground;

		private TextMeshProUGUI numText;

		private TextMeshProUGUI numTextMax;

		private void Start()
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance != (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			instance = this;
			roundBarUI = ((Component)this).GetComponent<OverchargeRoundBarUI>();
			if (Object.op_Implicit((Object)(object)roundBarUI))
			{
				overchargeUI = Object.FindObjectOfType<OverchargeUI>(true);
				if (Object.op_Implicit((Object)(object)overchargeUI))
				{
					numText = ((Component)overchargeUI).GetComponent<TextMeshProUGUI>();
					numTextMax = ((Component)((Component)overchargeUI).transform.Find("OverchargeMax")).GetComponent<TextMeshProUGUI>();
					sign = ((Component)((Component)overchargeUI).transform.Find("Icon")).GetComponent<Image>();
					sign.fillAmount = 1f;
					sign.fillMethod = (FillMethod)1;
					sign.type = (Type)3;
					signBackground = Object.Instantiate<GameObject>(((Component)sign).gameObject, ((Component)sign).gameObject.transform.parent).GetComponent<Image>();
					((Object)((Component)signBackground).gameObject).name = "Overcharge Sign Background";
					((Component)signBackground).gameObject.transform.SetSiblingIndex(0);
					((Graphic)signBackground).color = Color.clear;
				}
			}
		}

		private void Update()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)roundBarUI))
			{
				roundBarUI.originalColor = Helpers.ToColor(Plugin.OverchargeUIRoundBarColor.Value, "#ff00004b");
			}
			if (!Object.op_Implicit((Object)(object)overchargeUI))
			{
				return;
			}
			if (!Plugin.OverchargeUIShowLegacy.Value)
			{
				((Component)overchargeUI).gameObject.SetActive(false);
				return;
			}
			((Component)overchargeUI).gameObject.SetActive(true);
			((Graphic)sign).color = Helpers.ToColor(Plugin.OverchargeUILegacySignColor.Value, "#ff0000");
			((Graphic)signBackground).color = ((Graphic)sign).color * new Color(1f, 1f, 1f, 0.1f);
			((Graphic)numText).color = Helpers.ToColor(Plugin.OverchargeUILegacyColor.Value, "#ff0700");
			((Graphic)numTextMax).color = (Plugin.OverchargeUILegacyMatchSlash.Value ? Helpers.ToColor(Plugin.OverchargeUILegacyMaxColor.Value, "#ff0700") : Helpers.ToColor(Plugin.OverchargeUILegacyColor.Value, "#fc0000"));
			((TMP_Text)numTextMax).text = ((TMP_Text)numTextMax).text.Replace("red", Plugin.OverchargeUILegacyColor.Value);
			if (PhysGrabber.instance.physGrabBeamOverChargeFloat > 0f && Object.op_Implicit((Object)(object)roundBarUI) && !((Behaviour)roundBarUI.roundBarBG).enabled)
			{
				((Behaviour)roundBarUI.roundBarBG).enabled = true;
			}
			if (!Plugin.OverchargeUILegacySignAsBar.Value)
			{
				sign.fillAmount = 1f;
			}
			else
			{
				sign.fillAmount = NormalizeFillAmount(PhysGrabber.instance.physGrabBeamOverChargeFloat);
			}
		}

		private float NormalizeFillAmount(float amount)
		{
			if (amount <= 0f)
			{
				return 0f;
			}
			if (amount >= 1f)
			{
				return 1f;
			}
			return Mathf.Lerp(0.03f, 0.96f, amount);
		}
	}
	public class UITweak_Stamina : MonoBehaviour
	{
		public static UITweak_Stamina instance;

		public const string hexColorZapSign = "#fcff00";

		public const string hexColorStamina = "#fcff00";

		public const string hexColorMaxStamina = "#ffa500";

		private const float VISUAL_ZAPSIGN_MIN = 0.04f;

		private const float VISUAL_ZAPSIGN_MAX = 0.97f;

		private EnergyUI energyUI;

		private Image zapSign;

		private Image zapSignBackground;

		private TextMeshProUGUI staminaText;

		private TextMeshProUGUI staminaTextMax;

		private bool initialized;

		private void Start()
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance != (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			instance = this;
			energyUI = ((Component)this).GetComponent<EnergyUI>();
			staminaText = ((Component)this).GetComponent<TextMeshProUGUI>();
			staminaTextMax = ((Component)((Component)this).transform.Find("EnergyMax")).GetComponent<TextMeshProUGUI>();
			zapSign = ((Component)((Component)this).transform.Find("Zap")).GetComponent<Image>();
			zapSign.fillAmount = 1f;
			zapSign.fillMethod = (FillMethod)1;
			zapSign.type = (Type)3;
			zapSignBackground = Object.Instantiate<GameObject>(((Component)zapSign).gameObject, ((Component)zapSign).gameObject.transform.parent).GetComponent<Image>();
			((Object)((Component)zapSignBackground).gameObject).name = "Zap Sign Background";
			((Component)zapSignBackground).gameObject.transform.SetSiblingIndex(0);
			((Graphic)zapSignBackground).color = Color.clear;
			initialized = true;
		}

		private void Update()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			if (initialized)
			{
				((Graphic)zapSign).color = Helpers.ToColor(Plugin.StaminaZapSignColor.Value, "#fcff00");
				((Graphic)zapSignBackground).color = ((Graphic)zapSign).color * new Color(1f, 1f, 1f, 0.1f);
				((Graphic)staminaText).color = Helpers.ToColor(Plugin.StaminaZapSignColor.Value, "#fcff00");
				((Graphic)staminaTextMax).color = (Plugin.StaminaMaxMatchSlash.Value ? Helpers.ToColor(Plugin.StaminaColor.Value, "#fcff00") : Helpers.ToColor(Plugin.StaminaMaxColor.Value, "#ffa500"));
				((TMP_Text)staminaTextMax).text = ((TMP_Text)staminaTextMax).text.Replace("orange", Plugin.StaminaMaxColor.Value);
				if (((SemiUI)energyUI).flashColorTime > 0f)
				{
					((SemiUI)energyUI).originalTextColor = Helpers.ToColor(Plugin.StaminaColor.Value, "#fcff00");
				}
				else
				{
					((Graphic)staminaText).color = Helpers.ToColor(Plugin.StaminaColor.Value, "#fcff00");
				}
				if (!Plugin.StaminaZapSignAsStaminaBar.Value || !Object.op_Implicit((Object)(object)PlayerController.instance) || PlayerAvatar.instance.isDisabled)
				{
					zapSign.fillAmount = 1f;
				}
				else
				{
					zapSign.fillAmount = NormalizeFillAmount(PlayerController.instance.EnergyCurrent / PlayerController.instance.EnergyStart);
				}
			}
		}

		private float NormalizeFillAmount(float amount)
		{
			if (amount <= 0f)
			{
				return 0f;
			}
			if (amount >= 1f)
			{
				return 1f;
			}
			return Mathf.Lerp(0.04f, 0.97f, amount);
		}
	}
	public class UITweak_Tumble : MonoBehaviour
	{
		public const string hexColorExitLight = "#ffb20050";

		public const string hexColorExitDark = "#ffb20032";

		public const string hexColorStunnedLight = "#ff000050";

		public const string hexColorStunnedDark = "#ff000032";

		public static UITweak_Tumble instance;

		private TumbleUI tumbleUI;

		private bool init;

		private IEnumerator Start()
		{
			yield return (object)new WaitUntil((Func<bool>)(() => LevelGenerator.Instance.Generated));
			if ((Object)(object)instance != (Object)null)
			{
				Object.Destroy((Object)(object)this);
				yield break;
			}
			instance = this;
			tumbleUI = ((Component)this).GetComponent<TumbleUI>();
			if ((Object)(object)tumbleUI == (Object)null)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			else
			{
				init = true;
			}
		}

		private void Update()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (init)
			{
				tumbleUI.canExitColor1 = Helpers.ToColor(Plugin.TumbleUIColorExitLight.Value, "#ffb20050");
				tumbleUI.canExitColor2 = Helpers.ToColor(Plugin.TumbleUIColorExitDark.Value, "#ffb20032");
				tumbleUI.canNotExitColor1 = Helpers.ToColor(Plugin.TumbleUIColorStunnedLight.Value, "#ff000050");
				tumbleUI.canNotExitColor2 = Helpers.ToColor(Plugin.TumbleUIColorStunnedLight.Value, "#ff000032");
				tumbleUI.updateTime = 1f / (float)Plugin.TumbleUIFrameRate.Value;
				tumbleUI.introSpeed = Plugin.TumbleUIInSpeed.Value;
				tumbleUI.outroSpeed = Plugin.TumbleUIOutSpeed.Value;
			}
		}
	}
	public class UITweak_TumbleWings : MonoBehaviour
	{
		public const string hexColorWing = "#0065ff";

		public const string hexColorHolder = "#00beff";

		public const string hexColorBar = "#00bbff";

		public static UITweak_TumbleWings instance;

		private TumbleWingsUI tumbleWingsUI;

		private TextMeshProUGUI[] holder;

		private RawImage[] wings;

		private RawImage bar;

		private bool setup;

		private Coroutine coroutine;

		private void Start()
		{
			if ((Object)(object)instance != (Object)null)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			instance = this;
			tumbleWingsUI = ((Component)this).GetComponent<TumbleWingsUI>();
		}

		private void OnDestroy()
		{
			if (coroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(coroutine);
			}
		}

		private void Setup()
		{
			if (!setup)
			{
				setup = true;
				holder = (TextMeshProUGUI[])(object)new TextMeshProUGUI[2]
				{
					((Component)((Component)this).transform.Find("Bar/Holder Left")).gameObject.GetComponent<TextMeshProUGUI>(),
					((Component)((Component)this).transform.Find("Bar/Holder Right")).gameObject.GetComponent<TextMeshProUGUI>()
				};
				wings = (RawImage[])(object)new RawImage[2]
				{
					((Component)((Component)this).transform.Find("Bar/Wing Left")).gameObject.GetComponentInChildren<RawImage>(true),
					((Component)((Component)this).transform.Find("Bar/Wing Right")).gameObject.GetComponentInChildren<RawImage>(true)
				};
				bar = ((Component)((Component)this).transform.Find("Bar/Tumble Wings Bar")).gameObject.GetComponent<RawImage>();
				coroutine = ((MonoBehaviour)this).StartCoroutine(Change());
			}
		}

		private void Update()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)tumbleWingsUI.itemUpgradePlayerTumbleWingsLogic))
			{
				Setup();
				if (!(tumbleWingsUI.itemUpgradePlayerTumbleWingsLogic.tumbleWingTimer <= 0f))
				{
					Color val = Helpers.ToColor(Plugin.TumbleWingUIBarColorStart.Value, "#00bbff");
					Color val2 = Helpers.ToColor(Plugin.TumbleWingUIBarColorEnd.Value, "#00bbff");
					((Graphic)bar).color = Color.Lerp(val2, val, tumbleWingsUI.itemUpgradePlayerTumbleWingsLogic.tumbleWingTimer);
				}
			}
		}

		private IEnumerator Change()
		{
			while (true)
			{
				yield return (object)new WaitForSeconds(5f);
				TextMeshProUGUI[] array = holder;
				for (int i = 0; i < array.Length; i++)
				{
					((Graphic)array[i]).color = Helpers.ToColor(Plugin.TumbleWingUIHolderColor.Value, "#00beff");
				}
				RawImage[] array2 = wings;
				for (int i = 0; i < array2.Length; i++)
				{
					((Graphic)array2[i]).color = Helpers.ToColor(Plugin.TumbleWingUIWingColor.Value, "#0065ff");
				}
			}
		}
	}
}
namespace RepoHUDTweaks.patches
{
	[HarmonyPatch(typeof(Aim))]
	internal class AimPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakeP()
		{
			Update();
		}

		public static void Update()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected I4, but got Unknown
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Aim.instance) || Aim.instance.aimStates.Count == 0)
			{
				return;
			}
			AimState val = Aim.instance.defaultState;
			foreach (AimState aimState in Aim.instance.aimStates)
			{
				if (Aim.instance.currentState == aimState.State)
				{
					val = aimState;
				}
				State state = aimState.State;
				switch ((int)state)
				{
				case 0:
					aimState.Color = Helpers.ToColor(Plugin.AimColorDefault.Value, aimState.Color);
					break;
				case 1:
					aimState.Color = Helpers.ToColor(Plugin.AimColorGrabbable.Value, aimState.Color);
					break;
				case 2:
					aimState.Color = Helpers.ToColor(Plugin.AimColorGrab.Value, aimState.Color);
					break;
				case 3:
					aimState.Color = Helpers.ToColor(Plugin.AimColorRotate.Value, aimState.Color);
					break;
				case 5:
					aimState.Color = Helpers.ToColor(Plugin.AimColorClimbable.Value, aimState.Color);
					break;
				case 6:
					aimState.Color = Helpers.ToColor(Plugin.AimColorClimb.Value, aimState.Color);
					break;
				case 7:
					aimState.Color = Helpers.ToColor(Plugin.AimColorDisabled.Value, aimState.Color);
					break;
				}
			}
			Aim instance = Aim.instance;
			Color currentColor = (((Graphic)Aim.instance.image).color = val.Color);
			instance.currentColor = currentColor;
		}
	}
	[HarmonyPatch(typeof(BigMessageUI))]
	internal class BigMessageUIPatch
	{
		public const string colorBigMessage = "#ffffff";

		[HarmonyPatch("BigMessage")]
		[HarmonyPostfix]
		private static void BigMessage(ref BigMessageUI __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.bigMessageColor == Color.white)
			{
				if (((SemiUI)__instance).flashColorTime > 0f)
				{
					((SemiUI)__instance).originalTextColor = Helpers.ToColor(Plugin.BigMessageUIColor.Value, "#ffffff");
				}
				else
				{
					((Graphic)__instance.Text).color = Helpers.ToColor(Plugin.BigMessageUIColor.Value, "#ffffff");
				}
			}
		}
	}
	[HarmonyPatch(typeof(CurrencyUI))]
	internal class CurrencyUIPatch
	{
		public const string currencyColorDefault = "#c9e9e6";

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update(ref CurrencyUI __instance)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (((SemiUI)__instance).flashColorTime > 0f)
			{
				((SemiUI)__instance).originalTextColor = Helpers.ToColor(Plugin.CurrencyUIColor.Value, "#c9e9e6");
			}
			else
			{
				((Graphic)__instance.Text).color = Helpers.ToColor(Plugin.CurrencyUIColor.Value, "#c9e9e6");
			}
		}
	}
	[HarmonyPatch(typeof(DirtFinderCounter))]
	internal class DirtFinderCounterPatch
	{
		public const string colorMapAmbientLight = "#00ff19";

		private static Light mapAmbientLight;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update(ref DirtFinderCounter __instance)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			FetchStuff(__instance);
			if (Object.op_Implicit((Object)(object)mapAmbientLight))
			{
				mapAmbientLight.color = Helpers.ToColor(Plugin.MapAmbientColor.Value, "#00ff19");
			}
		}

		private static void FetchStuff(DirtFinderCounter dfc)
		{
			if ((Object)(object)mapAmbientLight == (Object)null)
			{
				mapAmbientLight = ((Component)((Component)dfc).transform.parent.Find("Light")).GetComponent<Light>();
			}
		}
	}
	public class DirtFinderPatches
	{
		[HarmonyPatch(typeof(DirtFinderMapPlayer), "Awake")]
		[HarmonyPostfix]
		private static void DFMP_AwakeP()
		{
			UpdatePlayer();
		}

		public static void UpdatePlayer()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)DirtFinderMapPlayer.Instance))
			{
				((Component)((Component)DirtFinderMapPlayer.Instance).transform.Find("Player Graphic")).GetComponent<SpriteRenderer>().color = Helpers.ToColor(Plugin.MapObjectPlayerColor.Value, "#72ff79");
			}
		}

		[HarmonyPatch(typeof(DirtFinderMapDoorTarget), "Start")]
		[HarmonyPostfix]
		private static void DFMDT_StartP(ref DirtFinderMapDoorTarget __instance)
		{
			UpdateDoorTarget(__instance);
		}

		public static void UpdateAllDoorTargets()
		{
			DirtFinderMapDoorTarget[] array = Object.FindObjectsOfType<DirtFinderMapDoorTarget>();
			for (int i = 0; i < array.Length; i++)
			{
				UpdateDoorTarget(array[i]);
			}
		}

		private static void UpdateDoorTarget(DirtFinderMapDoorTarget target)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			MeshRenderer[] componentsInChildren = ((Component)target).GetComponentsInChildren<MeshRenderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Renderer)componentsInChildren[i]).material.color = Helpers.ToColor(Plugin.MapObjectDoorColor.Value, "#45ff50");
			}
		}

		[HarmonyPatch(typeof(MapBacktrack), "Start")]
		[HarmonyPostfix]
		private static void MB_StartP(ref MapBacktrack __instance)
		{
			UpdateBacktrack(__instance);
		}

		public static void UpdateBacktrack(MapBacktrack mb)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)mb == (Object)null)
			{
				mb = Object.FindObjectOfType<MapBacktrack>();
			}
			if (!((Object)(object)mb == (Object)null))
			{
				for (int i = 0; i < mb.points.Count; i++)
				{
					Color color = GetLerp(i, mb.points.Count - 1);
					mb.points[i].spriteRenderer.color = color;
				}
			}
			static Color GetLerp(int index, int count)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				Color val = Helpers.ToColor(Plugin.MapObjectBacktrackColorStart.Value, "#ffffff");
				Color val2 = Helpers.ToColor(Plugin.MapObjectBacktrackColorEnd.Value, "#ffffff");
				return Color.Lerp(val, val2, (float)index / (float)count);
			}
		}
	}
	[HarmonyPatch(typeof(EnergyUI))]
	internal class EnergyUIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(ref EnergyUI __instance)
		{
			((Component)__instance).gameObject.AddComponent<UITweak_Stamina>();
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref EnergyUI __instance)
		{
			if (Plugin.ScaleUpStamina.Value)
			{
				string text = Mathf.Ceil(PlayerController.instance.EnergyCurrent * 2.5f).ToString();
				string text2 = Mathf.Ceil(PlayerController.instance.EnergyStart * 2.5f).ToString();
				((TMP_Text)__instance.Text).text = text;
				((TMP_Text)__instance.textEnergyMax).text = "<b><color=orange>/</color></b>" + text2;
				((TMP_Text)__instance.textEnergyMax).text.Replace("orange", Plugin.StaminaMaxColor.Value);
			}
			if (!string.IsNullOrEmpty(Plugin.StaminaLabel.Value) && !((SemiUI)__instance).isHidden)
			{
				TextMeshProUGUI textEnergyMax = __instance.textEnergyMax;
				((TMP_Text)textEnergyMax).text = ((TMP_Text)textEnergyMax).text + Plugin.StaminaLabel.Value;
			}
		}
	}
	[HarmonyPatch(typeof(GoalUI))]
	internal class GoalUIPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref GoalUI __instance)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			((TMP_Text)__instance.Text).text = ((TMP_Text)__instance.Text).text.Replace("#7D250B", Plugin.GoalUISlashColor.Value);
			if (((SemiUI)__instance).flashColorTime > 0f)
			{
				((SemiUI)__instance).originalTextColor = Helpers.ToColor(Plugin.GoalUIColor.Value, "#ff5f00");
			}
			else
			{
				((Graphic)__instance.Text).color = Helpers.ToColor(Plugin.GoalUIColor.Value, "#ff5f00");
			}
		}
	}
	[HarmonyPatch(typeof(HaulUI))]
	internal class HaulUIPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref HaulUI __instance)
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			((TMP_Text)__instance.Text).text = ((TMP_Text)__instance.Text).text.Replace("#558B2F", Plugin.HaulUIDollarSignColor.Value);
			((TMP_Text)__instance.Text).text = ((TMP_Text)__instance.Text).text.Replace("#558b2f", Plugin.HaulUIDollarSignColor.Value);
			((TMP_Text)__instance.Text).text = ((TMP_Text)__instance.Text).text.Replace("#616161", Plugin.HaulUISlashColor.Value);
			if (((SemiUI)__instance).flashColorTime > 0f)
			{
				((SemiUI)__instance).originalTextColor = Helpers.ToColor(Plugin.HaulUIColor.Value, "#c9e9e6");
			}
			else
			{
				((Graphic)__instance.Text).color = Helpers.ToColor(Plugin.HaulUIColor.Value, "#c9e9e6");
			}
		}
	}
	[HarmonyPatch(typeof(HealthUI))]
	internal class HealthUIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(ref HealthUI __instance)
		{
			((Component)__instance).gameObject.AddComponent<UITweak_Health>();
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref HealthUI __instance)
		{
			if (!string.IsNullOrEmpty(Plugin.HealthLabel.Value) && !((SemiUI)__instance).isHidden)
			{
				TextMeshProUGUI textMaxHealth = __instance.textMaxHealth;
				((TMP_Text)textMaxHealth).text = ((TMP_Text)textMaxHealth).text + Plugin.HealthLabel.Value;
			}
		}
	}
	[HarmonyPatch(typeof(HurtVignette))]
	internal class HurtVignettePatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		private static bool UpdateP(ref HurtVignette __instance)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelGenerator.Instance.Generated || SemiFunc.MenuLevel())
			{
				return false;
			}
			if ((Object)(object)PlayerAvatar.instance == (Object)null)
			{
				return false;
			}
			__instance.activeColor = Helpers.ToColor(Plugin.HurtVignetteColor.Value, __instance.activeColor);
			if (!Plugin.HurtVignetteHealthBased.Value || !Object.op_Implicit((Object)(object)PlayerAvatar.instance.playerHealth))
			{
				return true;
			}
			float num = (float)PlayerAvatar.instance.playerHealth.health / (float)PlayerAvatar.instance.playerHealth.maxHealth;
			float num2 = Mathf.Max(Plugin.HurtVignetteHealthBasedScaleMax.Value, Plugin.HurtVignetteHealthBasedScaleMin.Value);
			float num3 = Mathf.Min(Plugin.HurtVignetteHealthBasedScaleMax.Value, Plugin.HurtVignetteHealthBasedScaleMin.Value);
			if ((num >= 1f && !Plugin.HurtVignetteAtMaxHealth.Value) || (PlayerAvatar.instance.isDisabled && !Plugin.HurtVignetteWhileDead.Value))
			{
				Image image = __instance.image;
				((Graphic)image).color = ((Graphic)image).color * new Color(0f, 0f, 0f, 0f);
			}
			else
			{
				((Graphic)__instance.image).color = __instance.activeColor;
			}
			((Transform)__instance.rectTransform).localScale = Vector3.one * Mathf.Lerp(num3, num2, num);
			return false;
		}

		public static void SpoofLerp()
		{
			if (Object.op_Implicit((Object)(object)HurtVignette.instance))
			{
				HurtVignette.instance.lerp = 0.5f;
			}
		}
	}
	[HarmonyPatch(typeof(InventorySpot))]
	internal class InventorySpotPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Start(ref InventorySpot __instance)
		{
			((Component)__instance).gameObject.AddComponent<UITweak_Inventory>();
		}
	}
	[HarmonyPatch(typeof(ItemInfoUI))]
	internal class ItemInfoUIPatch
	{
		public const string colorGradStart = "#ffff00";

		public const string colorGradEnd = "#ff6300";

		public const string colorGradEnemyStart = "#ff0000";

		public const string colorGradEnemyEnd = "#ff1a00";

		[HarmonyPatch("ItemInfoText")]
		[HarmonyPostfix]
		private static void ItemInfoText(ref ItemInfoUI __instance, ref bool enemy)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if (enemy)
			{
				Color val = Helpers.ToColor(Plugin.ItemInfoUIGradEnemyStart.Value, "#ff0000");
				Color val2 = Helpers.ToColor(Plugin.ItemInfoUIGradEnemyEnd.Value, "#ff1a00");
				((TMP_Text)__instance.Text).colorGradient = new VertexGradient(val, val, val2, val2);
			}
			else
			{
				Color val3 = Helpers.ToColor(Plugin.ItemInfoUIGradStart.Value, "#ffff00");
				Color val4 = Helpers.ToColor(Plugin.ItemInfoUIGradEnd.Value, "#ff6300");
				__instance.originalGradient = new VertexGradient(val3, val3, val4, val4);
				HandleGrabbedObjectBattery();
			}
		}

		private static void HandleGrabbedObjectBattery()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.ItemInfoUIShowItemBattery.Value && Object.op_Implicit((Object)(object)PhysGrabber.instance) && Object.op_Implicit((Object)(object)PhysGrabber.instance.grabbedPhysGrabObject) && !(ItemInfoUI.instance.messageTimer <= 0f) && !(ItemInfoUI.instance.messagePrev == "prev"))
			{
				ItemBattery component = ((Component)PhysGrabber.instance.grabbedPhysGrabObject).GetComponent<ItemBattery>();
				if (Object.op_Implicit((Object)(object)component))
				{
					Color colorFromProgress = WorldSpaceUIValuePatch.GetColorFromProgress(Mathf.Clamp01(component.batteryLife / 100f));
					((TMP_Text)ItemInfoUI.instance.Text).text = ItemInfoUI.instance.messagePrev + $" (<color=#{Helpers.ToHex(colorFromProgress)}>{Mathf.CeilToInt(component.batteryLife)}%</color>)";
				}
			}
		}
	}
	[HarmonyPatch(typeof(Map))]
	public class MapPatch
	{
		public const string colorWall = "#077600";

		public const string colorFloor = "#004803";

		public const string colorInactiveWall = "#8e4000";

		public const string colorInactiveFloor = "#542400";

		public const string colorTruckWall = "#00797d";

		public const string colorTruckFloor = "#005154";

		public const string colorUsedWall = "#950001";

		public const string colorUsedFloor = "#4d0005";

		public const string colorUnexploredOutline = "#008908";

		public const string colorUnexplored = "#000000";

		public const string colorStairs = "#2aff37";

		public const string colorUnexploredGraphic = "#00bc09";

		public const string colorObjectItem = "#00ffeb";

		public const string colorObjectValuable = "#ffd300";

		public const string colorObjectDeathHead = "#ff000e";

		public const string colorObjectDoor = "#45ff50";

		public const string colorObjectPlayer = "#72ff79";

		public const string colorObjectBacktrack = "#ffffff";

		public const string colorBackground = "#004f02";

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(ref Map __instance)
		{
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> obj = new List<GameObject>
			{
				__instance.Wall1x1Object, __instance.Wall1x1DiagonalObject, __instance.Wall1x1CurveObject, __instance.Wall1x05Object, __instance.Wall1x05DiagonalObject, __instance.Wall1x05CurveObject, __instance.Wall1x025Object, __instance.Wall1x025DiagonalObject, __instance.Door1x1Object, __instance.Door1x05Object,
				__instance.Door1x1DiagonalObject, __instance.Door1x05DiagonalObject, __instance.Door1x2Object, __instance.Door1x1WizardObject, __instance.Door1x1ArcticObject, __instance.Door1x1MuseumObject, __instance.DoorBlockedObject, __instance.DoorBlockedWizardObject, __instance.DoorBlockedArcticObject, __instance.DoorDiagonalObject
			};
			List<GameObject> list = new List<GameObject> { __instance.FloorObject1x1, __instance.FloorObject1x1Diagonal, __instance.FloorObject1x1Curve, __instance.FloorObject1x1CurveInverted, __instance.FloorObject1x05, __instance.FloorObject1x05Diagonal, __instance.FloorObject1x05Curve, __instance.FloorObject1x05CurveInverted, __instance.FloorObject1x025, __instance.FloorObject1x025Diagonal };
			foreach (GameObject item in obj)
			{
				ApplyColorToMeshRenderer(item, Helpers.ToColor(Plugin.MapWallColor.Value, "#077600"));
			}
			foreach (GameObject item2 in list)
			{
				ApplyColorToMeshRenderer(item2, Helpers.ToColor(Plugin.MapFloorColor.Value, "#004803"));
			}
			ApplyColorToMeshRenderer(__instance.StairsObject, Helpers.ToColor(Plugin.MapStairsColor.Value, "#2aff37"));
			ApplyColorToMeshRenderer(__instance.WallInactive, Helpers.ToColor(Plugin.MapInactiveWallColor.Value, "#8e4000"));
			ApplyColorToMeshRenderer(__instance.FloorInactive, Helpers.ToColor(Plugin.MapInactiveFloorColor.Value, "#542400"));
			ApplyColorToMeshRenderer(__instance.WallTruck, Helpers.ToColor(Plugin.MapTruckWallColor.Value, "#00797d"));
			ApplyColorToMeshRenderer(__instance.FloorTruck, Helpers.ToColor(Plugin.MapTruckFloorColor.Value, "#005154"));
			ApplyColorToMeshRenderer(__instance.WallUsed, Helpers.ToColor(Plugin.MapUsedWallColor.Value, "#950001"));
			ApplyColorToMeshRenderer(__instance.FloorUsed, Helpers.ToColor(Plugin.MapUsedFloorColor.Value, "#4d0005"));
			ApplyColorToMeshRenderer(__instance.RoomVolumeOutline, Helpers.ToColor(Plugin.MapUnexploredOutlineColor.Value, "#008908"));
			ApplyColorToMeshRenderer(__instance.RoomVolume, Helpers.ToColor(Plugin.MapUnexploredColor.Value, "#000000"));
			__instance.ModulePrefab.GetComponentInChildren<SpriteRenderer>().color = Helpers.ToColor(Plugin.MapUnexploredGraphicColor.Value, "#00bc09");
		}

		private static void ApplyColorToMeshRenderer(GameObject mapObject, Color color)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			MeshRenderer[] componentsInChildren = mapObject.GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					((Renderer)val).material.color = color;
				}
			}
		}

		private static Color ConvertCustomEntityColor(Color color)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			string text = "#" + ColorUtility.ToHtmlStringRGB(color).ToLower();
			if (text == "#00ffeb")
			{
				return Helpers.ToColor(Plugin.MapObjectItemColor.Value, "#00ffeb");
			}
			if (text == "#ff000e")
			{
				return Helpers.ToColor(Plugin.MapObjectDeathHeadColor.Value, "#ff000e");
			}
			return color;
		}

		[HarmonyPatch(typeof(MapValuable), "Start")]
		[HarmonyPostfix]
		private static void MapValuable_StartP(ref MapValuable __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			__instance.spriteRenderer.color = Helpers.ToColor(Plugin.MapObjectValuableColor.Value, "#ffd300");
		}

		[HarmonyPatch("AddCustom")]
		[HarmonyPrefix]
		private static void AddCustomP(ref Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			color = ConvertCustomEntityColor(color);
		}

		public static void UpdateAllValuables()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			MapValuable[] array = Object.FindObjectsOfType<MapValuable>();
			for (int i = 0; i < array.Length; i++)
			{
				array[i].spriteRenderer.color = Helpers.ToColor(Plugin.MapObjectValuableColor.Value, "#ffd300");
			}
		}

		public static void UpdateAllItems()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			MapCustomEntity[] array = Object.FindObjectsOfType<MapCustomEntity>();
			foreach (MapCustomEntity val in array)
			{
				val.spriteRenderer.color = ConvertCustomEntityColor(val.mapCustom.color);
			}
		}

		public static void UpdateBG()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)Map.Instance))
			{
				MeshRenderer component = ((Component)((Component)Map.Instance).transform.parent.Find("Active/Player/Background")).GetComponent<MeshRenderer>();
				if (Object.op_Implicit((Object)(object)component))
				{
					((Renderer)component).material.color = Helpers.ToColor(Plugin.MapBackgroundColor.Value, "#004f02");
				}
			}
		}
	}
	[HarmonyPatch(typeof(MissionUI))]
	internal class MissionUIPatch
	{
		public const string colorMission = "#ffffff";

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update(ref MissionUI __instance)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (((SemiUI)__instance).flashColorTime > 0f)
			{
				((SemiUI)__instance).originalTextColor = Helpers.ToColor(Plugin.MissionUIColor.Value, "#ffffff");
			}
			else
			{
				((Graphic)__instance.Text).color = Helpers.ToColor(Plugin.MissionUIColor.Value, "#ffffff");
			}
		}
	}
	[HarmonyPatch(typeof(OverchargeRoundBarUI))]
	internal class OverchargeRoundBarUIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(ref OverchargeRoundBarUI __instance)
		{
			((Component)__instance).gameObject.AddComponent<UITweak_Overcharge>();
		}
	}
	[HarmonyPatch(typeof(OverchargeUI))]
	public class OverchargeUIPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref OverchargeUI __instance)
		{
			if (!string.IsNullOrEmpty(Plugin.OverchargeUILegacyLabel.Value) && !((SemiUI)__instance).isHidden)
			{
				TextMeshProUGUI textOverchargeMax = __instance.textOverchargeMax;
				((TMP_Text)textOverchargeMax).text = ((TMP_Text)textOverchargeMax).text + Plugin.OverchargeUILegacyLabel.Value;
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabber))]
	internal class PhysGrabberPatch
	{
		private static string cachedName = "";

		private static string lastName = "";

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref PhysGrabber __instance)
		{
			if (__instance.isLocal && Object.op_Implicit((Object)(object)__instance.grabbedPhysGrabObject) && __instance.grabbedPhysGrabObject.isValuable && Plugin.ItemInfoUIShowValuableNames.Value)
			{
				ItemInfoUI.instance.ItemInfoText((ItemAttributes)null, GetGrabbedPhysObjectLabel(), false);
			}
		}

		private static string GetGrabbedPhysObjectLabel()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			PhysGrabObject grabbedPhysGrabObject = PhysGrabber.instance.grabbedPhysGrabObject;
			string text = GetName(((Object)grabbedPhysGrabObject).name);
			if (Plugin.ItemInfoUIShowValuableValues.Value)
			{
				ValuableObject component = ((Component)grabbedPhysGrabObject).GetComponent<ValuableObject>();
				float progress = Mathf.Clamp01(component.dollarValueCurrent / component.dollarValueOriginal);
				string text2 = "$" + SemiFunc.DollarGetString((int)component.dollarValueCurrent);
				Color colorFromProgress = WorldSpaceUIValuePatch.GetColorFromProgress(progress);
				text = text + " (<color=#" + Helpers.ToHex(colorFromProgress) + ">" + text2 + "</color>)";
			}
			return text;
		}

		private static string GetName(string gameObjectName)
		{
			if (gameObjectName == cachedName)
			{
				return lastName;
			}
			lastName = gameObjectName.Replace("Valuable Wizard ", "").Replace("Valuable Manor ", "").Replace("Valuable Arctic ", "")
				.Replace("Valuable Museum ", "")
				.Replace("Valuable Desert ", "")
				.Replace("Valuable ", "")
				.Replace("(Clone)", "");
			cachedName = gameObjectName;
			return lastName;
		}
	}
	[HarmonyPatch(typeof(PhysGrabObjectImpactDetector))]
	internal class PhysGrabObjectImpactDetectorPatch
	{
		[HarmonyPatch("DestroyObjectRPC")]
		[HarmonyPrefix]
		private static void DestroyObjectRPCP(ref PhysGrabObjectImpactDetector __instance, ref PhotonMessageInfo _info)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.WSUIVL_AlwaysDisplayWhenPossible.Value && SemiFunc.MasterOnlyRPC(_info) && Object.op_Implicit((Object)(object)__instance.valuableObject) && !(__instance.valuableObject.dollarValueCurrent < __instance.valuableObject.dollarValueOriginal * 0.15f))
			{
				WorldSpaceUIParent.instance.ValueLostCreate(((Component)__instance).transform.position, (int)__instance.valuableObject.dollarValueCurrent);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerController))]
	internal class PlayerControllerPatch
	{
		private static PlayerAvatar Self => PlayerAvatar.instance;

		private static PlayerTumble Tumble => PlayerAvatar.instance.tumble;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateP(ref PlayerController __instance)
		{
			if (!LevelGenerator.Instance.Generated || SemiFunc.MenuLevel())
			{
				return;
			}
			bool flag = Mathf.Abs(SemiFunc.InputMovementX()) > 0f || Mathf.Abs(SemiFunc.InputMovementY()) > 0f;
			if (Self.isTumbling)
			{
				if (Plugin.WASDCancelsTumbleImmediately.Value)
				{
					bool flag2 = __instance.tumbleInputDisableTimer <= 0f && !Tumble.tumbleOverride && __instance.InputDisableTimer <= 0f;
					if (flag && flag2)
					{
						Tumble.TumbleRequest(false, true);
					}
				}
			}
			else
			{
				if (Plugin.SpaceToExitCrouch.Value && __instance.toggleCrouch && __instance.JumpImpulse)
				{
					__instance.toggleCrouch = false;
				}
				if (Plugin.SprintToExitCrouch.Value && __instance.toggleCrouch && flag && SemiFunc.InputDown((InputKey)15) && __instance.InputDisableTimer <= 0f)
				{
					__instance.toggleCrouch = false;
				}
			}
		}
	}
	[HarmonyPatch(typeof(StatsUI))]
	internal class StatsUIPatch
	{
		public const string colorNames = "#ff8d00";

		public const string colorValues = "#ffffff";

		private static TextMeshProUGUI names;

		private static TextMeshProUGUI values;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update(ref StatsUI __instance)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)names))
			{
				names = ((Component)__instance).GetComponent<TextMeshProUGUI>();
			}
			if (!Object.op_Implicit((Object)(object)values))
			{
				values = ((Component)((Component)__instance).transform.Find("StatsNumbers")).GetComponent<TextMeshProUGUI>();
			}
			if (Object.op_Implicit((Object)(object)names))
			{
				((Graphic)names).color = Helpers.ToColor(Plugin.UpgradeNameColor.Value, "#ff8d00");
			}
			if (Object.op_Implicit((Object)(object)values))
			{
				((Graphic)values).color = Helpers.ToColor(Plugin.UpgradeValueColor.Value, "#ffffff");
			}
		}
	}
	[HarmonyPatch(typeof(ToggleMuteUI))]
	internal class ToggleMuteUIPatch
	{
		public const string colorMuted = "#ff9400";

		private static Image muteIcon;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update(ref ToggleMuteUI __instance)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)muteIcon == (Object)null)
			{
				muteIcon = ((Component)((Component)__instance).transform.Find("Icon")).GetComponent<Image>();
			}
			else
			{
				((Graphic)muteIcon).color = Helpers.ToColor(Plugin.ToggleMuteUIColor.Value, "#ff9400");
			}
		}
	}
	[HarmonyPatch(typeof(TumbleUI))]
	internal class TumbleUIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(ref TumbleUI __instance)
		{
			((Component)__instance).gameObject.AddComponent<UITweak_Tumble>();
		}
	}
	[HarmonyPatch(typeof(TumbleWingsUI))]
	internal class TumbleWingsUIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(ref TumbleWingsUI __instance)
		{
			((Component)__instance).gameObject.AddComponent<UITweak_TumbleWings>();
		}
	}
	[HarmonyPatch(typeof(VehicleUI))]
	public class VehicleUIPatch
	{
		public const string colorSpeed = "#ffeb04";

		public const string colorSpeedL0 = "#4a151080";

		public const string colorSpeedLabel = "#ffa500";

		public const string colorDollarSign = "#558b2f80";

		public const string colorDollarL0 = "#4a151080";

		public const string colorDollarValue = "#ffff00a6";

		[HarmonyPatch("ShowSpeed")]
		[HarmonyPostfix]
		private static void ShowSpeed(ref VehicleUI __instance)
		{
			((TMP_Text)__instance.Text).text = ((TMP_Text)__instance.Text).text.Replace("orange", "{1}").Replace("yellow", "{2}").Replace("#4A151080", "{3}");
			((TMP_Text)__instance.Text).text = ((TMP_Text)__instance.Text).text.Replace("{1}", Plugin.VehicleSpeedLabelColor.Value).Replace("{2}", Plugin.VehicleSpeedColor.Value).Replace("{3}", Plugin.VehicleSpeedLeadingZeroColor.Value);
		}

		[HarmonyPatch("ShowValuableBoxValue")]
		[HarmonyPostfix]
		private static void ShowValuableBoxValue(ref VehicleUI __instance)
		{
			((TMP_Text)__instance.valuableBoxText).text = ((TMP_Text)__instance.valuableBoxText).text.Replace("#FFFF00A6", "{1}").Replace("#4A151080", "{2}").Replace("#558B2F80", "{3}");
			((TMP_Text)__instance.valuableBoxText).text = ((TMP_Text)__instance.valuableBoxText).text.Replace("{1}", Plugin.VehicleDollarValueColor.Value).Replace("{2}", Plugin.VehicleDollarValueLeadingZeroColor.Value).Replace("{3}", Plugin.VehicleDollarSignColor.Value);
		}
	}
	[HarmonyPatch(typeof(WorldSpaceUIValueLost))]
	internal class WorldSpaceUIValueLostPatch
	{
		public class ValueBreakpoint
		{
			public ConfigEntry<string> color;

			public ConfigEntry<float> scale;

			public ConfigEntry<float> time;

			public ValueBreakpoint(ConfigEntry<string> _color, ConfigEntry<float> _scale, ConfigEntry<float> _time)
			{
				color = _color;
				scale = _scale;
				time = _time;
			}
		}

		public const string VALUE_LOST_COLOR = "#f13337";

		public static Dictionary<float, ValueBreakpoint> valueBreakpoints = new Dictionary<float, ValueBreakpoint>
		{
			{
				50000f,
				new ValueBreakpoint(Plugin.WSUIVL_Color50000, Plugin.WSUIVL_Scale50000, Plugin.WSUIVL_Timer50000)
			},
			{
				10000f,
				new ValueBreakpoint(Plugin.WSUIVL_Color10000, Plugin.WSUIVL_Scale10000, Plugin.WSUIVL_Timer10000)
			},
			{
				5000f,
				new ValueBreakpoint(Plugin.WSUIVL_Color5000, Plugin.WSUIVL_Scale5000, Plugin.WSUIVL_Timer5000)
			},
			{
				1000f,
				new ValueBreakpoint(Plugin.WSUIVL_Color1000, Plugin.WSUIVL_Scale1000, Plugin.WSUIVL_Timer1000)
			},
			{
				0f,
				new ValueBreakpoint(Plugin.WSUIVL_Color0, Plugin.WSUIVL_Scale0, Plugin.WSUIVL_Timer0)
			}
		};

		private static (ValueBreakpoint, ValueBreakpoint, float) GetBreakpoint(float value)
		{
			if (value <= 0f)
			{
				return (valueBreakpoints.Last().Value, valueBreakpoints.Last().Value, 0f);
			}
			ValueBreakpoint value2 = valueBreakpoints.First().Value;
			float num = float.MaxValue;
			foreach (KeyValuePair<float, ValueBreakpoint> valueBreakpoint in valueBreakpoints)
			{
				if (value >= valueBreakpoint.Key)
				{
					return (valueBreakpoint.Value, value2, Mathf.InverseLerp(valueBreakpoint.Key, num, value));
				}
				value2 = valueBreakpoint.Value;
				num = valueBreakpoint.Key;
			}
			return (value2, value2, 0f);
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartP(WorldSpaceUIValueLost __instance)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_0081: 

modules/ShaderEdit.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
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("ShaderEdit")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ShaderEdit")]
[assembly: AssemblyTitle("ShaderEdit")]
[assembly: AssemblyVersion("1.0.1.0")]
namespace ShaderEdit;

public struct FogValues
{
	public bool Enabled;

	public int Mode;

	public float Start;

	public float End;

	public float Density;

	public float FarClip;
}
public interface IFogEnvironment
{
	int SceneToken { get; }

	bool IsValid { get; }

	FogValues Read();

	void Write(FogValues values);
}
public sealed class FogRenderOverride
{
	private IFogEnvironment environment;

	private FogValues original;

	private int sceneToken;

	public void Begin(IFogEnvironment target, string mode)
	{
		End();
		if (!(mode == "Default") && target.IsValid)
		{
			original = target.Read();
			sceneToken = target.SceneToken;
			environment = target;
			target.Write(Calculate(original, mode));
		}
	}

	public void End()
	{
		if (environment != null)
		{
			IFogEnvironment fogEnvironment = environment;
			environment = null;
			if (fogEnvironment.IsValid && fogEnvironment.SceneToken == sceneToken)
			{
				fogEnvironment.Write(original);
			}
		}
	}

	public static FogValues Calculate(FogValues value, string mode)
	{
		if (!value.Enabled)
		{
			return value;
		}
		if (mode == "DoubleDistance")
		{
			value.Start *= 2f;
			value.End *= 2f;
			value.Density *= 0.5f;
			value.FarClip = Math.Max(value.FarClip, (value.Mode == 1) ? (value.End + 1f) : (value.FarClip * 2f));
		}
		else if (mode == "Off")
		{
			value.Enabled = false;
			value.FarClip = Math.Max(value.FarClip, 1000f);
		}
		return value;
	}
}
public sealed class ModSettings
{
	public static readonly string[] EffectNames = new string[5] { "Bloom", "Vignette", "ColorGrading", "LensDistortion", "ChromaticAberration" };

	private readonly Dictionary<string, ConfigEntry<bool>> effects = new Dictionary<string, ConfigEntry<bool>>();

	public ConfigEntry<bool> Enabled { get; }

	public ConfigEntry<bool> EnableHotkey { get; }

	public ConfigEntry<string> Fog { get; }

	public ConfigEntry<float> Brightness { get; }

	public ModSettings(ConfigFile config)
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Expected O, but got Unknown
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Expected O, but got Unknown
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Expected O, but got Unknown
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fe: Expected O, but got Unknown
		bool saveOnConfigSet = config.SaveOnConfigSet;
		config.SaveOnConfigSet = false;
		try
		{
			ConfigEntry<string> val = config.Bind<string>("General", "Mode", "NoBloomAndColorGrading", new ConfigDescription("Legacy mode, migrated automatically.", (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" }));
			ConfigEntry<bool> val2 = config.Bind<bool>("General", "EnableCycleKey", true, new ConfigDescription("Legacy hotkey setting.", (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" }));
			Enabled = config.Bind<bool>("General", "ModEnabled", val.Value != "Original", "MOD設定の適用。OFFで元の表示に戻ります。各エフェクトの設定は保持されます。F8でも切り替えられます。");
			EnableHotkey = config.Bind<bool>("General", "EnableHotkey", val2.Value, "ショートカットによるMOD全体のON/OFFを有効にします。初期キーはF8です。");
			Brightness = config.Bind<float>("Brightness", "Multiplier", 2f, new ConfigDescription("明るさ倍率。1.0=補正なし、2.0=露出2倍。ColorGradingがOFFでも使用できます。F8でMODをOFFにすると補正も解除します。 / Brightness multiplier, independent of color grading.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			Fog = config.Bind<string>("Fog", "Distance", "DoubleDistance", new ConfigDescription("霧: Default=デフォルト / DoubleDistance=プレイヤーから霧までの距離2倍 / Off=霧オフ。MOD全体がONのときに適用します。", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Default", "DoubleDistance", "Off" }), Array.Empty<object>()));
			string[] effectNames = EffectNames;
			foreach (string text in effectNames)
			{
				effects.Add(text, config.Bind<bool>("Effects", text, LegacyAllows(val.Value, text), "ON: ゲーム本来の設定に従います。OFF: このエフェクトを無効化します。 / ON: follow game settings; OFF: suppress this effect."));
			}
			effectNames = new string[6] { "Grain", "MotionBlur", "AmbientOcclusion", "AutoExposure", "DepthOfField", "ScreenSpaceReflections" };
			foreach (string text2 in effectNames)
			{
				ConfigEntry<bool> val3 = config.Bind<bool>("Effects", text2, true, new ConfigDescription("Retired effect setting.", (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" }));
				config.Remove(((ConfigEntryBase)val3).Definition);
			}
			config.Remove(((ConfigEntryBase)val).Definition);
			config.Remove(((ConfigEntryBase)val2).Definition);
		}
		finally
		{
			config.SaveOnConfigSet = saveOnConfigSet;
		}
		config.Save();
	}

	public bool IsEffectEnabled(string name)
	{
		if (effects.TryGetValue(name, out var value))
		{
			return value.Value;
		}
		return true;
	}

	private static bool LegacyAllows(string mode, string name)
	{
		if (name == "ChromaticAberration")
		{
			return false;
		}
		if (mode == "NoPostProcessingEffects")
		{
			return false;
		}
		switch (name)
		{
		case "Bloom":
			if (mode != "NoBloom")
			{
				return mode != "NoBloomAndColorGrading";
			}
			return false;
		case "ColorGrading":
			if (mode != "NoColorGrading" && mode != "NoBloomAndColorGrading")
			{
				return mode != "NoColorGradingAndVignette";
			}
			return false;
		case "Vignette":
			if (mode != "NoVignette")
			{
				return mode != "NoColorGradingAndVignette";
			}
			return false;
		default:
			return true;
		}
	}
}
[BepInPlugin("local.repo.playervieweffects", "ShaderEdit", "1.0.1")]
[BepInProcess("REPO.exe")]
public sealed class Plugin : BaseUnityPlugin
{
	private struct SavedState
	{
		public bool Value;

		public bool Override;
	}

	private sealed class UnityFogEnvironment : IFogEnvironment
	{
		public Camera Camera { get; }

		public int SceneToken
		{
			get
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				Scene activeScene = SceneManager.GetActiveScene();
				return SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
			}
		}

		public bool IsValid => Object.op_Implicit((Object)(object)Camera);

		public UnityFogEnvironment(Camera camera)
		{
			Camera = camera;
		}

		public FogValues Read()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected I4, but got Unknown
			return new FogValues
			{
				Enabled = RenderSettings.fog,
				Mode = (int)RenderSettings.fogMode,
				Start = RenderSettings.fogStartDistance,
				End = RenderSettings.fogEndDistance,
				Density = RenderSettings.fogDensity,
				FarClip = Camera.farClipPlane
			};
		}

		public void Write(FogValues value)
		{
			RenderSettings.fog = value.Enabled;
			RenderSettings.fogStartDistance = value.Start;
			RenderSettings.fogEndDistance = value.End;
			RenderSettings.fogDensity = value.Density;
			Camera.farClipPlane = value.FarClip;
		}
	}

	private ModSettings settings;

	private ConfigEntry<KeyboardShortcut> toggleKey;

	private readonly Dictionary<PostProcessEffectSettings, SavedState> saved = new Dictionary<PostProcessEffectSettings, SavedState>();

	private readonly List<PostProcessEffectSettings> stale = new List<PostProcessEffectSettings>();

	private PostProcessVolume[] volumes = (PostProcessVolume[])(object)new PostProcessVolume[0];

	private readonly FogRenderOverride fogOverride = new FogRenderOverride();

	private UnityFogEnvironment fogEnvironment;

	private bool restoreRequested;

	private bool lastEnabled;

	private float nextScan;

	private float noticeUntil;

	private static Plugin instance;

	private Harmony harmony;

	private string lastFogDiagnostic;

	private void Awake()
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Expected O, but got Unknown
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Expected O, but got Unknown
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Expected O, but got Unknown
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Expected O, but got Unknown
		settings = new ModSettings(((BaseUnityPlugin)this).Config);
		bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
		ConfigEntry<KeyboardShortcut> val = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "CycleKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), new ConfigDescription("Legacy shortcut.", (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" }));
		toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "ToggleKey", val.Value, new ConfigDescription("Toggle between original rendering and configured mod effects. Edit this shortcut in the cfg file.", (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" }));
		((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val).Definition);
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
		((BaseUnityPlugin)this).Config.Save();
		((BaseUnityPlugin)this).Config.SettingChanged += OnSettingChanged;
		lastEnabled = settings.Enabled.Value;
		instance = this;
		harmony = new Harmony("local.repo.playervieweffects.fog-render-order");
		try
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(PostProcessLayer), "OnPreCull", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "BeforePostProcessSetup", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not install the fog preparation hook. Fog changes on post-processed cameras are skipped. " + ex));
		}
		try
		{
			MethodInfo methodInfo2 = AccessTools.Method(typeof(PostProcessManager), "UpdateSettings", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterVolumeBlend", (Type[])null)
			{
				priority = 0
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not install the independent brightness hook. " + ex2));
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"ShaderEdit 1.0.1 loaded. F8 toggles all configured adjustments.");
	}

	private void OnSettingChanged(object sender, SettingChangedEventArgs args)
	{
		restoreRequested = true;
		lastFogDiagnostic = null;
	}

	private void OnEnable()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Expected O, but got Unknown
		Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(BeforeCameraRender));
		Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(AfterCameraRender));
		nextScan = 0f;
	}

	private void Update()
	{
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		fogOverride.End();
		if (settings != null && settings.EnableHotkey.Value)
		{
			KeyboardShortcut value = toggleKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				settings.Enabled.Value = !settings.Enabled.Value;
			}
		}
	}

	private void LateUpdate()
	{
		if (settings == null)
		{
			return;
		}
		if (restoreRequested)
		{
			RestoreEffects();
			restoreRequested = false;
			nextScan = 0f;
		}
		if (lastEnabled != settings.Enabled.Value)
		{
			lastEnabled = settings.Enabled.Value;
			noticeUntil = Time.unscaledTime + 4f;
			((BaseUnityPlugin)this).Logger.LogInfo((object)(lastEnabled ? "Configured effects applied." : "Original rendering restored."));
		}
		if (!settings.Enabled.Value)
		{
			return;
		}
		if (Time.unscaledTime >= nextScan)
		{
			volumes = Object.FindObjectsByType<PostProcessVolume>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			nextScan = Time.unscaledTime + 1f;
		}
		stale.Clear();
		foreach (KeyValuePair<PostProcessEffectSettings, SavedState> item in saved)
		{
			if (!Object.op_Implicit((Object)(object)item.Key))
			{
				stale.Add(item.Key);
			}
		}
		foreach (PostProcessEffectSettings item2 in stale)
		{
			saved.Remove(item2);
		}
		PostProcessVolume[] array = volumes;
		foreach (PostProcessVolume val in array)
		{
			if (!Object.op_Implicit((Object)(object)val) || !((Behaviour)val).isActiveAndEnabled || val.weight <= 0f)
			{
				continue;
			}
			PostProcessProfile profile = val.profile;
			if (!Object.op_Implicit((Object)(object)profile))
			{
				continue;
			}
			foreach (PostProcessEffectSettings setting in profile.settings)
			{
				if (Object.op_Implicit((Object)(object)setting) && !settings.IsEffectEnabled(((object)setting).GetType().Name))
				{
					if (!saved.ContainsKey(setting))
					{
						saved.Add(setting, new SavedState
						{
							Value = ((ParameterOverride<bool>)(object)setting.enabled).value,
							Override = ((ParameterOverride)setting.enabled).overrideState
						});
					}
					((ParameterOverride)setting.enabled).overrideState = true;
					((ParameterOverride<bool>)(object)setting.enabled).value = false;
				}
			}
		}
	}

	private void BeforeCameraRender(Camera camera)
	{
		PostProcessLayer component = ((Component)camera).GetComponent<PostProcessLayer>();
		if (!Object.op_Implicit((Object)(object)component) || !((Behaviour)component).isActiveAndEnabled)
		{
			ApplyFogBeforeSetup(camera);
		}
	}

	private static void BeforePostProcessSetup(PostProcessLayer __instance)
	{
		if (Object.op_Implicit((Object)(object)instance) && ((Behaviour)instance).isActiveAndEnabled)
		{
			instance.ApplyFogBeforeSetup(((Component)__instance).GetComponent<Camera>());
		}
	}

	private static void AfterVolumeBlend(PostProcessLayer __0, Camera __1)
	{
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		Plugin plugin = instance;
		if (!Object.op_Implicit((Object)(object)plugin) || !((Behaviour)plugin).isActiveAndEnabled || plugin.settings == null || !plugin.settings.Enabled.Value || (Object)(object)__1 != (Object)(object)Camera.main || plugin.settings.Brightness.Value <= 1f)
		{
			return;
		}
		AutoExposure val = __0.GetSettings<AutoExposure>();
		if (Object.op_Implicit((Object)(object)val))
		{
			float value = plugin.settings.Brightness.Value;
			if (((ParameterOverride<bool>)(object)((PostProcessEffectSettings)val).enabled).value)
			{
				FloatParameter keyValue = val.keyValue;
				((ParameterOverride<float>)(object)keyValue).value = ((ParameterOverride<float>)(object)keyValue).value * value;
				return;
			}
			((ParameterOverride<bool>)(object)((PostProcessEffectSettings)val).enabled).value = true;
			((ParameterOverride<float>)(object)val.minLuminance).value = 0f;
			((ParameterOverride<float>)(object)val.maxLuminance).value = 0f;
			((ParameterOverride<float>)(object)val.keyValue).value = value;
			((ParameterOverride<EyeAdaptation>)(object)val.eyeAdaptation).value = (EyeAdaptation)1;
		}
	}

	private void ApplyFogBeforeSetup(Camera camera)
	{
		if (Object.op_Implicit((Object)(object)camera) && settings != null && settings.Enabled.Value && !(settings.Fog.Value == "Default") && !((Object)(object)camera != (Object)(object)Camera.main))
		{
			if (fogEnvironment == null || (Object)(object)fogEnvironment.Camera != (Object)(object)camera)
			{
				fogEnvironment = new UnityFogEnvironment(camera);
				lastFogDiagnostic = null;
			}
			FogValues fogValues = fogEnvironment.Read();
			fogOverride.Begin(fogEnvironment, settings.Fog.Value);
			if (lastFogDiagnostic != settings.Fog.Value)
			{
				FogValues fogValues2 = fogEnvironment.Read();
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Fog {settings.Fog.Value} prepared before post-processing: start/end {fogValues.Start}/{fogValues.End} -> {fogValues2.Start}/{fogValues2.End}, fog {fogValues.Enabled} -> {fogValues2.Enabled}, far clip {fogValues.FarClip} -> {fogValues2.FarClip}.");
				lastFogDiagnostic = settings.Fog.Value;
			}
		}
	}

	private void AfterCameraRender(Camera camera)
	{
		if (fogEnvironment != null && (Object)(object)fogEnvironment.Camera == (Object)(object)camera)
		{
			fogOverride.End();
		}
	}

	private void RestoreEffects()
	{
		foreach (KeyValuePair<PostProcessEffectSettings, SavedState> item in saved)
		{
			if (Object.op_Implicit((Object)(object)item.Key))
			{
				((ParameterOverride<bool>)(object)item.Key.enabled).value = item.Value.Value;
				((ParameterOverride)item.Key.enabled).overrideState = item.Value.Override;
			}
		}
		saved.Clear();
	}

	private void OnGUI()
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		if (settings != null && Time.unscaledTime < noticeUntil)
		{
			GUI.Box(new Rect(20f, 20f, 480f, 38f), "ShaderEdit: " + (settings.Enabled.Value ? "MOD settings applied" : "Original"));
		}
	}

	private void OnDisable()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Expected O, but got Unknown
		Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(BeforeCameraRender));
		Camera.onPostRender = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(AfterCameraRender));
		fogOverride.End();
		RestoreEffects();
	}

	private void OnDestroy()
	{
		((BaseUnityPlugin)this).Config.SettingChanged -= OnSettingChanged;
		OnDisable();
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		if ((Object)(object)instance == (Object)(object)this)
		{
			instance = null;
		}
	}
}

modules/Snow.dll

Decompiled a week ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Omniscye")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Snow")]
[assembly: AssemblyTitle("Snow")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 Omniscye.SnowEverywhere
{
	[BepInPlugin("Omniscye.SnowEverywhere", "SnowEverywhere", "1.4.1")]
	public class SnowEverywhere : BaseUnityPlugin
	{
		private sealed class SnowController : MonoBehaviour
		{
			internal struct Settings
			{
				public bool Enabled;

				public float FlakesPerSecond;

				public float FallSpeed;

				public float FlakeSize;

				public float WindX;

				public float WindZ;

				public float SpawnBoxHalfExtent;

				public int MaxParticles;

				public bool StickToCamera;

				public bool UseUnscaledTime;
			}

			private ParticleSystem _ps = null;

			private EmissionModule _emission;

			private MainModule _main;

			private ShapeModule _shape;

			private VelocityOverLifetimeModule _vel;

			private ParticleSystemRenderer _rend = null;

			private Camera? _cam;

			private Settings _settings;

			private float _targetLifetime;

			private bool _manualSimulateFallback = false;

			public void Initialize(Settings s, Texture2D? customTexture)
			{
				_settings = s;
				BuildParticleSystem(customTexture);
				RefreshForScene();
				if (s.Enabled)
				{
					Enable();
				}
				else
				{
					Disable();
				}
			}

			public void RefreshForScene()
			{
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0092: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				_cam = Camera.main;
				if ((Object)(object)_cam == (Object)null)
				{
					Camera[] array = Object.FindObjectsOfType<Camera>();
					Camera[] array2 = array;
					foreach (Camera val in array2)
					{
						if ((Object)(object)val != (Object)null && ((Behaviour)val).enabled)
						{
							_cam = val;
							break;
						}
					}
				}
				if (_settings.StickToCamera && (Object)(object)_cam != (Object)null)
				{
					Vector3 position = ((Component)_cam).transform.position;
					position.y += 15f;
					((Component)this).transform.position = position;
				}
			}

			private void LateUpdate()
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				if (_settings.StickToCamera && (Object)(object)_cam != (Object)null)
				{
					Vector3 position = ((Component)_cam).transform.position;
					position.y += 15f;
					((Component)this).transform.position = position;
				}
				if (!_settings.Enabled || (Object)(object)_ps == (Object)null)
				{
					return;
				}
				if (_manualSimulateFallback)
				{
					float num = (_settings.UseUnscaledTime ? Time.unscaledDeltaTime : Time.deltaTime);
					if (_ps.isPlaying)
					{
						_ps.Pause(false);
					}
					_ps.Simulate(num, false, false, false);
				}
				else if (_ps.isStopped || _ps.isPaused)
				{
					_ps.Play();
				}
			}

			private void BuildParticleSystem(Texture2D? customTexture)
			{
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Expected O, but got Unknown
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_0131: Unknown result type (might be due to invalid IL or missing references)
				//IL_0136: Unknown result type (might be due to invalid IL or missing references)
				//IL_014e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0153: Unknown result type (might be due to invalid IL or missing references)
				//IL_016f: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0202: Unknown result type (might be due to invalid IL or missing references)
				//IL_0225: Unknown result type (might be due to invalid IL or missing references)
				//IL_0237: Unknown result type (might be due to invalid IL or missing references)
				//IL_023c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0288: Unknown result type (might be due to invalid IL or missing references)
				//IL_0299: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0319: Unknown result type (might be due to invalid IL or missing references)
				_ps = ((Component)this).gameObject.AddComponent<ParticleSystem>();
				_rend = ((Component)_ps).GetComponent<ParticleSystemRenderer>();
				_rend.alignment = (ParticleSystemRenderSpace)0;
				_rend.renderMode = (ParticleSystemRenderMode)0;
				Shader val = Shader.Find("Particles/Standard Unlit");
				if ((Object)(object)val == (Object)null)
				{
					val = Shader.Find("Legacy Shaders/Particles/Alpha Blended");
				}
				Material val2 = new Material(val);
				((Object)val2).name = "Snow_Menu_Material";
				val2.color = Color.white;
				if ((Object)(object)customTexture != (Object)null)
				{
					val2.mainTexture = (Texture)(object)customTexture;
				}
				val2.SetFloat("_Mode", 2f);
				val2.EnableKeyword("_ALPHABLEND_ON");
				val2.DisableKeyword("_ALPHATEST_ON");
				val2.DisableKeyword("_ALPHAPREMULTIPLY_ON");
				val2.SetInt("_ZWrite", 0);
				val2.SetInt("_SrcBlend", 5);
				val2.SetInt("_DstBlend", 10);
				val2.renderQueue = 3000;
				((Renderer)_rend).material = val2;
				((Renderer)_rend).sortingOrder = 32767;
				TrySetAlwaysSimulate(_ps, _rend);
				_main = _ps.main;
				((MainModule)(ref _main)).loop = true;
				((MainModule)(ref _main)).startColor = MinMaxGradient.op_Implicit(Color.white);
				((MainModule)(ref _main)).startSize = MinMaxCurve.op_Implicit(_settings.FlakeSize);
				_targetLifetime = Mathf.Max(6f, 25f / Mathf.Max(0.05f, _settings.FallSpeed));
				((MainModule)(ref _main)).startLifetime = MinMaxCurve.op_Implicit(_targetLifetime);
				((MainModule)(ref _main)).startSpeed = MinMaxCurve.op_Implicit(0f);
				((MainModule)(ref _main)).maxParticles = _settings.MaxParticles;
				((MainModule)(ref _main)).simulationSpace = (ParticleSystemSimulationSpace)1;
				_emission = _ps.emission;
				((EmissionModule)(ref _emission)).enabled = true;
				((EmissionModule)(ref _emission)).rateOverTime = MinMaxCurve.op_Implicit(_settings.FlakesPerSecond);
				_shape = _ps.shape;
				((ShapeModule)(ref _shape)).enabled = true;
				((ShapeModule)(ref _shape)).shapeType = (ParticleSystemShapeType)5;
				((ShapeModule)(ref _shape)).scale = new Vector3(_settings.SpawnBoxHalfExtent * 2f, 2f, _settings.SpawnBoxHalfExtent * 2f);
				((ShapeModule)(ref _shape)).position = Vector3.zero;
				_vel = _ps.velocityOverLifetime;
				((VelocityOverLifetimeModule)(ref _vel)).enabled = true;
				((VelocityOverLifetimeModule)(ref _vel)).space = (ParticleSystemSimulationSpace)1;
				((VelocityOverLifetimeModule)(ref _vel)).x = MinMaxCurve.op_Implicit(_settings.WindX);
				((VelocityOverLifetimeModule)(ref _vel)).y = MinMaxCurve.op_Implicit(0f - _settings.FallSpeed);
				((VelocityOverLifetimeModule)(ref _vel)).z = MinMaxCurve.op_Implicit(_settings.WindZ);
				_ps.Play();
			}

			private void TrySetAlwaysSimulate(ParticleSystem ps, ParticleSystemRenderer rend)
			{
				if ((Object)(object)rend != (Object)null)
				{
					((Renderer)rend).allowOcclusionWhenDynamic = false;
				}
				PropertyInfo property = typeof(ParticleSystem).GetProperty("cullingMode", BindingFlags.Instance | BindingFlags.Public);
				if (property != null)
				{
					Type propertyType = property.PropertyType;
					object value;
					try
					{
						value = Enum.Parse(propertyType, "AlwaysSimulate");
					}
					catch
					{
						value = Enum.ToObject(propertyType, 2);
					}
					try
					{
						property.SetValue(ps, value, null);
						_manualSimulateFallback = false;
						return;
					}
					catch
					{
					}
				}
				_manualSimulateFallback = true;
			}

			public void Enable()
			{
				_settings.Enabled = true;
				if ((Object)(object)_ps == (Object)null)
				{
					return;
				}
				if (_manualSimulateFallback)
				{
					if (_ps.isPlaying)
					{
						_ps.Pause(false);
					}
				}
				else
				{
					_ps.Play();
				}
			}

			public void Disable()
			{
				_settings.Enabled = false;
				if (!((Object)(object)_ps == (Object)null))
				{
					_ps.Pause();
				}
			}

			public void SetEmissionRate(float r)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				_settings.FlakesPerSecond = Mathf.Max(0f, r);
				((EmissionModule)(ref _emission)).rateOverTime = MinMaxCurve.op_Implicit(_settings.FlakesPerSecond);
				RecalculateRecommendedMaxParticles();
			}

			public void SetFallSpeed(float s)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				_settings.FallSpeed = Mathf.Max(0.01f, s);
				((VelocityOverLifetimeModule)(ref _vel)).y = MinMaxCurve.op_Implicit(0f - _settings.FallSpeed);
				_targetLifetime = Mathf.Max(6f, 25f / _settings.FallSpeed);
				((MainModule)(ref _main)).startLifetime = MinMaxCurve.op_Implicit(_targetLifetime);
				RecalculateRecommendedMaxParticles();
			}

			public void SetFlakeSize(float s)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				_settings.FlakeSize = Mathf.Clamp(s, 0.005f, 0.25f);
				((MainModule)(ref _main)).startSize = MinMaxCurve.op_Implicit(_settings.FlakeSize);
			}

			public void SetWind(float x, float z)
			{
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				_settings.WindX = x;
				_settings.WindZ = z;
				((VelocityOverLifetimeModule)(ref _vel)).x = MinMaxCurve.op_Implicit(x);
				((VelocityOverLifetimeModule)(ref _vel)).z = MinMaxCurve.op_Implicit(z);
			}

			public void SetSpawnBox(float halfExtent)
			{
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				_settings.SpawnBoxHalfExtent = Mathf.Clamp(halfExtent, 5f, 200f);
				((ShapeModule)(ref _shape)).scale = new Vector3(_settings.SpawnBoxHalfExtent * 2f, 2f, _settings.SpawnBoxHalfExtent * 2f);
			}

			public void SetMaxParticles(int max)
			{
				_settings.MaxParticles = Mathf.Clamp(max, 200, 50000);
				((MainModule)(ref _main)).maxParticles = _settings.MaxParticles;
			}

			public void SetStickToCamera(bool stick)
			{
				_settings.StickToCamera = stick;
			}

			public void SetUseUnscaledTime(bool useUnscaled)
			{
				_settings.UseUnscaledTime = useUnscaled;
			}

			private void RecalculateRecommendedMaxParticles()
			{
				int num = Mathf.CeilToInt(_settings.FlakesPerSecond * _targetLifetime * 1.2f);
				if (num > _settings.MaxParticles)
				{
					_settings.MaxParticles = num;
					((MainModule)(ref _main)).maxParticles = _settings.MaxParticles;
				}
			}
		}

		public const string PluginGuid = "Omniscye.SnowEverywhere";

		public const string PluginName = "SnowEverywhere";

		public const string PluginVersion = "1.4.1";

		private ConfigEntry<bool> _enabled = null;

		private ConfigEntry<float> _flakesPerSecond = null;

		private ConfigEntry<float> _fallSpeed = null;

		private ConfigEntry<float> _flakeSize = null;

		private ConfigEntry<float> _windX = null;

		private ConfigEntry<float> _windZ = null;

		private ConfigEntry<float> _spawnBoxHalfExtent = null;

		private ConfigEntry<int> _maxParticles = null;

		private ConfigEntry<bool> _stickToCamera = null;

		private ConfigEntry<bool> _useUnscaledTime = null;

		private ConfigEntry<bool> _onlyInMenuLobby = null;

		private ConfigEntry<bool> _useCustomTexture = null;

		private ConfigEntry<string> _customTextureName = null;

		private SnowController? _controller;

		private float _filterPollTimer;

		private bool _lastAllowed;

		private bool _loggedSemiFuncNotReady;

		private Texture2D? _snowTex;

		internal static SnowEverywhere Instance { get; private set; }

		internal static ManualLogSource Logger => Instance._logger;

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		internal Harmony? Harmony { get; set; }

		private void Awake()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_004a: Expected O, but got Unknown
			Instance = this;
			((Component)this).transform.parent = null;
			((Object)this).hideFlags = (HideFlags)61;
			BindConfig();
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
			TryLoadSnowTexture();
			EnsureController();
			SceneManager.sceneLoaded += OnSceneLoaded;
			ApplyMenuFilter(initial: true);
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} loaded — menu/lobby-gated snowfall with custom texture support.");
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			_filterPollTimer -= (_useUnscaledTime.Value ? Time.unscaledDeltaTime : Time.deltaTime);
			if (_filterPollTimer <= 0f)
			{
				_filterPollTimer = 0.5f;
				ApplyMenuFilter(initial: false);
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if ((Object)(object)_controller == (Object)null)
			{
				EnsureController();
			}
			_controller.RefreshForScene();
			ApplyMenuFilter(initial: true);
			Logger.LogDebug((object)("Snow refreshed for scene '" + ((Scene)(ref scene)).name + "'."));
		}

		private void BindConfig()
		{
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master toggle for snowfall.");
			_flakesPerSecond = ((BaseUnityPlugin)this).Config.Bind<float>("Snow", "FlakesPerSecond", 150f, "Emission rate (flakes/second).");
			_fallSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Snow", "FallSpeed", 0.8f, "Downward speed in m/s. Lower = slower.");
			_flakeSize = ((BaseUnityPlugin)this).Config.Bind<float>("Snow", "FlakeSize", 0.06f, "Base particle size in meters.");
			_windX = ((BaseUnityPlugin)this).Config.Bind<float>("Snow", "WindX", 0.15f, "Horizontal drift X.");
			_windZ = ((BaseUnityPlugin)this).Config.Bind<float>("Snow", "WindZ", -0.05f, "Horizontal drift Z.");
			_spawnBoxHalfExtent = ((BaseUnityPlugin)this).Config.Bind<float>("Snow", "SpawnBoxHalfExtent", 25f, "Half-extent of spawn box (XZ).");
			_maxParticles = ((BaseUnityPlugin)this).Config.Bind<int>("Performance", "MaxParticles", 8000, "Max live particles (raise if rate×lifetime is high).");
			_stickToCamera = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "StickToCamera", true, "Anchor emitter to active camera.");
			_useUnscaledTime = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseUnscaledTime", true, "Use unscaled time so menus/slowmo don’t freeze snow.");
			_onlyInMenuLobby = ((BaseUnityPlugin)this).Config.Bind<bool>("Scenes", "OnlyInMenuLobby", true, "If true, snow runs only when SemiFunc.MenuLevel() is true.");
			_useCustomTexture = ((BaseUnityPlugin)this).Config.Bind<bool>("Visual", "UseCustomTexture", true, "If true, tries to load a PNG beside the DLL and use it for flake texture.");
			_customTextureName = ((BaseUnityPlugin)this).Config.Bind<string>("Visual", "CustomTextureName", "snow.png", "File name of the texture next to the plugin DLL.");
		}

		private void EnsureController()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			if (!((Object)(object)_controller != (Object)null))
			{
				GameObject val = new GameObject("SnowEverywhere_Controller");
				Object.DontDestroyOnLoad((Object)(object)val);
				((Object)val).hideFlags = (HideFlags)61;
				_controller = val.AddComponent<SnowController>();
				_controller.Initialize(new SnowController.Settings
				{
					Enabled = _enabled.Value,
					FlakesPerSecond = _flakesPerSecond.Value,
					FallSpeed = _fallSpeed.Value,
					FlakeSize = _flakeSize.Value,
					WindX = _windX.Value,
					WindZ = _windZ.Value,
					SpawnBoxHalfExtent = _spawnBoxHalfExtent.Value,
					MaxParticles = _maxParticles.Value,
					StickToCamera = _stickToCamera.Value,
					UseUnscaledTime = _useUnscaledTime.Value
				}, _snowTex);
				_enabled.SettingChanged += delegate
				{
					ApplyMenuFilter(initial: false);
				};
				_flakesPerSecond.SettingChanged += delegate
				{
					_controller.SetEmissionRate(_flakesPerSecond.Value);
				};
				_fallSpeed.SettingChanged += delegate
				{
					_controller.SetFallSpeed(_fallSpeed.Value);
				};
				_flakeSize.SettingChanged += delegate
				{
					_controller.SetFlakeSize(_flakeSize.Value);
				};
				_windX.SettingChanged += delegate
				{
					_controller.SetWind(_windX.Value, _windZ.Value);
				};
				_windZ.SettingChanged += delegate
				{
					_controller.SetWind(_windX.Value, _windZ.Value);
				};
				_spawnBoxHalfExtent.SettingChanged += delegate
				{
					_controller.SetSpawnBox(_spawnBoxHalfExtent.Value);
				};
				_maxParticles.SettingChanged += delegate
				{
					_controller.SetMaxParticles(_maxParticles.Value);
				};
				_stickToCamera.SettingChanged += delegate
				{
					_controller.SetStickToCamera(_stickToCamera.Value);
				};
				_useUnscaledTime.SettingChanged += delegate
				{
					_controller.SetUseUnscaledTime(_useUnscaledTime.Value);
				};
			}
		}

		private void ApplyMenuFilter(bool initial)
		{
			if ((Object)(object)_controller == (Object)null)
			{
				return;
			}
			if (!_enabled.Value)
			{
				_controller.Disable();
				return;
			}
			bool flag = true;
			if (_onlyInMenuLobby.Value)
			{
				flag = IsMenuOrLobbyActiveSafe();
			}
			if (initial || flag != _lastAllowed)
			{
				_lastAllowed = flag;
				if (flag)
				{
					_controller.Enable();
					Logger.LogDebug((object)"Snow: ENABLE (menu level detected).");
				}
				else
				{
					_controller.Disable();
					Logger.LogDebug((object)"Snow: DISABLE (not a menu level).");
				}
			}
		}

		private bool IsMenuOrLobbyActiveSafe()
		{
			try
			{
				return SemiFunc.MenuLevel();
			}
			catch (Exception ex)
			{
				if (!_loggedSemiFuncNotReady)
				{
					_loggedSemiFuncNotReady = true;
					Logger.LogDebug((object)("Snow: SemiFunc.MenuLevel() not ready yet (" + ex.GetType().Name + "). Will retry."));
				}
				return false;
			}
		}

		private void TryLoadSnowTexture()
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			_snowTex = null;
			if (!_useCustomTexture.Value)
			{
				return;
			}
			try
			{
				string path = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? "";
				string text = Path.Combine(path, _customTextureName.Value);
				if (!File.Exists(text))
				{
					Logger.LogDebug((object)("Snow: custom texture not found at '" + text + "'. Using default white material."));
					return;
				}
				byte[] array = File.ReadAllBytes(text);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false, false);
				if (!ImageConversion.LoadImage(val, array, false))
				{
					Logger.LogWarning((object)"Snow: failed to load snow texture (LoadImage returned false).");
					Object.Destroy((Object)(object)val);
					return;
				}
				((Object)val).name = "Snow_Menu_Texture";
				((Texture)val).wrapMode = (TextureWrapMode)1;
				((Texture)val).filterMode = (FilterMode)1;
				_snowTex = val;
				Logger.LogInfo((object)$"Snow: loaded custom flake texture '{_customTextureName.Value}' ({((Texture)val).width}x{((Texture)val).height}).");
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Snow: error loading custom texture: " + ex.GetType().Name + ": " + ex.Message));
				_snowTex = null;
			}
		}
	}
}