Decompiled source of Climber RealBoy v2.0.2

ClimberBadGuy.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DarkMachine.UI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ClimberBadGuy
{
	[BepInPlugin("climber.realboy.badguy.whiteknuckle.mod", "Climber (Real Boy) - Bad Guy Toggle", "2.0.2")]
	public class ClimberBadGuyPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "climber.realboy.badguy.whiteknuckle.mod";

		public const string PluginName = "Climber (Real Boy) - Bad Guy Toggle";

		public const string PluginVersion = "2.0.2";

		private const string TargetCosmeticId = "climber-real boy";

		private const string TargetSpriteName = "HND_B1A2";

		private const string CosmeticFolderName = "Climber_RealBoy";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> BadGuyEnabled;

		private static string pluginDir;

		private static SwapSprite targetSwap;

		private static Sprite originalSprite;

		private static Sprite badGuySprite;

		private static bool ready;

		private static UI_CosmeticInfoPanel activePanel;

		private static GameObject toggleRow;

		private static SubmitSlider toggleSlider;

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

		private static string StructuredContentDir => Path.Combine(pluginDir, "CosmeticContent", "Climber_RealBoy");

		private void Awake()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			pluginDir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			BadGuyEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Cosmetic", "BadGuyMode", false, "When enabled, the HND_B1A2 hand frame of the Climber (Real Boy) cosmetic is replaced with the bad guy photo.");
			InstallCosmeticContent();
			new Harmony("climber.realboy.badguy.whiteknuckle.mod").PatchAll(Assembly.GetExecutingAssembly());
			Log.LogInfo((object)"Climber Bad Guy toggle loaded.");
		}

		private static void ReportOnce(string where, Exception e)
		{
			if (reportedFailures.Add(where))
			{
				Log.LogError((object)(where + " failed (further occurrences are suppressed): " + e));
			}
		}

		private static List<KeyValuePair<string, string>> EnumerateBundledFiles()
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			string structuredContentDir = StructuredContentDir;
			string[] files;
			if (Directory.Exists(structuredContentDir))
			{
				files = Directory.GetFiles(structuredContentDir, "*", SearchOption.AllDirectories);
				foreach (string text in files)
				{
					list.Add(new KeyValuePair<string, string>(text, text.Substring(structuredContentDir.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)));
				}
				return list;
			}
			files = Directory.GetFiles(pluginDir);
			foreach (string text2 in files)
			{
				string fileName = Path.GetFileName(text2);
				switch (fileName)
				{
				case "cosmetic-handitem-settings.json":
				case "card-background.png":
				case "card-foreground.png":
					list.Add(new KeyValuePair<string, string>(text2, fileName));
					continue;
				}
				if (fileName.StartsWith("interact-", StringComparison.Ordinal) && fileName.EndsWith(".png", StringComparison.Ordinal))
				{
					list.Add(new KeyValuePair<string, string>(text2, Path.Combine("Interacts", fileName)));
				}
				else if ((fileName.StartsWith("HND_", StringComparison.Ordinal) || fileName.StartsWith("MF", StringComparison.Ordinal) || fileName.StartsWith("PHA", StringComparison.Ordinal)) && fileName.EndsWith(".png", StringComparison.Ordinal))
				{
					list.Add(new KeyValuePair<string, string>(text2, Path.Combine("Sprites", fileName)));
				}
			}
			return list;
		}

		private static string FindBundledFile(string relativePath)
		{
			foreach (KeyValuePair<string, string> item in EnumerateBundledFiles())
			{
				if (string.Equals(item.Value, relativePath, StringComparison.OrdinalIgnoreCase))
				{
					return item.Key;
				}
			}
			return null;
		}

		private static string FindBadGuyImage()
		{
			string[] array = new string[2]
			{
				Path.Combine(pluginDir, "Assets", "BadGuy.png"),
				Path.Combine(pluginDir, "BadGuy.png")
			};
			foreach (string text in array)
			{
				if (File.Exists(text))
				{
					return text;
				}
			}
			return null;
		}

		private static void InstallCosmeticContent()
		{
			try
			{
				List<KeyValuePair<string, string>> list = EnumerateBundledFiles();
				if (!list.Exists((KeyValuePair<string, string> f) => f.Value == "cosmetic-handitem-settings.json"))
				{
					Log.LogWarning((object)("Bundled cosmetic content (cosmetic-handitem-settings.json) not found in " + pluginDir + " - nothing to install."));
					return;
				}
				string text = Path.Combine(Paths.GameRootPath, "White Knuckle_Data", "Mods", "Cosmetics", "Hands", "Climber_RealBoy");
				int num = 0;
				foreach (KeyValuePair<string, string> item in list)
				{
					try
					{
						string text2 = Path.Combine(text, item.Value);
						Directory.CreateDirectory(Path.GetDirectoryName(text2));
						File.Copy(item.Key, text2, overwrite: true);
					}
					catch (Exception ex)
					{
						num++;
						Log.LogWarning((object)("Could not copy " + item.Key + ": " + ex.Message));
					}
				}
				Log.LogInfo((object)("Installed Climber (Real Boy) cosmetic (" + list.Count + " files) to " + text + ((num > 0) ? (" - " + num + " file(s) failed") : "")));
			}
			catch (Exception ex2)
			{
				Log.LogError((object)("Failed to install cosmetic content: " + ex2));
			}
		}

		internal static void VerifyAndRepairCosmetic()
		{
			try
			{
				Cosmetic_HandItem val = Traverse.Create(typeof(CL_CosmeticManager)).Field("cosmeticHands").GetValue<List<Cosmetic_HandItem>>()?.Find((Cosmetic_HandItem c) => c?.cosmeticData?.id == "climber-real boy");
				if ((Object)(object)val == (Object)null)
				{
					Log.LogWarning((object)"The game did not load the Climber (Real Boy) cosmetic - check that White Knuckle_Data/Mods/Cosmetics/Hands/Climber_RealBoy exists.");
					return;
				}
				int num = 0;
				int num2 = 0;
				foreach (SwapSprite swapSprite in val.cosmeticData.swapSprites)
				{
					if (swapSprite.replacementSprites == null)
					{
						swapSprite.replacementSprites = new List<Sprite>();
					}
					if (swapSprite.replacementSprites.Count == 0)
					{
						foreach (string replacementSpriteName in swapSprite.replacementSpriteNames)
						{
							string text = FindBundledFile(Path.Combine("Sprites", replacementSpriteName + ".png"));
							Sprite val2 = ((text != null) ? RuntimeSpriteImporter.LoadSpriteFromFile(text, 100f, (FilterMode)0, false, false) : null);
							if ((Object)(object)val2 != (Object)null)
							{
								((Object)val2).name = replacementSpriteName;
								swapSprite.replacementSprites.Add(val2);
								num++;
							}
						}
					}
					if (swapSprite.replacementSprites.Count > 0)
					{
						num2++;
					}
				}
				foreach (InteractSwap interactSwap in val.cosmeticData.interactSwaps)
				{
					if (!((Object)(object)interactSwap.replacementSprite != (Object)null))
					{
						string text2 = FindBundledFile(Path.Combine("Interacts", interactSwap.replacementSpriteName + ".png"));
						if (text2 != null)
						{
							interactSwap.replacementSprite = RuntimeSpriteImporter.LoadSpriteFromFile(text2, 100f, (FilterMode)0, false, false);
							num++;
						}
					}
				}
				if ((Object)(object)((Cosmetic_Base)val).cosmeticInfo.cardBackground == (Object)null)
				{
					string text3 = FindBundledFile("card-background.png");
					if (text3 != null)
					{
						((Cosmetic_Base)val).cosmeticInfo.cardBackground = RuntimeSpriteImporter.LoadSpriteFromFile(text3, 100f, (FilterMode)1, true, false);
						num++;
					}
				}
				if ((Object)(object)((Cosmetic_Base)val).cosmeticInfo.cardForeground == (Object)null)
				{
					string text4 = FindBundledFile("card-foreground.png");
					if (text4 != null)
					{
						((Cosmetic_Base)val).cosmeticInfo.cardForeground = RuntimeSpriteImporter.LoadSpriteFromFile(text4, 100f, (FilterMode)1, true, false);
						num++;
					}
				}
				Log.LogInfo((object)("Climber (Real Boy) cosmetic ready: " + num2 + "/" + val.cosmeticData.swapSprites.Count + " swap entries have sprites" + ((num > 0) ? (" (" + num + " restored from the bundled copy because the game failed to load them)") : "")));
			}
			catch (Exception e)
			{
				ReportOnce("VerifyAndRepairCosmetic", e);
			}
		}

		internal static void EnsureReady(Cosmetic_HandItem instance)
		{
			if (ready)
			{
				return;
			}
			try
			{
				if (instance?.cosmeticData?.id != "climber-real boy" || instance.cosmeticData.swapSprites == null)
				{
					return;
				}
				SwapSprite val = instance.cosmeticData.swapSprites.Find((SwapSprite s) => s.spriteName == "HND_B1A2");
				if (val?.replacementSprites != null && val.replacementSprites.Count != 0)
				{
					targetSwap = val;
					originalSprite = val.replacementSprites[0];
					ready = true;
					try
					{
						badGuySprite = LoadBadGuySprite(originalSprite);
					}
					catch (Exception ex)
					{
						badGuySprite = null;
						Log.LogWarning((object)("Bad guy image could not be loaded; the toggle is disabled. " + ex.Message));
					}
					ApplyState();
				}
			}
			catch (Exception e)
			{
				ready = true;
				ReportOnce("EnsureReady", e);
			}
		}

		private static void ApplyState()
		{
			if (targetSwap != null)
			{
				targetSwap.replacementSprites[0] = ((BadGuyEnabled.Value && (Object)(object)badGuySprite != (Object)null) ? badGuySprite : originalSprite);
			}
		}

		private static Sprite LoadBadGuySprite(Sprite reference)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			//IL_00a6: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = File.ReadAllBytes(FindBadGuyImage() ?? throw new FileNotFoundException("BadGuy.png not found next to the plugin (" + pluginDir + ")"));
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			(Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[3]
			{
				typeof(Texture2D),
				typeof(byte[]),
				typeof(bool)
			}))?.Invoke(null, new object[3] { val, array, false });
			((Texture)val).filterMode = (FilterMode)0;
			Vector2 pivot = reference.pivot;
			Rect rect = reference.rect;
			Vector2 val2 = pivot / ((Rect)(ref rect)).size;
			float pixelsPerUnit = reference.pixelsPerUnit;
			float num = ((Texture)val).width;
			rect = reference.rect;
			float num2 = pixelsPerUnit * (num / ((Rect)(ref rect)).width);
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), val2, num2, 0u, (SpriteMeshType)0);
		}

		internal static void OnInfoPanelUpdated(UI_CosmeticInfoPanel panel)
		{
			try
			{
				Cosmetic_Base selectedCosmetic = panel.selectedCosmetic;
				Cosmetic_HandItem val = (Cosmetic_HandItem)(object)((selectedCosmetic is Cosmetic_HandItem) ? selectedCosmetic : null);
				int num;
				if ((Object)(object)val != (Object)null)
				{
					num = ((val.cosmeticData.id == "climber-real boy") ? 1 : 0);
					if (num != 0)
					{
						EnsureReady(val);
					}
				}
				else
				{
					num = 0;
				}
				if (num == 0 || (Object)(object)badGuySprite == (Object)null)
				{
					if ((Object)(object)toggleRow != (Object)null)
					{
						toggleRow.SetActive(false);
					}
				}
				else
				{
					activePanel = panel;
					EnsureToggleUi(panel);
					panel.settingRoot.SetActive(true);
					toggleRow.SetActive(true);
					toggleSlider.SetValueWithoutNotify(BadGuyEnabled.Value ? 1f : 0f);
				}
			}
			catch (Exception e)
			{
				ReportOnce("OnInfoPanelUpdated", e);
			}
		}

		private static void EnsureToggleUi(UI_CosmeticInfoPanel panel)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			if (!((Object)(object)toggleRow != (Object)null))
			{
				GameObject gameObject = ((Component)((Component)panel.accessorySlider).transform.parent).gameObject;
				toggleRow = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent);
				((Object)toggleRow).name = "BadGuyToggleRow";
				toggleSlider = toggleRow.GetComponentInChildren<SubmitSlider>(true);
				toggleSlider.onValueChanged = new SliderEvent();
				toggleSlider.minValue = 0f;
				toggleSlider.maxValue = 1f;
				toggleSlider.wholeNumbers = true;
				toggleSlider.stepAmount = 1f;
				((UnityEvent<float>)(object)toggleSlider.onValueChanged).AddListener((UnityAction<float>)OnToggleChanged);
				TMP_Text componentInChildren = toggleRow.GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.text = "Bad guy";
				}
			}
		}

		private static void OnToggleChanged(float value)
		{
			try
			{
				BadGuyEnabled.Value = value >= 0.5f;
				ApplyState();
				activePanel.UpdateSprite();
			}
			catch (Exception e)
			{
				ReportOnce("OnToggleChanged", e);
			}
		}
	}
	[HarmonyPatch(typeof(Cosmetic_HandItem), "SwapUISprite")]
	internal static class SwapUISpritePatch
	{
		private static void Prefix(Cosmetic_HandItem __instance, Image image)
		{
			ClimberBadGuyPlugin.EnsureReady(__instance);
		}
	}
	[HarmonyPatch(typeof(Cosmetic_HandItem), "SpriteSwap")]
	internal static class SpriteSwapPatch
	{
		private static void Prefix(Cosmetic_HandItem __instance)
		{
			ClimberBadGuyPlugin.EnsureReady(__instance);
		}
	}
	[HarmonyPatch(typeof(CL_CosmeticManager), "Initialize")]
	internal static class CosmeticManagerInitPatch
	{
		private static bool verified;

		private static void Postfix()
		{
			if (!verified)
			{
				verified = true;
				ClimberBadGuyPlugin.VerifyAndRepairCosmetic();
			}
		}
	}
	[HarmonyPatch(typeof(UI_CosmeticInfoPanel), "UpdateSprite")]
	internal static class UpdateSpritePatch
	{
		private static void Postfix(UI_CosmeticInfoPanel __instance)
		{
			ClimberBadGuyPlugin.OnInfoPanelUpdated(__instance);
		}
	}
}