Decompiled source of Custom HNR Icons v1.0.0

plugins/HNRCustomIcons.dll

Decompiled a day 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 System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HNRCustomIcons")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("HNRCustomIcons")]
[assembly: AssemblyTitle("HNRCustomIcons")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 HNRCustomIcons
{
	[BepInPlugin("com.custom.hnr.customicons", "HNR Custom Icons", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class HNRCustomIconsPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.custom.hnr.customicons";

		public const string PluginName = "HNR Custom Icons";

		public const string PluginVersion = "1.0.0";

		public const string HnrGuid = "eduardo.wk.herobrinenotremoved";

		internal static ManualLogSource Log;

		internal static string IconsDir;

		internal static ConfigEntry<KeyboardShortcut> ReloadShortcut;

		private static readonly Dictionary<string, Texture2D> OverrideCache = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> LoggedOverrides = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0058: 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
			Log = ((BaseUnityPlugin)this).Logger;
			IconsDir = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? Paths.PluginPath, "icons");
			Directory.CreateDirectory(IconsDir);
			ReloadShortcut = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("HotReload", "ReloadIconsKey", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Press this key in-game to clear cached icon overrides and reload PNGs from disk.");
			_harmony = new Harmony("com.custom.hnr.customicons");
			PatchMinerSalvageIcon(_harmony);
			Log.LogInfo((object)("HNR Custom Icons 1.0.0 initialized. Drop custom PNGs into: " + IconsDir));
		}

		private void Update()
		{
			//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)
			if (ReloadShortcut != null)
			{
				KeyboardShortcut value = ReloadShortcut.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					ClearCache();
					Log.LogInfo((object)"[HNRCustomIcons] Icon override cache cleared; PNGs will reload on next icon lookup.");
				}
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			DestroyCachedTextures();
		}

		public static void ClearCache()
		{
			DestroyCachedTextures();
			OverrideCache.Clear();
			LoggedOverrides.Clear();
		}

		private static void DestroyCachedTextures()
		{
			foreach (KeyValuePair<string, Texture2D> item in OverrideCache)
			{
				if ((Object)(object)item.Value != (Object)null)
				{
					Object.Destroy((Object)(object)item.Value);
				}
			}
		}

		private static void PatchMinerSalvageIcon(Harmony harmony)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("MinerSalvage");
			if (type == null)
			{
				Log.LogWarning((object)"[HNRCustomIcons] Could not find type 'MinerSalvage'. Make sure HerobrineNotRemoved is installed.");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "Icon", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogWarning((object)"[HNRCustomIcons] Could not find method 'MinerSalvage.Icon'.");
				return;
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(HNRCustomIconsPlugin), "MinerSalvage_Icon_Prefix", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Log.LogInfo((object)"[HNRCustomIcons] Patched MinerSalvage.Icon.");
		}

		public static bool MinerSalvage_Icon_Prefix(object item, ref Texture2D __result)
		{
			if (item == null)
			{
				return true;
			}
			string prefabName = GetPrefabName(item);
			if (string.IsNullOrEmpty(prefabName))
			{
				return true;
			}
			if (OverrideCache.TryGetValue(prefabName, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					__result = value;
					return false;
				}
				return true;
			}
			Texture2D val = ResolveOverrideTexture(item, prefabName);
			OverrideCache[prefabName] = val;
			if ((Object)(object)val != (Object)null)
			{
				if (LoggedOverrides.Add(prefabName))
				{
					Log.LogInfo((object)("[HNRCustomIcons] Overriding icon for '" + prefabName + "' with '" + ((Object)val).name + ".png'"));
				}
				__result = val;
				return false;
			}
			return true;
		}

		private static string GetPrefabName(object item)
		{
			PropertyInfo property = item.GetType().GetProperty("prefabName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				return property.GetValue(item) as string;
			}
			return item.GetType().GetField("prefabName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(item) as string;
		}

		private static string StripNavmeshSuffix(string prefabName)
		{
			if (prefabName.EndsWith("_Navmesh", StringComparison.Ordinal))
			{
				return prefabName.Substring(0, prefabName.Length - "_Navmesh".Length);
			}
			return prefabName;
		}

		private static string GetAliasName(object item, string prefabName)
		{
			bool flag = false;
			try
			{
				object? obj = item.GetType().GetProperty("itemAsset", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(item);
				Component val = (Component)((obj is Component) ? obj : null);
				if (val != null && (Object)(object)val != (Object)null)
				{
					Type type = AccessTools.TypeByName("DEN_SlugGrub");
					if (type != null && (Object)(object)val.GetComponent(type) != (Object)null)
					{
						flag = true;
					}
				}
			}
			catch
			{
			}
			if (flag || prefabName.IndexOf("Grub", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return "food_grub";
			}
			if (prefabName.IndexOf("Bean", StringComparison.OrdinalIgnoreCase) >= 0 && prefabName.IndexOf("Eaten", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return "food_beans";
			}
			if (prefabName.StartsWith("Item_Note", StringComparison.OrdinalIgnoreCase))
			{
				if (prefabName.IndexOf("Blood", StringComparison.OrdinalIgnoreCase) < 0)
				{
					return "Item_Note_01";
				}
				return "Item_Note_Bloody";
			}
			return null;
		}

		private static Texture2D ResolveOverrideTexture(object item, string prefabName)
		{
			if (string.IsNullOrEmpty(IconsDir) || !Directory.Exists(IconsDir))
			{
				return null;
			}
			Texture2D val = LoadPng(Path.Combine(IconsDir, prefabName + ".png"));
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			string text = StripNavmeshSuffix(prefabName);
			if (!string.Equals(text, prefabName, StringComparison.Ordinal))
			{
				val = LoadPng(Path.Combine(IconsDir, text + ".png"));
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			string aliasName = GetAliasName(item, text);
			if (!string.IsNullOrEmpty(aliasName))
			{
				val = LoadPng(Path.Combine(IconsDir, aliasName + ".png"));
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}

		private static Texture2D LoadPng(string filePath)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (!File.Exists(filePath))
			{
				return null;
			}
			try
			{
				byte[] array = File.ReadAllBytes(filePath);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, array, false))
				{
					Object.Destroy((Object)(object)val);
					Log.LogWarning((object)("[HNRCustomIcons] Failed to decode PNG: " + filePath));
					return null;
				}
				((Texture)val).filterMode = (FilterMode)0;
				((Texture)val).wrapMode = (TextureWrapMode)1;
				((Object)val).name = Path.GetFileNameWithoutExtension(filePath);
				val.Apply(false, false);
				return val;
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[HNRCustomIcons] Error loading '" + filePath + "': " + ex.Message));
				return null;
			}
		}
	}
}