Decompiled source of HoldToMelee v0.1.0

BepInEx/plugins/HoldToMelee/HoldToMelee.dll

Decompiled 3 weeks ago
using System;
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 BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HoldToMelee")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("HoldToMelee")]
[assembly: AssemblyTitle("HoldToMelee")]
[assembly: AssemblyVersion("0.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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;
		}
	}
	[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 HoldToMelee
{
	internal sealed class ComboController
	{
		private readonly ComboState state = new ComboState();

		private readonly ShovelAdapter adapter;

		private readonly Func<bool> enabled;

		private readonly ManualLogSource logger;

		private readonly Func<PlayerControllerB, bool> canUseItem;

		private readonly FieldRef<PlayerControllerB, float> switchingTime;

		private InputAction? attackAction;

		private PlayerControllerB? inputPlayer;

		private bool inputFailureLogged;

		internal ComboController(Func<bool> enabled, ManualLogSource logger)
		{
			this.enabled = enabled;
			this.logger = logger;
			adapter = new ShovelAdapter(logger);
			canUseItem = AccessTools.MethodDelegate<Func<PlayerControllerB, bool>>(AccessTools.Method(typeof(PlayerControllerB), "CanUseItem", (Type[])null, (Type[])null), (object)null, true);
			switchingTime = AccessTools.FieldRefAccess<PlayerControllerB, float>("timeSinceSwitchingSlots");
		}

		private static bool IsLocal(PlayerControllerB player)
		{
			if ((Object)(object)StartOfRound.Instance != (Object)null && (Object)(object)StartOfRound.Instance.localPlayerController == (Object)(object)player)
			{
				return ((NetworkBehaviour)player).IsOwner;
			}
			return false;
		}

		private bool Allowed(PlayerControllerB player, GrabbableObject? item)
		{
			if (Application.isFocused && ((Behaviour)player).isActiveAndEnabled && IsLocal(player) && player.isPlayerControlled && !player.isPlayerDead && !player.inSpecialMenu && !player.isTypingChat && !player.inTerminalMenu && !player.inSpecialInteractAnimation && !player.isGrabbingObjectAnimation && !player.inShockingMinigame && (Object)(object)item != (Object)null && ((Behaviour)item).isActiveAndEnabled && ((NetworkBehaviour)item).IsOwner && item.isHeld && (Object)(object)item.playerHeldBy == (Object)(object)player && (Object)(object)player.currentlyHeldObjectServer == (Object)(object)item)
			{
				return canUseItem(player);
			}
			return false;
		}

		internal void Begin(PlayerControllerB player, InputAction action)
		{
			if (!IsLocal(player))
			{
				return;
			}
			try
			{
				attackAction = action;
				inputPlayer = player;
				GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
				if (!enabled() || !action.enabled || !action.IsPressed() || !Allowed(player, currentlyHeldObjectServer) || !adapter.Supports(currentlyHeldObjectServer))
				{
					state.Interrupt();
				}
				else
				{
					state.Begin(currentlyHeldObjectServer, enabled: true, allowed: true, pressed: true, Time.frameCount);
				}
			}
			catch (Exception e)
			{
				InputFailure(e);
			}
		}

		internal void Release(PlayerControllerB player)
		{
			if (!((Object)(object)player != (Object)(object)inputPlayer))
			{
				if (!Application.isFocused || attackAction == null || !attackAction.enabled)
				{
					state.Interrupt();
				}
				else
				{
					state.Release();
				}
			}
		}

		internal void Interrupt()
		{
			state.Interrupt();
			try
			{
				if (attackAction == null || (Application.isFocused && attackAction.enabled && !attackAction.IsPressed()))
				{
					state.Release();
				}
			}
			catch (Exception)
			{
			}
		}

		internal void InputSkipped(PlayerControllerB player)
		{
			if ((Object)(object)player == (Object)(object)inputPlayer)
			{
				Interrupt();
			}
		}

		internal void RecordAttempt(GrabbableObject item)
		{
			if (state.Matches(item))
			{
				state.RecordAttempt(Time.frameCount);
			}
		}

		internal void ActivationSkipped(GrabbableObject item)
		{
			if (state.Matches(item))
			{
				Interrupt();
			}
		}

		internal void ReleaseShovelHold(Shovel shovel)
		{
			if (!state.Matches(shovel))
			{
				return;
			}
			try
			{
				PlayerControllerB playerHeldBy = ((GrabbableObject)shovel).playerHeldBy;
				if (!enabled() || attackAction == null || !attackAction.enabled || !attackAction.IsPressed() || (Object)(object)playerHeldBy == (Object)null || !Allowed(playerHeldBy, (GrabbableObject?)(object)shovel) || !adapter.Supports((GrabbableObject?)(object)shovel))
				{
					Interrupt();
				}
				else if (shovel.reelingUp)
				{
					shovel.isHoldingButton = false;
				}
			}
			catch (Exception ex)
			{
				adapter.Disable((GrabbableObject)(object)shovel, ex.Message);
				Interrupt();
			}
		}

		internal void Tick()
		{
			if (attackAction == null)
			{
				return;
			}
			try
			{
				if (!Application.isFocused || !attackAction.enabled)
				{
					Interrupt();
					return;
				}
				PlayerControllerB val = (((Object)(object)StartOfRound.Instance == (Object)null) ? null : StartOfRound.Instance.localPlayerController);
				GrabbableObject val2 = (((Object)(object)val == (Object)null) ? null : val.currentlyHeldObjectServer);
				bool allowed = (Object)(object)val != (Object)null && (Object)(object)val == (Object)(object)inputPlayer && Allowed(val, val2);
				state.Observe(enabled(), allowed, attackAction.IsPressed(), val2);
				Shovel val3 = (Shovel)(object)((val2 is Shovel) ? val2 : null);
				if (val3 == null || !state.Matches(val2) || !adapter.Supports(val2))
				{
					return;
				}
				bool ready = adapter.Ready(val3) && switchingTime.Invoke(val) >= 0.075f;
				if (!state.TrySchedule(Time.frameCount, ready))
				{
					return;
				}
				try
				{
					((GrabbableObject)val3).UseItemOnClient(true);
				}
				catch (Exception ex)
				{
					adapter.Disable((GrabbableObject)(object)val3, ex.Message);
					Interrupt();
				}
			}
			catch (Exception e)
			{
				InputFailure(e);
			}
		}

		private void InputFailure(Exception e)
		{
			Interrupt();
			if (!inputFailureLogged)
			{
				inputFailureLogged = true;
				logger.LogWarning((object)$"Auto combo input unavailable; native input is unchanged. {e}");
			}
		}
	}
	internal sealed class ComboState
	{
		private bool requireRelease;

		private int lastAttemptFrame = -1;

		internal object? Target { get; private set; }

		internal bool Begin(object target, bool enabled, bool allowed, bool pressed, int frame)
		{
			if (!enabled || !allowed || !pressed || requireRelease)
			{
				return false;
			}
			Target = target;
			lastAttemptFrame = frame;
			return true;
		}

		internal void Observe(bool enabled, bool allowed, bool pressed, object? target)
		{
			if (!enabled || !allowed || (Target != null && Target != target))
			{
				Interrupt();
			}
			if (!pressed)
			{
				Release();
			}
		}

		internal bool TrySchedule(int frame, bool ready)
		{
			if (Target == null || requireRelease || !ready || frame == lastAttemptFrame)
			{
				return false;
			}
			lastAttemptFrame = frame;
			return true;
		}

		internal void RecordAttempt(int frame)
		{
			lastAttemptFrame = frame;
		}

		internal bool Matches(object target)
		{
			if (!requireRelease)
			{
				return Target == target;
			}
			return false;
		}

		internal void Interrupt()
		{
			Target = null;
			requireRelease = true;
		}

		internal void Release()
		{
			Target = null;
			requireRelease = false;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
	internal static class AttackPressedPatch
	{
		private static void Prefix(PlayerControllerB __instance, CallbackContext __0)
		{
			if (((CallbackContext)(ref __0)).performed)
			{
				Plugin.Instance?.Controller?.Begin(__instance, ((CallbackContext)(ref __0)).action);
			}
		}

		private static void Postfix(PlayerControllerB __instance, bool __runOriginal)
		{
			if (!__runOriginal)
			{
				Plugin.Instance?.Controller?.InputSkipped(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_canceled")]
	internal static class AttackReleasedPatch
	{
		private static void Prefix(PlayerControllerB __instance)
		{
			Plugin.Instance?.Controller?.Release(__instance);
		}
	}
	[HarmonyPatch(typeof(GrabbableObject), "UseItemOnClient")]
	internal static class UseAttemptPatch
	{
		private static void Prefix(GrabbableObject __instance, bool __0)
		{
			if (__0)
			{
				Plugin.Instance?.Controller?.RecordAttempt(__instance);
			}
		}

		private static void Postfix(GrabbableObject __instance, bool __runOriginal)
		{
			if (!__runOriginal)
			{
				Plugin.Instance?.Controller?.ActivationSkipped(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Shovel), "ItemActivate")]
	internal static class ShovelActivationPatch
	{
		private static void Postfix(Shovel __instance, bool __1, bool __runOriginal)
		{
			if (__1)
			{
				if (__runOriginal)
				{
					Plugin.Instance?.Controller?.ReleaseShovelHold(__instance);
				}
				else
				{
					Plugin.Instance?.Controller?.ActivationSkipped((GrabbableObject)(object)__instance);
				}
			}
		}
	}
	[BepInPlugin("sakur.lethalcompany.holdtomelee", "HoldToMelee", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string PluginId = "sakur.lethalcompany.holdtomelee";

		private ConfigEntry<bool>? enabledEntry;

		private Harmony? harmony;

		internal static Plugin? Instance { get; private set; }

		internal ComboController? Controller { get; private set; }

		private void Awake()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			Instance = this;
			enabledEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "开启长按武器连击:按住攻击键自动连续挥击铲子机制武器。关闭恢复原版举铲。菜刀不受影响。无需重启。");
			enabledEntry.SettingChanged += OnSettingChanged;
			try
			{
				Controller = new ComboController(() => enabledEntry.Value, ((BaseUnityPlugin)this).Logger);
				harmony = new Harmony("sakur.lethalcompany.holdtomelee");
				harmony.PatchAll(typeof(Plugin).Assembly);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"HoldToMelee 0.1.0 loaded (local shovel input assistance only).");
			}
			catch (Exception arg)
			{
				Controller?.Interrupt();
				Controller = null;
				Harmony? obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				((BaseUnityPlugin)this).Logger.LogError((object)$"Auto combo disabled: game hooks unavailable. {arg}");
			}
			if (Chainloader.PluginInfos.ContainsKey("ainavt.lc.lethalconfig"))
			{
				try
				{
					SettingsIntegration.Register(enabledEntry);
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("LethalConfig integration unavailable; config file remains usable. " + ex.Message));
				}
			}
		}

		private void OnSettingChanged(object sender, EventArgs args)
		{
			Controller?.Interrupt();
		}

		private void LateUpdate()
		{
			Controller?.Tick();
		}

		private void OnApplicationFocus(bool focused)
		{
			if (!focused)
			{
				Controller?.Interrupt();
			}
		}

		private void OnApplicationPause(bool paused)
		{
			if (paused)
			{
				Controller?.Interrupt();
			}
		}

		private void OnDisable()
		{
			Controller?.Interrupt();
		}

		private void OnDestroy()
		{
			Controller?.Interrupt();
			if (enabledEntry != null)
			{
				enabledEntry.SettingChanged -= OnSettingChanged;
			}
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
	internal static class SettingsIntegration
	{
		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void Register(ConfigEntry<bool> entry)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(entry, new BoolCheckBoxOptions
			{
				Name = "开启长按武器连击",
				Section = "操作",
				Description = "按住攻击键自动连续挥击铲子、路牌及沿用原版铲子机制的武器;关闭恢复原版举铲。菜刀不受影响。",
				RequiresRestart = false
			}));
			LethalConfigManager.SetModDescription("纯客户端长按连击,仅接续原版铲子攻击流程,保留原版伤害与攻击节奏。");
		}
	}
	internal sealed class ShovelAdapter
	{
		private readonly Dictionary<Type, bool> supported = new Dictionary<Type, bool>();

		private readonly ConditionalWeakTable<GrabbableObject, object> disabled = new ConditionalWeakTable<GrabbableObject, object>();

		private readonly ConditionalWeakTable<Item, object> warnedDefinitions = new ConditionalWeakTable<Item, object>();

		private readonly ManualLogSource logger;

		internal ShovelAdapter(ManualLogSource logger)
		{
			this.logger = logger;
		}

		internal bool Supports(GrabbableObject? item)
		{
			if (!(item is Shovel))
			{
				return false;
			}
			Type type = ((object)item).GetType();
			if (disabled.TryGetValue(item, out object value))
			{
				return false;
			}
			if ((Object)(object)item.itemProperties == (Object)null)
			{
				Disable(item, "Missing item definition.");
				return false;
			}
			if (item.itemProperties.syncUseFunction)
			{
				if (!warnedDefinitions.TryGetValue(item.itemProperties, out value))
				{
					warnedDefinitions.Add(item.itemProperties, new object());
					logger.LogInfo((object)("Leaving generic use synchronization unchanged for a " + type.FullName + " item definition."));
				}
				return false;
			}
			if (!supported.TryGetValue(type, out var value2))
			{
				value2 = WeaponTypePolicy.InheritsActivation(type, typeof(Shovel));
				supported[type] = value2;
				if (!value2)
				{
					logger.LogInfo((object)("Leaving custom shovel activation unchanged: " + type.FullName));
				}
			}
			return value2;
		}

		internal bool Ready(Shovel shovel)
		{
			if (float.IsNaN(((GrabbableObject)shovel).useCooldown) || float.IsInfinity(((GrabbableObject)shovel).useCooldown) || float.IsNaN(((GrabbableObject)shovel).currentUseCooldown) || float.IsInfinity(((GrabbableObject)shovel).currentUseCooldown))
			{
				Disable((GrabbableObject)(object)shovel, "Unrecognized use cooldown.");
				return false;
			}
			if (!shovel.reelingUp)
			{
				if (!(((GrabbableObject)shovel).useCooldown <= 0f))
				{
					return ((GrabbableObject)shovel).currentUseCooldown <= 0f;
				}
				return true;
			}
			return false;
		}

		internal void Disable(GrabbableObject item, string reason)
		{
			if (!disabled.TryGetValue(item, out object _))
			{
				disabled.Add(item, new object());
				logger.LogWarning((object)("Auto combo disabled for this " + ((object)item).GetType().FullName + " instance: " + reason));
			}
		}
	}
	internal static class WeaponTypePolicy
	{
		internal static bool InheritsActivation(Type actual, Type vanilla)
		{
			if (vanilla.IsAssignableFrom(actual))
			{
				return actual.GetMethod("ItemActivate", BindingFlags.Instance | BindingFlags.Public, null, new Type[2]
				{
					typeof(bool),
					typeof(bool)
				}, null)?.DeclaringType == vanilla;
			}
			return false;
		}
	}
}