Decompiled source of GetOffMyLawn v1.7.0

GetOffMyLawn.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
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 BepInEx.Logging;
using ComfyLib;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("GetOffMyLawn")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GetOffMyLawn")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("514d9344-a1b0-4edf-93a8-17c7ae859946")]
[assembly: AssemblyFileVersion("1.7.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.7.0.0")]
[module: UnverifiableCode]
namespace GetOffMyLawn
{
	public static class PieceUtils
	{
		private static readonly List<Piece> _pieceCache = new List<Piece>();

		private static int _pieceCount = 0;

		public static bool RepairPiece(this Player player, ItemData toolItem, Piece piece)
		{
			//IL_003d: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			Plant val = default(Plant);
			if (!Object.op_Implicit((Object)(object)piece) || !Object.op_Implicit((Object)(object)piece.m_nview) || !piece.m_nview.IsValid() || ((Component)piece).TryGetComponent<Plant>(ref val))
			{
				return false;
			}
			if (!player.CheckCanRemovePiece(piece) || !PrivateArea.CheckAccess(((Component)piece).transform.position, 0f, true, false))
			{
				return false;
			}
			RepairPiece(piece, PluginConfig.TargetPieceHealth.Value, Time.time);
			player.FaceLookDirection();
			((Character)player).m_zanim.SetTrigger(toolItem.m_shared.m_attack.m_attackAnimation);
			EffectList placeEffect = piece.m_placeEffect;
			if (placeEffect != null)
			{
				placeEffect.Create(((Component)piece).transform.position, ((Component)piece).transform.rotation, (Transform)null, 1f, -1);
			}
			if (PluginConfig.ShowTopLeftMessageOnPieceRepair.Value)
			{
				((Character)player).Message((MessageType)1, Localization.instance.Localize("$msg_repaired", new string[1] { piece.m_name }), 0, (Sprite)null);
			}
			return true;
		}

		public static void RepairPiece(Piece piece, float targetHealth, float repairTime)
		{
			piece.m_nview.ClaimOwnership();
			piece.m_nview.m_zdo.Set(ZDOVars.s_health, targetHealth);
			WearNTear val = default(WearNTear);
			if (((Component)piece).TryGetComponent<WearNTear>(ref val))
			{
				val.m_lastRepair = repairTime;
				val.m_healthPercentage = Mathf.Clamp01(targetHealth / val.m_health);
				val.SetHealthVisual(val.m_healthPercentage, true);
			}
		}

		public static void RepairPiecesInRadius(Vector3 origin, float radius)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			_pieceCache.Clear();
			_pieceCount = 0;
			GetAllPiecesInRadius(origin, radius, _pieceCache);
			float value = PluginConfig.TargetPieceHealth.Value;
			float time = Time.time;
			Plant val = default(Plant);
			foreach (Piece item in _pieceCache)
			{
				if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)item.m_nview) || !item.m_nview.IsValid() || ((Component)item).TryGetComponent<Plant>(ref val))
				{
					continue;
				}
				RepairPiece(item, value, time);
				if (PluginConfig.ShowRepairEffectOnWardActivation.Value)
				{
					EffectList placeEffect = item.m_placeEffect;
					if (placeEffect != null)
					{
						placeEffect.Create(((Component)item).transform.position, ((Component)item).transform.rotation, (Transform)null, 1f, -1);
					}
				}
				_pieceCount++;
			}
			GetOffMyLawn.LogInfo($"Repaired {_pieceCount} pieces to health: {PluginConfig.TargetPieceHealth.Value}");
			if (PluginConfig.ShowTopLeftMessageOnPieceRepair.Value)
			{
				((Character)Player.m_localPlayer).Message((MessageType)1, $"Repaired {_pieceCount} pieces to health: {PluginConfig.TargetPieceHealth.Value}", 0, (Sprite)null);
			}
			_pieceCache.Clear();
		}

		private static void GetAllPiecesInRadius(Vector3 origin, float radius, List<Piece> pieces)
		{
			//IL_0027: 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)
			foreach (Piece s_allPiece in Piece.s_allPieces)
			{
				if (((Component)s_allPiece).gameObject.layer != Piece.s_ghostLayer && !(Vector3.Distance(origin, ((Component)s_allPiece).transform.position) >= radius))
				{
					pieces.Add(s_allPiece);
				}
			}
		}
	}
	[BepInPlugin("redseiko.valheim.getoffmylawn", "GetOffMyLawn", "1.7.0")]
	public sealed class GetOffMyLawn : BaseUnityPlugin
	{
		public const string PluginGUID = "redseiko.valheim.getoffmylawn";

		public const string PluginName = "GetOffMyLawn";

		public const string PluginVersion = "1.7.0";

		private static ManualLogSource _logger;

		private Harmony _harmony;

		private void Awake()
		{
			_logger = ((BaseUnityPlugin)this).Logger;
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "redseiko.valheim.getoffmylawn");
		}

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

		public static void LogInfo(object obj)
		{
			_logger.LogInfo((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {obj}");
		}

		public static void LogWarning(object obj)
		{
			_logger.LogWarning((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {obj}");
		}
	}
	[HarmonyPatch(typeof(BaseAI))]
	internal static class BaseAIPatch
	{
		public static int TargetRayMask;

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePostfix()
		{
			if (PluginConfig.IsModEnabled.Value && TargetRayMask == 0)
			{
				TargetRayMask = LayerMask.GetMask(new string[4] { "Default", "static_solid", "Default_small", "vehicle" });
				GetOffMyLawn.LogInfo($"Modifying BaseAI.m_monsterTargetRayMask from: {BaseAI.m_monsterTargetRayMask} to {TargetRayMask}.");
				BaseAI.m_monsterTargetRayMask = TargetRayMask;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("FindRandomStaticTarget")]
		private static bool FindRandomStaticTargetPrefix(ref StaticTarget __result)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__result = null;
				return false;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch("FindClosestStaticPriorityTarget")]
		private static bool FindClosestStaticPriorityTargetPrefix(ref StaticTarget __result)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__result = null;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(MonsterAI))]
	internal static class MonsterAIPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("UpdateTarget")]
		private static void UpdateTargetPrefix(ref MonsterAI __instance)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__instance.m_attackPlayerObjects = false;
			}
		}
	}
	[HarmonyPatch(typeof(Piece))]
	internal static class PiecePatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("SetCreator")]
		private static void SetCreatorPostfix(Piece __instance)
		{
			Plant val = default(Plant);
			if (PluginConfig.IsModEnabled.Value && Object.op_Implicit((Object)(object)__instance) && Object.op_Implicit((Object)(object)__instance.m_nview) && !((Component)__instance).TryGetComponent<Plant>(ref val))
			{
				__instance.m_nview.GetZDO().Set(ZDOVars.s_health, PluginConfig.TargetPieceHealth.Value);
			}
		}
	}
	[HarmonyPatch(typeof(Player))]
	internal static class PlayerPatch
	{
		public static readonly HashSet<string> RemovablePieceOverrides = new HashSet<string> { "$tool_cart", "$ship_longship", "$ship_raft", "$ship_karve" };

		[HarmonyPrefix]
		[HarmonyPatch("Repair")]
		private static bool RepairPrefix(Player __instance, ItemData toolItem)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				__instance.RepairPiece(toolItem, __instance.m_hoveringPiece);
				return false;
			}
			return true;
		}

		[HarmonyTranspiler]
		[HarmonyPatch("RemovePiece")]
		private static IEnumerable<CodeInstruction> RemovePieceTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)typeof(Piece).GetField("m_canBeRemoved"), (string)null)
			}).SetInstructionAndAdvance(Transpilers.EmitDelegate<Func<Piece, bool>>((Func<Piece, bool>)CanBeRemovedDelegate)).InstructionEnumeration();
		}

		private static bool CanBeRemovedDelegate(Piece piece)
		{
			if (!piece.m_canBeRemoved)
			{
				if (PluginConfig.IsModEnabled.Value)
				{
					return RemovablePieceOverrides.Contains(piece.m_name);
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PrivateArea))]
	internal static class PrivateAreaPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Interact")]
		private static void InteractPostfix(ref PrivateArea __instance)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (PluginConfig.IsModEnabled.Value && Object.op_Implicit((Object)(object)__instance) && __instance.IsEnabled() && __instance.m_piece.IsCreator())
			{
				PieceUtils.RepairPiecesInRadius(((Component)__instance).transform.position, __instance.m_radius);
			}
		}
	}
	[HarmonyPatch(typeof(WearNTear))]
	internal static class WearNTearPatch
	{
		public static readonly long PieceHealthDamageThreshold = 100000L;

		[HarmonyPrefix]
		[HarmonyPatch("ApplyDamage")]
		private static bool ApplyDamagePrefix(ref WearNTear __instance, ref bool __result, ref float damage)
		{
			if (!PluginConfig.IsModEnabled.Value || !PluginConfig.EnablePieceHealthDamageThreshold.Value)
			{
				return true;
			}
			float @float = __instance.m_nview.m_zdo.GetFloat(ZDOVars.s_health, __instance.m_health);
			if (@float <= 0f)
			{
				__result = false;
				return false;
			}
			if (@float >= (float)PieceHealthDamageThreshold)
			{
				__result = false;
				return false;
			}
			@float -= damage;
			__instance.m_nview.m_zdo.Set(ZDOVars.s_health, @float);
			if (@float <= 0f)
			{
				__instance.Destroy();
			}
			else
			{
				__instance.m_nview.InvokeRPC(ZNetView.Everybody, "WNTHealthChanged", new object[1] { @float });
			}
			__result = true;
			return false;
		}
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<float> TargetPieceHealth { get; private set; }

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

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

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

		public static void BindConfig(ConfigFile config)
		{
			IsModEnabled = config.BindInOrder("_Global", "isModEnabled", defaultValue: true, "Globally enable or disable this mod.");
			TargetPieceHealth = config.BindInOrder("PieceValue", "targetPieceHealth", 1E+17f, "Target value to set piece health to when creating and repairing.");
			EnablePieceHealthDamageThreshold = config.BindInOrder("Optimization", "enablePieceHealthDamageThreshold", defaultValue: true, "If piece health exceeds 100K, DO NOT execute ApplyDamage() or send WNTHealthChanged messages.");
			ShowTopLeftMessageOnPieceRepair = config.BindInOrder("Indicators", "showTopLeftMessageOnPieceRepair", defaultValue: false, "Shows a message in the top-left message area on piece repair.");
			ShowRepairEffectOnWardActivation = config.BindInOrder("Indicators", "showRepairEffectOnWardActivation", defaultValue: false, "Shows the repair effect on affected pieces when activating a ward.");
		}
	}
}
namespace ComfyLib
{
	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)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = GetSettingOrder(section)
				}
			}));
		}

		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);
			};
		}
	}
	public static class ObjectExtensions
	{
		public static T FirstByNameOrThrow<T>(this T[] unityObjects, string name) where T : Object
		{
			foreach (T val in unityObjects)
			{
				if (((Object)val).name == name)
				{
					return val;
				}
			}
			throw new InvalidOperationException($"Could not find Unity object of type {typeof(T)} with name: {name}");
		}

		public static T Ref<T>(this T unityObject) where T : Object
		{
			if (!Object.op_Implicit((Object)(object)unityObject))
			{
				return default(T);
			}
			return unityObject;
		}
	}
}