Decompiled source of TorchesAndResin v1.8.0

TorchesAndResin.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
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 ComfyLib;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("TorchesAndResin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TorchesAndResin")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("0dcd6a5f-93ee-4e00-b8df-8720d1176557")]
[assembly: AssemblyFileVersion("1.8.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.8.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 TorchesAndResin
{
	public static class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<int> TorchStartingFuel { get; private set; }

		public static ConfigEntry<bool> CandleHoverTextShowFuel { get; private set; }

		public static ConfigEntry<bool> CandleAlwaysToggleOn { get; private set; }

		public static ConfigEntry<bool> CandleUpdateStateNeverWet { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			IsModEnabled = config.BindInOrder("_Global", "isModEnabled", defaultValue: true, "Globally enable or disable this mod.");
			TorchStartingFuel = config.BindInOrder("Fuel", "torchStartingFuel", 10000, "Value to set eligible torches' starting fuel to.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10000, 99999));
			CandleHoverTextShowFuel = config.BindInOrder("Candle", "candleHoverTextShowFuel", defaultValue: true, "When true, will show the remaining fuel for candles in its hover-text.");
			CandleAlwaysToggleOn = config.BindInOrder("Candle", "candleAlwaysToggleOn", defaultValue: true, "When true, eligible candles will always be toggled-on.");
			CandleUpdateStateNeverWet = config.BindInOrder("Candle", "candleUpdateStateNeverWet", defaultValue: true, "When true, eligible over-fueld candles will not be wet or underwater when updating state.");
		}
	}
	public static class FireplaceManager
	{
		public static readonly HashSet<int> EligibleFireplaceHashCodes = new HashSet<int>
		{
			StringExtensionMethods.GetStableHashCode("Candle_resin"),
			StringExtensionMethods.GetStableHashCode("fire_pit_iron"),
			StringExtensionMethods.GetStableHashCode("piece_groundtorch"),
			StringExtensionMethods.GetStableHashCode("piece_groundtorch_wood"),
			StringExtensionMethods.GetStableHashCode("piece_walltorch"),
			StringExtensionMethods.GetStableHashCode("piece_brazierceiling01"),
			StringExtensionMethods.GetStableHashCode("piece_brazierfloor01")
		};

		public static void SetEligibleFireplaceFuel(Fireplace fireplace, float startingFuel)
		{
			ZNetView nview = fireplace.m_nview;
			ZDO zdo = nview.m_zdo;
			if (!EligibleFireplaceHashCodes.Contains(zdo.m_prefab))
			{
				return;
			}
			fireplace.m_startFuel = startingFuel;
			if (nview.IsOwner())
			{
				float num = default(float);
				if (!zdo.GetFloat(ZDOVars.s_fuel, ref num) || num < startingFuel)
				{
					zdo.Set(ZDOVars.s_fuel, startingFuel);
				}
				int num2 = default(int);
				if (fireplace.m_canTurnOff && PluginConfig.CandleAlwaysToggleOn.Value && zdo.GetInt(ZDOVars.s_state, ref num2) && num2 != 1)
				{
					zdo.Set(ZDOVars.s_state, 1, false);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Fireplace))]
	internal static class FireplacePatch
	{
		[HarmonyTranspiler]
		[HarmonyPatch("Awake")]
		private static IEnumerable<CodeInstruction> AwakeTranspiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			List<Label> labels;
			return new CodeMatcher(instructions, generator).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[3]
			{
				new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Fireplace), "m_nview"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.Method(typeof(ZNetView), "IsOwner", (Type[])null, (Type[])null), (string)null)
			}).ThrowIfInvalid("Could not patch Fireplace.Awake()! (check-is-owner")
				.ExtractLabels(out labels)
				.Insert((CodeInstruction[])(object)new CodeInstruction[2]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null),
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(FireplacePatch), "CheckIsOwnerPreDelegate", (Type[])null, (Type[])null))
				})
				.AddLabels((IEnumerable<Label>)labels)
				.MatchStartForward((CodeMatch[])(object)new CodeMatch[3]
				{
					new CodeMatch((OpCode?)OpCodes.Ldstr, (object)"UpdateFireplace", (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldc_R4, (object)0f, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldc_R4, (object)2f, (string)null)
				})
				.ThrowIfInvalid("Could not patch Fireplace.Awake()! (invoke-update-fireplace)")
				.Advance(1)
				.SetOperandAndAdvance((object)0.5f)
				.InstructionEnumeration();
		}

		private static void CheckIsOwnerPreDelegate(Fireplace fireplace)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				FireplaceManager.SetEligibleFireplaceFuel(fireplace, PluginConfig.TorchStartingFuel.Value);
			}
		}

		[HarmonyTranspiler]
		[HarmonyPatch("GetHoverText")]
		private static IEnumerable<CodeInstruction> GetHoverTextTranspiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			return new CodeMatcher(instructions, generator).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[4]
			{
				new CodeMatch((OpCode?)OpCodes.Ldloc_1, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldstr, (object)"\n[<color=yellow><b>$KEY_Use</b></color>] $piece_use", (string)null),
				new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Stloc_1, (object)null, (string)null)
			}).ThrowIfInvalid("Could not patch Fireplace.GetHoverText()! (can-turn-off-text)")
				.Advance(2)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2]
				{
					new CodeInstruction(OpCodes.Ldloc_0, (object)null),
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(FireplacePatch), "CanTurnOffHoverTextDelegate", (Type[])null, (Type[])null))
				})
				.InstructionEnumeration();
		}

		private static string CanTurnOffHoverTextDelegate(string hoverText, float fuel)
		{
			if (PluginConfig.IsModEnabled.Value && PluginConfig.CandleHoverTextShowFuel.Value)
			{
				return $"\n( $piece_fire_fuel {fuel:F2} )\n[<color=yellow><b>$KEY_Use</b></color>] $piece_use";
			}
			return hoverText;
		}

		[HarmonyPrefix]
		[HarmonyPatch("UpdateState")]
		private static void UpdateStatePrefix(Fireplace __instance, ref bool __state)
		{
			if (__instance.m_canTurnOff && __instance.m_wet && PluginConfig.IsModEnabled.Value && PluginConfig.CandleUpdateStateNeverWet.Value && __instance.m_startFuel > __instance.m_maxFuel)
			{
				__state = true;
				__instance.m_wet = false;
			}
			else
			{
				__state = false;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("UpdateState")]
		private static void UpdateStatePostfix(Fireplace __instance, bool __state)
		{
			if (__state)
			{
				__instance.m_wet = true;
			}
		}

		[HarmonyTranspiler]
		[HarmonyPatch("IsBurning")]
		private static IEnumerable<CodeInstruction> IsBuringTranspiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			return new CodeMatcher(instructions, generator).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Floating), "IsUnderWater", (Type[])null, (Type[])null), (string)null)
			}).ThrowIfInvalid("Could not patch Fireplace.IsBurning()! (is-under-water-check)")
				.Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null),
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(FireplacePatch), "IsUnderWaterPostDelegate", (Type[])null, (Type[])null))
				})
				.InstructionEnumeration();
		}

		private static bool IsUnderWaterPostDelegate(bool isUnderWater, Fireplace fireplace)
		{
			if (isUnderWater && fireplace.m_canTurnOff && PluginConfig.IsModEnabled.Value && PluginConfig.CandleUpdateStateNeverWet.Value && fireplace.m_startFuel > fireplace.m_maxFuel)
			{
				return false;
			}
			return isUnderWater;
		}
	}
	[BepInPlugin("redseiko.valheim.torchesandresin", "TorchesAndResin", "1.8.0")]
	public sealed class TorchesAndResin : BaseUnityPlugin
	{
		public const string PluginGuid = "redseiko.valheim.torchesandresin";

		public const string PluginName = "TorchesAndResin";

		public const string PluginVersion = "1.8.0";

		private void Awake()
		{
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "redseiko.valheim.torchesandresin");
		}
	}
}
namespace ComfyLib
{
	public static class CodeMatcherExtensions
	{
		public static CodeMatcher CreateLabelOffset(this CodeMatcher matcher, int offset, out Label label)
		{
			return matcher.CreateLabelAt(matcher.Pos + offset, ref label);
		}

		public static CodeMatcher DeclareLocal(this CodeMatcher matcher, ILGenerator generator, Type localType, out LocalBuilder localBuilder)
		{
			localBuilder = generator.DeclareLocal(localType);
			return matcher;
		}

		public static CodeMatcher ExtractLabels(this CodeMatcher matcher, out List<Label> labels)
		{
			labels = matcher.Labels.ToList();
			matcher.Labels.Clear();
			return matcher;
		}
	}
	public static class ConfigFileExtensions
	{
		internal sealed class ConfigurationManagerAttributes
		{
			public Action<ConfigEntryBase> CustomDrawer;

			public bool? Browsable;

			public bool? HideDefaultButton;

			public bool? HideSettingName;

			public bool? IsAdvanced;

			public int? Order;

			public bool? ReadOnly;
		}

		private static readonly Dictionary<string, int> _sectionToSettingOrder = new Dictionary<string, int>();

		private static int GetSettingOrder(string section)
		{
			if (!_sectionToSettingOrder.TryGetValue(section, out var value))
			{
				value = 0;
			}
			_sectionToSettingOrder[section] = value - 1;
			return value;
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, AcceptableValueBase acceptableValues, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = null,
					HideDefaultButton = hideDefaultButton,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, Action<ConfigEntryBase> customDrawer = null, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = customDrawer,
					HideDefaultButton = hideDefaultButton,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action settingChangedHandler)
		{
			configEntry.SettingChanged += delegate
			{
				settingChangedHandler();
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<T> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((T)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<ConfigEntry<T>> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((ConfigEntry<T>)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}
	}
}