Decompiled source of Meadingful Icons v0.1.3

Plugins/VentureValheim.MeadingfulIcons.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("VentureValheim.MeadingfulIcons")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VentureValheim.MeadingfulIcons")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("884001A0-E62E-49F3-901A-80B5B1CECF4F")]
[assembly: AssemblyFileVersion("0.1.3")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.3.0")]
[module: UnverifiableCode]
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;
		}
	}
}
namespace VentureValheim.MeadingfulIcons
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("com.orianaventure.mod.MeadingfulIcons", "MeadingfulIcons", "0.1.3")]
	public class MeadingfulIconsPlugin : BaseUnityPlugin
	{
		private const string ModName = "MeadingfulIcons";

		private const string ModVersion = "0.1.3";

		private const string Author = "com.orianaventure.mod";

		private const string ModGUID = "com.orianaventure.mod.MeadingfulIcons";

		private static string ConfigFileName = "com.orianaventure.mod.MeadingfulIcons.cfg";

		private static string ConfigFileFullPath;

		private readonly Harmony HarmonyInstance = new Harmony("com.orianaventure.mod.MeadingfulIcons");

		public static readonly ManualLogSource MeadingfulIconsLogger;

		private static ConfigEntry<bool> CE_ReplaceIcons;

		private static ConfigEntry<int> CE_StackSize;

		private readonly ConfigurationManagerAttributes AdminConfig = new ConfigurationManagerAttributes
		{
			IsAdminOnly = true
		};

		private readonly ConfigurationManagerAttributes ClientConfig = new ConfigurationManagerAttributes
		{
			IsAdminOnly = false
		};

		private DateTime _lastReloadTime;

		private const long RELOAD_DELAY = 10000000L;

		public static bool GetReplaceIcons()
		{
			return CE_ReplaceIcons.Value;
		}

		public static int GetStackSize()
		{
			return CE_StackSize.Value;
		}

		private void AddConfig<T>(string key, string section, string description, bool synced, T value, ref ConfigEntry<T> configEntry)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			string extendedDescription = GetExtendedDescription(description, synced);
			configEntry = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, value, new ConfigDescription(extendedDescription, (AcceptableValueBase)null, new object[1] { synced ? AdminConfig : ClientConfig }));
		}

		public string GetExtendedDescription(string description, bool synchronizedSetting)
		{
			return description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]");
		}

		public void Awake()
		{
			AddConfig("ReplaceIcons", "General", "True to replace all mead base icons (boolean).", synced: false, value: true, ref CE_ReplaceIcons);
			AddConfig("StackSize", "General", "Stack Size for all mead bases (integer).", synced: true, 10, ref CE_StackSize);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			HarmonyInstance.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			DateTime now = DateTime.Now;
			long num = now.Ticks - _lastReloadTime.Ticks;
			if (File.Exists(ConfigFileFullPath) && num >= 10000000)
			{
				try
				{
					MeadingfulIconsLogger.LogInfo((object)"Attempting to reload configuration...");
					((BaseUnityPlugin)this).Config.Reload();
				}
				catch
				{
					MeadingfulIconsLogger.LogError((object)("There was an issue loading " + ConfigFileName));
					return;
				}
				_lastReloadTime = now;
				if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsDedicated())
				{
					MeadingfulIcons.ApplyMeadingfulChanges();
				}
			}
		}

		static MeadingfulIconsPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			MeadingfulIconsLogger = Logger.CreateLogSource("MeadingfulIcons");
			CE_ReplaceIcons = null;
			CE_StackSize = null;
		}
	}
	public class MeadingfulIcons
	{
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		public static class Patch_ObjectDB_Awake
		{
			private static void Postfix()
			{
				//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)
				Scene activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name.Equals("main"))
				{
					_objectDBReady = true;
					ApplyMeadingfulChanges();
				}
				else
				{
					_objectDBReady = false;
				}
			}
		}

		private static readonly MeadingfulIcons _instance;

		private static AssetBundle _iconBundle;

		private static readonly HashSet<string> _meadList;

		private static bool _objectDBReady;

		public static MeadingfulIcons Instance => _instance;

		static MeadingfulIcons()
		{
			_instance = new MeadingfulIcons();
			_iconBundle = null;
			_meadList = new HashSet<string>
			{
				"MeadBaseHealthMinor", "MeadBaseHealthMedium", "MeadBaseHealthMajor", "MeadBaseHealthLingering", "MeadBaseStaminaMinor", "MeadBaseStaminaMedium", "MeadBaseStaminaLingering", "MeadBaseEitrMinor", "MeadBaseEitrLingering", "MeadBaseFrostResist",
				"MeadBasePoisonResist", "BarleyWineBase"
			};
			_objectDBReady = false;
		}

		private MeadingfulIcons()
		{
		}

		public static bool GetItemDrop(string name, out ItemDrop item)
		{
			item = null;
			if (!Utility.IsNullOrWhiteSpace(name))
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(name));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					itemPrefab = ObjectDB.instance.GetItemPrefab(name);
				}
				if ((Object)(object)itemPrefab != (Object)null)
				{
					item = itemPrefab.GetComponent<ItemDrop>();
					if ((Object)(object)item != (Object)null)
					{
						return true;
					}
				}
			}
			return false;
		}

		private static Texture2D DuplicateTexture(Sprite sprite)
		{
			//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_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_002e: 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_004a: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			if ((Object)(object)sprite == (Object)null)
			{
				return null;
			}
			Rect textureRect = sprite.textureRect;
			int num = (int)((Rect)(ref textureRect)).width;
			textureRect = sprite.textureRect;
			int num2 = (int)((Rect)(ref textureRect)).height;
			textureRect = sprite.textureRect;
			int num3 = (int)((Rect)(ref textureRect)).x;
			int height = ((Texture)sprite.texture).height;
			textureRect = sprite.textureRect;
			int num4 = height - (int)((Rect)(ref textureRect)).y - num2;
			RenderTexture active = RenderTexture.active;
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)sprite.texture).width, ((Texture)sprite.texture).height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)2);
			Graphics.Blit((Texture)(object)sprite.texture, temporary);
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(num, num2);
			val.ReadPixels(new Rect((float)num3, (float)num4, (float)num, (float)num2), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			return val;
		}

		private static Sprite MergeTextures(string name, Texture2D baseTexture, Texture2D overlayTexture)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: 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_0031: 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_0038: 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_005e: 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_0070: Unknown result type (might be due to invalid IL or missing references)
			int width = ((Texture)baseTexture).width;
			int height = ((Texture)baseTexture).height;
			Texture2D val = new Texture2D(width, height);
			for (int i = 0; i < width; i++)
			{
				for (int j = 0; j < height; j++)
				{
					val.SetPixel(i, j, Color.clear);
					Color pixel = overlayTexture.GetPixel(i, j);
					if (pixel.a != 0f)
					{
						val.SetPixel(i, j, pixel);
						continue;
					}
					Color pixel2 = baseTexture.GetPixel(i, j);
					if (pixel2.a != 0f)
					{
						val.SetPixel(i, j, pixel2);
					}
				}
			}
			val.Apply();
			Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)width, (float)height), new Vector2(0.5f, 0.5f));
			((Object)obj).name = name;
			return obj;
		}

		public static void ApplyMeadingfulChanges()
		{
			if (!_objectDBReady)
			{
				return;
			}
			if (MeadingfulIconsPlugin.GetReplaceIcons() && (Object)(object)_iconBundle == (Object)null)
			{
				try
				{
					_iconBundle = AssetUtils.LoadAssetBundleFromResources("meadingful_icons", Assembly.GetExecutingAssembly());
				}
				catch (Exception ex)
				{
					MeadingfulIconsPlugin.MeadingfulIconsLogger.LogError((object)"Exception Caught! This mod might not behave as expected.");
					MeadingfulIconsPlugin.MeadingfulIconsLogger.LogInfo((object)ex);
				}
			}
			Texture2D val = null;
			if (GetItemDrop("MeadBaseTasty", out ItemDrop item))
			{
				if (MeadingfulIconsPlugin.GetReplaceIcons() && (Object)(object)_iconBundle != (Object)null && item.m_itemData.m_shared.m_icons.Length != 0)
				{
					Sprite val2 = item.m_itemData.m_shared.m_icons[0];
					val = (Texture2D)((!((Texture)val2.texture).isReadable) ? ((object)DuplicateTexture(val2)) : ((object)val2.texture));
				}
				item.m_itemData.m_shared.m_maxStackSize = MeadingfulIconsPlugin.GetStackSize();
			}
			foreach (string mead in _meadList)
			{
				if (GetItemDrop(mead, out ItemDrop item2))
				{
					if (MeadingfulIconsPlugin.GetReplaceIcons() && (Object)(object)_iconBundle != (Object)null && (Object)(object)val != (Object)null)
					{
						Sprite val3 = null;
						try
						{
							val3 = _iconBundle.LoadAsset<Sprite>("VV_" + mead);
						}
						catch (Exception ex2)
						{
							MeadingfulIconsPlugin.MeadingfulIconsLogger.LogError((object)"Exception Caught! This mod might not behave as expected.");
							MeadingfulIconsPlugin.MeadingfulIconsLogger.LogInfo((object)ex2);
						}
						if ((Object)(object)val3 != (Object)null && ((Texture)val3.texture).isReadable)
						{
							Sprite val4 = MergeTextures("VV_" + mead, val, val3.texture);
							item2.m_itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { val4 };
						}
						else
						{
							MeadingfulIconsPlugin.MeadingfulIconsLogger.LogWarning((object)("Could not load " + mead + " icon! Skipping."));
						}
					}
					item2.m_itemData.m_shared.m_maxStackSize = MeadingfulIconsPlugin.GetStackSize();
				}
				else
				{
					MeadingfulIconsPlugin.MeadingfulIconsLogger.LogWarning((object)("Could not find " + mead + "! Skipping."));
				}
			}
			MeadingfulIconsPlugin.MeadingfulIconsLogger.LogInfo((object)"Done applying mead configurations.");
		}
	}
}