Decompiled source of WiresWeightedSlots v0.1.1

WiresWeightedSlots.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("WiresWeightedSlots")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WiresWeightedSlots")]
[assembly: AssemblyTitle("WiresWeightedSlots")]
[assembly: AssemblyVersion("1.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 WiresWeightedSlots
{
	[BepInPlugin("wire.valheim.weightedslots", "Wire's Weighted Slots", "0.1.1")]
	[BepInProcess("valheim.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string Guid = "wire.valheim.weightedslots";

		internal const string Name = "Wire's Weighted Slots";

		internal const string Version = "0.1.1";

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> MaxDarkness;

		internal static ConfigEntry<float> CurveWeight;

		internal static ConfigEntry<float> BorderInset;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Weighted Slot Backgrounds", "Enabled", true, "Shade the empty BACKGROUND inside an occupied inventory or hotbar slot according to that item's total weight.");
			MaxDarkness = ((BaseUnityPlugin)this).Config.Bind<float>("Weighted Slot Backgrounds", "Maximum darkness", 0.92f, new ConfigDescription("Upper limit of black opacity, reached only asymptotically for extremely heavy stacks. Increase up to 0.95 for stronger contrast.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.95f), Array.Empty<object>()));
			CurveWeight = ((BaseUnityPlugin)this).Config.Bind<float>("Weighted Slot Backgrounds", "Weight curve (kg)", 75f, new ConfigDescription("Half-darkness weight in kg. Higher numbers make the shading less intense at the same weight. Even extremely heavy stacks remain visually distinguishable.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 500f), Array.Empty<object>()));
			BorderInset = ((BaseUnityPlugin)this).Config.Bind<float>("Weighted Slot Backgrounds", "Border inset (pixels)", 3.5f, new ConfigDescription("Keep the dark shade away from the original slot border, rarity, and selection indicators.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 12f), Array.Empty<object>()));
			_harmony = new Harmony("wire.valheim.weightedslots");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Wire's Weighted Slots 0.1.1 loaded.");
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
			WeightShade.RestoreAll();
		}
	}
	internal sealed class WeightShade : MonoBehaviour
	{
		private static readonly List<WeightShade> All = new List<WeightShade>();

		private Image _shade;

		private float _lastWeight = float.NaN;

		internal int SeenStamp;

		private float _lastDark = float.NaN;

		private float _lastScale = float.NaN;

		private float _lastInset = float.NaN;

		private bool _lastEnabled;

		internal void ClearIfNotSeen(int stamp)
		{
			if (SeenStamp != stamp && (Object)(object)_shade != (Object)null)
			{
				Apply(0f, Plugin.Enabled != null && Plugin.Enabled.Value);
			}
		}

		internal static void UpdateSlot(GameObject slot, float totalKg, int stamp = 0)
		{
			if ((Object)(object)slot == (Object)null)
			{
				return;
			}
			WeightShade weightShade = slot.GetComponent<WeightShade>();
			bool flag = Plugin.Enabled != null && Plugin.Enabled.Value;
			if ((Object)(object)weightShade == (Object)null)
			{
				if (!flag || totalKg < 0.05f)
				{
					return;
				}
				weightShade = slot.AddComponent<WeightShade>();
			}
			weightShade.SeenStamp = stamp;
			weightShade.Apply(flag ? Mathf.Max(0f, totalKg) : 0f, flag);
		}

		private void Awake()
		{
			All.Add(this);
		}

		private void EnsureImage()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_005f: 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_006a: 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: 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_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_00c2: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_shade != (Object)null))
			{
				GameObject val = new GameObject("WeightedSlots_BackgroundShade", new Type[3]
				{
					typeof(RectTransform),
					typeof(CanvasRenderer),
					typeof(Image)
				});
				RectTransform val2 = (RectTransform)val.transform;
				((Transform)val2).SetParent(((Component)this).transform, false);
				val2.anchorMin = Vector2.zero;
				val2.anchorMax = Vector2.one;
				((Transform)val2).localScale = Vector3.one;
				((Transform)val2).localRotation = Quaternion.identity;
				((Transform)val2).SetAsFirstSibling();
				_shade = val.GetComponent<Image>();
				((Graphic)_shade).raycastTarget = false;
				((Graphic)_shade).color = new Color(0f, 0f, 0f, 0f);
				((Behaviour)_shade).enabled = false;
			}
		}

		private void Apply(float weight, bool enabled)
		{
			//IL_00da: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			float value = Plugin.MaxDarkness.Value;
			float value2 = Plugin.CurveWeight.Value;
			float value3 = Plugin.BorderInset.Value;
			if ((Object)(object)_shade != (Object)null && weight == _lastWeight && value == _lastDark && value2 == _lastScale && value3 == _lastInset && enabled == _lastEnabled)
			{
				return;
			}
			_lastWeight = weight;
			_lastDark = value;
			_lastScale = value2;
			_lastInset = value3;
			_lastEnabled = enabled;
			float num = 0f;
			if (enabled && weight >= 0.05f)
			{
				num = value * weight / (weight + value2);
			}
			if (num <= 0.0005f)
			{
				if ((Object)(object)_shade != (Object)null && ((Behaviour)_shade).enabled)
				{
					((Behaviour)_shade).enabled = false;
				}
				return;
			}
			EnsureImage();
			RectTransform val = (RectTransform)((Component)_shade).transform;
			val.offsetMin = new Vector2(value3, value3);
			val.offsetMax = new Vector2(0f - value3, 0f - value3);
			((Graphic)_shade).color = new Color(0f, 0f, 0f, num);
			((Behaviour)_shade).enabled = true;
		}

		internal static void RestoreAll()
		{
			for (int num = All.Count - 1; num >= 0; num--)
			{
				WeightShade weightShade = All[num];
				if ((Object)(object)weightShade != (Object)null && (Object)(object)weightShade._shade != (Object)null)
				{
					((Behaviour)weightShade._shade).enabled = false;
				}
			}
		}

		private void OnDestroy()
		{
			All.Remove(this);
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
	[HarmonyAfter(new string[] { "wire.valheim.smoothui", "Azumatt.AzuExtendedPlayerInventory", "shudnal.MyLittleUI" })]
	internal static class InventoryGridPatch
	{
		private static readonly FieldRef<InventoryGrid, List<InventoryElement>> Elements = AccessTools.FieldRefAccess<InventoryGrid, List<InventoryElement>>("m_elements");

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix(InventoryGrid __instance)
		{
			Inventory inventory = __instance.GetInventory();
			if (inventory == null)
			{
				return;
			}
			List<InventoryElement> list = Elements.Invoke(__instance);
			if (list == null || list.Count == 0)
			{
				return;
			}
			int num = Mathf.Max(1, inventory.GetWidth());
			for (int i = 0; i < list.Count; i++)
			{
				InventoryElement val = list[i];
				if ((Object)(object)val != (Object)null && !val.m_used)
				{
					WeightShade.UpdateSlot(((Component)val).gameObject, 0f);
				}
			}
			List<ItemData> allItems = inventory.GetAllItems();
			for (int j = 0; j < allItems.Count; j++)
			{
				ItemData val2 = allItems[j];
				if (val2 == null || val2.m_shared == null)
				{
					continue;
				}
				int num2 = val2.m_gridPos.y * num + val2.m_gridPos.x;
				if (num2 >= 0 && num2 < list.Count)
				{
					InventoryElement val3 = list[num2];
					if (!((Object)(object)val3 == (Object)null))
					{
						WeightShade.UpdateSlot(((Component)val3).gameObject, val2.GetWeight(-1));
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(HotkeyBar), "UpdateIcons")]
	[HarmonyAfter(new string[] { "Azumatt.AzuExtendedPlayerInventory", "wire.valheim.smoothui" })]
	internal static class HotbarPatch
	{
		private static readonly FieldRef<HotkeyBar, List<ItemData>> Items = AccessTools.FieldRefAccess<HotkeyBar, List<ItemData>>("m_items");

		private static readonly FieldInfo ElementsField = AccessTools.Field(typeof(HotkeyBar), "m_elements");

		private static readonly FieldInfo ElementGoField = AccessTools.Field(typeof(HotkeyBar).GetNestedType("ElementData", BindingFlags.NonPublic), "m_go");

		private static int _drawStamp;

		private static bool _azuInitialized;

		private static FieldInfo _azuSlots;

		private static FieldInfo _azuQuickCount;

		private static void InitAzu()
		{
			if (_azuInitialized)
			{
				return;
			}
			_azuInitialized = true;
			if (Chainloader.PluginInfos.TryGetValue("Azumatt.AzuExtendedPlayerInventory", out var value))
			{
				Assembly assembly = ((object)value.Instance).GetType().Assembly;
				Type type = assembly.GetType("AzuEPI.EPI.ExtendedPlayerInventory", throwOnError: false);
				Type type2 = assembly.GetType("AzuEPI.AzuExtendedPlayerInventoryPlugin", throwOnError: false);
				if (type != null && type2 != null)
				{
					_azuSlots = AccessTools.Field(type, "slots");
					_azuQuickCount = AccessTools.Field(type2, "QuickSlotsAmount");
				}
			}
		}

		private static bool TryGetAzuStart(Player player, out int start)
		{
			start = 0;
			InitAzu();
			if (_azuSlots == null || _azuQuickCount == null)
			{
				return false;
			}
			ICollection collection = _azuSlots.GetValue(null) as ICollection;
			ConfigEntry<int> val = _azuQuickCount.GetValue(null) as ConfigEntry<int>;
			if (collection == null || val == null)
			{
				return false;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			int width = inventory.GetWidth();
			if (width <= 0)
			{
				return false;
			}
			int num = (collection.Count + width - 1) / width;
			start = (inventory.GetHeight() - num) * width + collection.Count - val.Value;
			return start >= 0;
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix(HotkeyBar __instance, Player player)
		{
			if ((Object)(object)player == (Object)null || ((Character)player).IsDead() || !(ElementsField.GetValue(__instance) is IList { Count: not 0 } list))
			{
				return;
			}
			int stamp = ++_drawStamp;
			List<ItemData> list2 = Items.Invoke(__instance);
			bool flag = ((Object)__instance).name == "AzuEPI_QuickAccessBar";
			int start = 0;
			int width = ((Humanoid)player).GetInventory().GetWidth();
			if ((!flag || TryGetAzuStart(player, out start)) && list2 != null)
			{
				for (int i = 0; i < list2.Count; i++)
				{
					ItemData val = list2[i];
					if (val == null || val.m_shared == null)
					{
						continue;
					}
					int num = (flag ? (val.m_gridPos.y * width + val.m_gridPos.x - start) : val.m_gridPos.x);
					if (num >= 0 && num < list.Count)
					{
						object? value = ElementGoField.GetValue(list[num]);
						GameObject val2 = (GameObject)((value is GameObject) ? value : null);
						if (!((Object)(object)val2 == (Object)null))
						{
							WeightShade.UpdateSlot(val2, val.GetWeight(-1), stamp);
						}
					}
				}
			}
			for (int j = 0; j < list.Count; j++)
			{
				object? value2 = ElementGoField.GetValue(list[j]);
				GameObject val3 = (GameObject)((value2 is GameObject) ? value2 : null);
				if (!((Object)(object)val3 == (Object)null))
				{
					WeightShade component = val3.GetComponent<WeightShade>();
					if ((Object)(object)component != (Object)null)
					{
						component.ClearIfNotSeen(stamp);
					}
				}
			}
		}
	}
}