Decompiled source of ArrowTweaks v1.0.0

plugins/ArrowTweaks.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using Valheim.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[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 ArrowTweaks
{
	[BepInPlugin("OGTristonMcPherson.ArrowTweaks", "ArrowTweaks", "1.0.0")]
	public class ArrowTweaksPlugin : BaseUnityPlugin
	{
		public const string GUID = "OGTristonMcPherson.ArrowTweaks";

		public const string NAME = "ArrowTweaks";

		public const string VERSION = "1.0.0";

		internal static ConfigEntry<bool> InfiniteBasic;

		internal static ConfigEntry<string> BasicArrowPrefabs;

		internal static ConfigEntry<int> SpecialStackSize;

		internal static ConfigEntry<float> CostMultiplier;

		internal static ConfigEntry<float> CraftSpeedMultiplier;

		internal static ConfigEntry<string> FletcherStations;

		internal static ConfigEntry<bool> IncludeBolts;

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			InfiniteBasic = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Basic arrows", "Infinite", true, "Basic arrows are never consumed when fired and show an infinity sign instead of a count. You still need at least one in your inventory.");
			BasicArrowPrefabs = ((BaseUnityPlugin)this).Config.Bind<string>("1 - Basic arrows", "Basic arrow prefabs", "ArrowWood", "Comma-separated prefab names treated as basic (infinite) arrows.");
			SpecialStackSize = ((BaseUnityPlugin)this).Config.Bind<int>("2 - Special arrows", "Max stack size", 9999, new ConfigDescription("Max stack size for every non-basic arrow.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 99999), Array.Empty<object>()));
			CostMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Special arrows", "Crafting cost multiplier", 0.5f, new ConfigDescription("Multiplier on the material cost of every non-basic arrow recipe. Rounded up, minimum 1 per ingredient.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1f), Array.Empty<object>()));
			CraftSpeedMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Fletcher table", "Arrow craft speed multiplier", 10f, new ConfigDescription("How many times faster arrows craft at the fletcher table. 1 = normal.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			FletcherStations = ((BaseUnityPlugin)this).Config.Bind<string>("3 - Fletcher table", "Station prefabs", "FletcherTable_TW", "Comma-separated crafting station prefab names the speed-up applies to.");
			IncludeBolts = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - General", "Include bolts", false, "Also apply the stack size, cost and craft speed changes to crossbow bolts.");
			CostMultiplier.SettingChanged += delegate
			{
				Rules.ResetCosts();
			};
			SpecialStackSize.SettingChanged += delegate
			{
				Rules.Refresh();
			};
			IncludeBolts.SettingChanged += delegate
			{
				Rules.ResetCosts();
				Rules.Refresh();
			};
			BasicArrowPrefabs.SettingChanged += delegate
			{
				Rules.ParseLists();
				Rules.ResetCosts();
				Rules.Refresh();
			};
			FletcherStations.SettingChanged += delegate
			{
				Rules.ParseLists();
			};
			Rules.ParseLists();
			_harmony = new Harmony("OGTristonMcPherson.ArrowTweaks");
			_harmony.PatchAll(typeof(ArrowTweaksPlugin).Assembly);
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class Rules
	{
		private class CostState
		{
			public int Original;

			public int Applied;
		}

		private class StackState
		{
			public int Original;
		}

		internal const string Infinity = "∞";

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

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

		private static readonly Dictionary<Requirement, CostState> _costs = new Dictionary<Requirement, CostState>();

		private static readonly Dictionary<SharedData, StackState> _stacks = new Dictionary<SharedData, StackState>();

		private static readonly Dictionary<TMP_FontAsset, bool> _glyphCache = new Dictionary<TMP_FontAsset, bool>();

		internal static void ParseLists()
		{
			_basic = Split(ArrowTweaksPlugin.BasicArrowPrefabs.Value);
			_stations = Split(ArrowTweaksPlugin.FletcherStations.Value);
		}

		private static HashSet<string> Split(string s)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = (s ?? "").Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					hashSet.Add(text);
				}
			}
			return hashSet;
		}

		internal static bool IsArrowShared(SharedData s, bool allowBolts)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if (s == null || (int)s.m_itemType != 9)
			{
				return false;
			}
			if (s.m_ammoType == "$ammo_arrows")
			{
				return true;
			}
			if (allowBolts)
			{
				return s.m_ammoType == "$ammo_bolts";
			}
			return false;
		}

		internal static bool IsBasicPrefab(string prefabName)
		{
			if (prefabName != null)
			{
				return _basic.Contains(prefabName);
			}
			return false;
		}

		internal static bool IsBasic(ItemData item)
		{
			if (item == null || item.m_shared == null)
			{
				return false;
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null)
			{
				return IsBasicPrefab(((Object)item.m_dropPrefab).name);
			}
			if (item.m_shared.m_name == "$item_arrowwood")
			{
				return _basic.Contains("ArrowWood");
			}
			return false;
		}

		internal static bool IsInfiniteBasic(ItemData item)
		{
			if (ArrowTweaksPlugin.InfiniteBasic.Value)
			{
				return IsBasic(item);
			}
			return false;
		}

		internal static bool IsSpecialArrowPrefab(GameObject prefab, out ItemDrop drop)
		{
			drop = null;
			if ((Object)(object)prefab == (Object)null || IsBasicPrefab(((Object)prefab).name))
			{
				return false;
			}
			drop = prefab.GetComponent<ItemDrop>();
			if ((Object)(object)drop != (Object)null)
			{
				return IsArrowShared(drop.m_itemData?.m_shared, ArrowTweaksPlugin.IncludeBolts.Value);
			}
			return false;
		}

		internal static bool IsFletcher(CraftingStation station)
		{
			if ((Object)(object)station != (Object)null)
			{
				return _stations.Contains(Utils.GetPrefabName(((Component)station).gameObject));
			}
			return false;
		}

		internal static void ResetCosts()
		{
			foreach (KeyValuePair<Requirement, CostState> cost in _costs)
			{
				if (cost.Key != null && cost.Key.m_amount == cost.Value.Applied)
				{
					cost.Key.m_amount = cost.Value.Original;
				}
			}
			_costs.Clear();
			Refresh();
		}

		internal static void Refresh()
		{
			ObjectDB instance = ObjectDB.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			try
			{
				RefreshStacks(instance);
				RefreshCosts(instance);
			}
			catch (Exception ex)
			{
				ArrowTweaksPlugin.Log.LogError((object)("Refresh failed: " + ex));
			}
		}

		private static void RefreshStacks(ObjectDB db)
		{
			int value = ArrowTweaksPlugin.SpecialStackSize.Value;
			HashSet<SharedData> hashSet = new HashSet<SharedData>();
			foreach (GameObject item in db.m_items)
			{
				if (IsSpecialArrowPrefab(item, out var drop))
				{
					SharedData shared = drop.m_itemData.m_shared;
					hashSet.Add(shared);
					if (!_stacks.TryGetValue(shared, out var value2))
					{
						Dictionary<SharedData, StackState> stacks = _stacks;
						StackState obj = new StackState
						{
							Original = shared.m_maxStackSize
						};
						value2 = obj;
						stacks[shared] = obj;
					}
					shared.m_maxStackSize = value;
				}
			}
			List<SharedData> list = new List<SharedData>();
			foreach (KeyValuePair<SharedData, StackState> stack in _stacks)
			{
				if (!hashSet.Contains(stack.Key))
				{
					stack.Key.m_maxStackSize = stack.Value.Original;
					list.Add(stack.Key);
				}
			}
			foreach (SharedData item2 in list)
			{
				_stacks.Remove(item2);
			}
		}

		private static void RefreshCosts(ObjectDB db)
		{
			float value = ArrowTweaksPlugin.CostMultiplier.Value;
			foreach (Recipe recipe in db.m_recipes)
			{
				if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || recipe.m_resources == null || !IsSpecialArrowPrefab(((Component)recipe.m_item).gameObject, out var _))
				{
					continue;
				}
				Requirement[] resources = recipe.m_resources;
				foreach (Requirement val in resources)
				{
					if (val != null && (!_costs.TryGetValue(val, out var value2) || val.m_amount != value2.Applied))
					{
						int amount = val.m_amount;
						int num = ((amount <= 0) ? amount : Math.Max(1, (int)Math.Ceiling((double)((float)amount * value) - 0.0001)));
						_costs[val] = new CostState
						{
							Original = amount,
							Applied = num
						};
						val.m_amount = num;
					}
				}
			}
		}

		internal static string InfinityFor(TMP_Text text)
		{
			TMP_FontAsset val = (((Object)(object)text != (Object)null) ? text.font : null);
			if ((Object)(object)val == (Object)null)
			{
				return "∞";
			}
			if (!_glyphCache.TryGetValue(val, out var value))
			{
				try
				{
					value = val.HasCharacter('∞', true, true);
				}
				catch
				{
					value = false;
				}
				_glyphCache[val] = value;
			}
			if (!value)
			{
				return "<rotate=90>8</rotate>";
			}
			return "∞";
		}

		internal static void SetInfinity(TMP_Text text)
		{
			if (!((Object)(object)text == (Object)null))
			{
				if (!((Component)text).gameObject.activeSelf)
				{
					((Component)text).gameObject.SetActive(true);
				}
				string text2 = InfinityFor(text);
				if (text.text != text2)
				{
					text.text = text2;
				}
			}
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	internal static class ObjectDB_Awake_Patch
	{
		[HarmonyPriority(0)]
		private static void Postfix()
		{
			Rules.Refresh();
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
	internal static class ObjectDB_CopyOtherDB_Patch
	{
		[HarmonyPriority(0)]
		private static void Postfix()
		{
			Rules.Refresh();
		}
	}
	[HarmonyPatch(typeof(Player), "OnSpawned")]
	internal static class Player_OnSpawned_Patch
	{
		[HarmonyPriority(0)]
		private static void Postfix()
		{
			Rules.Refresh();
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Show")]
	internal static class InventoryGui_Show_Patch
	{
		private static void Prefix()
		{
			Rules.Refresh();
		}
	}
	[HarmonyPatch(typeof(Attack), "UseAmmo")]
	internal static class Attack_UseAmmo_Patch
	{
		[ThreadStatic]
		internal static int Depth;

		private static void Prefix()
		{
			Depth++;
		}

		private static void Finalizer()
		{
			Depth--;
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(ItemData),
		typeof(int)
	})]
	internal static class Inventory_RemoveItem_Patch
	{
		[HarmonyPriority(800)]
		private static bool Prefix(ItemData item, ref bool __result)
		{
			if (Attack_UseAmmo_Patch.Depth > 0 && Rules.IsInfiniteBasic(item))
			{
				__result = true;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
	internal static class InventoryGrid_UpdateGui_Patch
	{
		private static readonly FieldRef<InventoryGrid, List<InventoryElement>> Elements = AccessTools.FieldRefAccess<InventoryGrid, List<InventoryElement>>("m_elements");

		private static readonly FieldRef<InventoryGrid, Inventory> Inv = AccessTools.FieldRefAccess<InventoryGrid, Inventory>("m_inventory");

		private static void Postfix(InventoryGrid __instance)
		{
			if (!ArrowTweaksPlugin.InfiniteBasic.Value)
			{
				return;
			}
			Inventory val = Inv.Invoke(__instance);
			List<InventoryElement> list = Elements.Invoke(__instance);
			if (val == null || list == null)
			{
				return;
			}
			int width = val.GetWidth();
			foreach (ItemData allItem in val.GetAllItems())
			{
				if (Rules.IsBasic(allItem))
				{
					int num = allItem.m_gridPos.y * width + allItem.m_gridPos.x;
					if (num >= 0 && num < list.Count)
					{
						Rules.SetInfinity(list[num]?.m_amount);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(HotkeyBar), "UpdateIcons")]
	internal static class HotkeyBar_UpdateIcons_Patch
	{
		private static readonly FieldInfo ElementsField = AccessTools.Field(typeof(HotkeyBar), "m_elements");

		private static readonly FieldInfo ItemsField = AccessTools.Field(typeof(HotkeyBar), "m_items");

		private static FieldInfo _amountField;

		private static void Postfix(HotkeyBar __instance)
		{
			if (!ArrowTweaksPlugin.InfiniteBasic.Value)
			{
				return;
			}
			IList list = ElementsField?.GetValue(__instance) as IList;
			List<ItemData> list2 = ItemsField?.GetValue(__instance) as List<ItemData>;
			if (list == null || list2 == null)
			{
				return;
			}
			foreach (ItemData item in list2)
			{
				if (!Rules.IsBasic(item))
				{
					continue;
				}
				int x = item.m_gridPos.x;
				if (x >= 0 && x < list.Count && list[x] != null)
				{
					object obj = list[x];
					if (_amountField == null)
					{
						_amountField = AccessTools.Field(obj.GetType(), "m_amount");
					}
					object? obj2 = _amountField?.GetValue(obj);
					Rules.SetInfinity((TMP_Text)((obj2 is TMP_Text) ? obj2 : null));
				}
			}
		}
	}
	[HarmonyPatch(typeof(ItemElement), "SetAmount")]
	internal static class RadialItemElement_SetAmount_Patch
	{
		private static readonly MethodInfo SetSubTitle = AccessTools.PropertySetter(typeof(ItemElement), "SubTitle");

		private static void Postfix(ItemElement __instance, ItemData __0)
		{
			if (!Rules.IsInfiniteBasic(__0) || (Object)(object)__instance.m_amount == (Object)null)
			{
				return;
			}
			Rules.SetInfinity(__instance.m_amount);
			try
			{
				SetSubTitle?.Invoke(__instance, new object[1] { __instance.m_amount.text });
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
	internal static class InventoryGui_UpdateRecipe_Patch
	{
		private static readonly FieldRef<InventoryGui, Recipe> CraftRecipe = AccessTools.FieldRefAccess<InventoryGui, Recipe>("m_craftRecipe");

		private static bool _active;

		private static float _craft;

		private static float _multi;

		private static void Prefix(InventoryGui __instance, Player player)
		{
			if (_active)
			{
				Restore(__instance);
			}
			float value = ArrowTweaksPlugin.CraftSpeedMultiplier.Value;
			if (!(value <= 1f) && !((Object)(object)player == (Object)null))
			{
				Recipe val = CraftRecipe.Invoke(__instance);
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val.m_item == (Object)null) && Rules.IsArrowShared(val.m_item.m_itemData?.m_shared, ArrowTweaksPlugin.IncludeBolts.Value) && Rules.IsFletcher(player.GetCurrentCraftingStation()))
				{
					_active = true;
					_craft = __instance.m_craftDuration;
					_multi = __instance.m_multiCraftDuration;
					__instance.m_craftDuration /= value;
					__instance.m_multiCraftDuration /= value;
				}
			}
		}

		private static void Finalizer(InventoryGui __instance)
		{
			if (_active)
			{
				Restore(__instance);
			}
		}

		private static void Restore(InventoryGui gui)
		{
			gui.m_craftDuration = _craft;
			gui.m_multiCraftDuration = _multi;
			_active = false;
		}
	}
}