Decompiled source of DodgeCancel v0.3.3

DodgeCancel.dll

Decompiled 3 weeks ago
using System;
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 UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace DodgeCancel;

[BepInPlugin("com.burks.dodgecancel", "Dodge Cancel", "0.3.3")]
public class DodgeCancelPlugin : BaseUnityPlugin
{
	public const string GUID = "com.burks.dodgecancel";

	public const string NAME = "Dodge Cancel";

	public const string VERSION = "0.3.3";

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> DodgeOn;

	internal static ConfigEntry<bool> BlockOn;

	internal static ConfigEntry<bool> AirBlock;

	internal static ConfigEntry<float> FastSpeed;

	internal static ConfigEntry<float> MaxSeconds;

	internal static ConfigEntry<int> LogFirst;

	private static int _logged;

	internal static readonly FieldRef<Humanoid, Attack> CurAttack = AccessTools.FieldRefAccess<Humanoid, Attack>("m_currentAttack");

	internal static readonly FieldRef<Humanoid, Attack> PrevAttack = AccessTools.FieldRefAccess<Humanoid, Attack>("m_previousAttack");

	internal static readonly FieldRef<Character, Animator> Anim = AccessTools.FieldRefAccess<Character, Animator>("m_animator");

	internal static readonly FieldRef<Character, bool> Blocking = AccessTools.FieldRefAccess<Character, bool>("m_blocking");

	internal static readonly MethodInfo ClearQueue = AccessTools.Method(typeof(Humanoid), "ClearActionQueue", (Type[])null, (Type[])null);

	internal static readonly MethodInfo Blocker = AccessTools.Method(typeof(Humanoid), "GetCurrentBlocker", (Type[])null, (Type[])null);

	internal static float SkipUntil = -1f;

	internal static float NoAttackUntil = -1f;

	internal static readonly FieldRef<Character, ZSyncAnimation> ZAnim = AccessTools.FieldRefAccess<Character, ZSyncAnimation>("m_zanim");

	internal static ConfigEntry<bool> Unstick;

	internal static ConfigEntry<float> UnstickAfter;

	internal static float LastCancel = -100f;

	private static float _stuckSince = -1f;

	private static int _tries;

	private static int[] _calm = new int[0];

	internal static bool Skipping => Time.time < SkipUntil;

	private void Awake()
	{
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Invalid comparison between Unknown and I4
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		DodgeOn = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DodgeCancelsAttack", true, "Pressing dodge during an attack cuts the attack short and rolls.");
		BlockOn = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BlockCancelsAttack", true, "Pressing block during an attack cuts the attack short and raises your guard.");
		AirBlock = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "BlockInTheAir", true, "Let you block while jumping or falling (forces it on if another mod stops it).");
		FastSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Advanced", "SkipSpeed", 25f, "How fast the rest of a cancelled attack animation is skipped.");
		MaxSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Advanced", "MaxSkipSeconds", 0.75f, "Give up skipping after this long.");
		Unstick = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UnstickAttacks", true, "If you are still frozen in an attack animation about a second after a cancel, put the animation back to normal.");
		UnstickAfter = ((BaseUnityPlugin)this).Config.Bind<float>("General", "UnstickAfterSeconds", 0.5f, "How long after a cancel you can still be in the attack animation before it is put back to normal. At skip speed any real attack is long over by then.");
		LogFirst = ((BaseUnityPlugin)this).Config.Bind<int>("Debug", "LogFirstEvents", 5, "Write the first this-many cancels and air-block fixes to the log each game start (0 = never).");
		if ((int)SystemInfo.graphicsDeviceType != 4)
		{
			new Harmony("com.burks.dodgecancel").PatchAll(Assembly.GetExecutingAssembly());
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Dodge Cancel 0.3.3 loaded.");
		}
	}

	internal static void Note(string s)
	{
		if (_logged < LogFirst.Value)
		{
			_logged++;
			Log.LogInfo((object)s);
		}
	}

	internal static bool IsMe(Character c)
	{
		if ((Object)(object)c != (Object)null)
		{
			return (Object)(object)c == (Object)(object)Player.m_localPlayer;
		}
		return false;
	}

	internal static void Cancel(Player p, string why)
	{
		Attack val = CurAttack.Invoke((Humanoid)(object)p);
		string text = ((val != null && val.m_attackAnimation != null) ? val.m_attackAnimation : "attack");
		LastCancel = Time.time;
		_stuckSince = -1f;
		_tries = 0;
		if (val != null)
		{
			try
			{
				val.Stop();
			}
			catch
			{
			}
			PrevAttack.Invoke((Humanoid)(object)p) = val;
			CurAttack.Invoke((Humanoid)(object)p) = null;
		}
		try
		{
			if (ClearQueue != null)
			{
				ClearQueue.Invoke(p, null);
			}
		}
		catch
		{
		}
		SkipUntil = Time.time + Mathf.Max(0.1f, MaxSeconds.Value);
		NoAttackUntil = SkipUntil;
		Animator val2 = Anim.Invoke((Character)(object)p);
		if ((Object)(object)val2 != (Object)null && val != null && !string.IsNullOrEmpty(val.m_attackAnimation))
		{
			try
			{
				val2.ResetTrigger(val.m_attackAnimation);
				for (int i = 0; i < 6; i++)
				{
					val2.ResetTrigger(val.m_attackAnimation + i);
				}
			}
			catch
			{
			}
		}
		if ((Object)(object)val2 != (Object)null)
		{
			val2.speed = Mathf.Max(1f, FastSpeed.Value);
		}
		Note(why + ": cancelled " + text + ((val != null && val.m_loopingAttack) ? " (looping)" : "") + ".");
	}

	private static void Watch()
	{
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		Animator val = (((Object)(object)localPlayer != (Object)null) ? Anim.Invoke((Character)(object)localPlayer) : null);
		if ((Object)(object)val == (Object)null || !Unstick.Value)
		{
			return;
		}
		try
		{
			if (_calm.Length != val.layerCount)
			{
				_calm = new int[val.layerCount];
			}
			bool flag = ((Character)localPlayer).InAttack();
			if (!flag)
			{
				for (int i = 0; i < val.layerCount; i++)
				{
					if (!val.IsInTransition(i))
					{
						int[] calm = _calm;
						int num = i;
						AnimatorStateInfo currentAnimatorStateInfo = val.GetCurrentAnimatorStateInfo(i);
						calm[num] = ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash;
					}
				}
			}
			float num2 = Mathf.Clamp(UnstickAfter.Value, 0.2f, 3f);
			if (Time.time - LastCancel > 30f || Time.time - LastCancel < num2 || !flag || CurAttack.Invoke((Humanoid)(object)localPlayer) != null || ((Character)localPlayer).InDodge() || ((Character)localPlayer).IsDead())
			{
				_stuckSince = -1f;
			}
			else
			{
				if (_stuckSince >= 0f && Time.time - _stuckSince < num2)
				{
					return;
				}
				_stuckSince = Time.time;
				_tries++;
				SkipUntil = -1f;
				NoAttackUntil = Time.time + 0.1f;
				val.speed = 1f;
				ZSyncAnimation obj = ZAnim.Invoke((Character)(object)localPlayer);
				if (obj != null)
				{
					obj.SetTrigger("attack_abort");
				}
				for (int j = 0; j < val.layerCount; j++)
				{
					if (_calm[j] != 0)
					{
						val.CrossFadeInFixedTime(_calm[j], 0.1f, j);
					}
				}
				if (_tries >= 3)
				{
					LastCancel = -100f;
				}
				Log.LogWarning((object)("Stuck in an attack animation after a cancel (" + (PrevAttack.Invoke((Humanoid)(object)localPlayer)?.m_attackAnimation ?? "?") + "): put back to the last normal pose after " + (Time.time - LastCancel).ToString("0.00") + " s."));
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Unstick check failed: " + ex.Message));
			LastCancel = -100f;
		}
	}

	private void Update()
	{
		Watch();
		if (SkipUntil < 0f)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			SkipUntil = -1f;
		}
		else if (!((Character)localPlayer).InAttack() || !Skipping)
		{
			SkipUntil = -1f;
			NoAttackUntil = Time.time + 0.1f;
			Animator val = Anim.Invoke((Character)(object)localPlayer);
			if ((Object)(object)val != (Object)null && val.speed > 1.01f)
			{
				val.speed = 1f;
			}
		}
	}
}
[HarmonyPatch(typeof(Player), "Dodge")]
public static class Dodge_Patch
{
	private static readonly MethodInfo DodgeStamina = AccessTools.Method(typeof(Player), "GetDodgeStaminaUse", (Type[])null, (Type[])null);

	public static void Postfix(Player __instance)
	{
		try
		{
			if (DodgeCancelPlugin.DodgeOn.Value && DodgeCancelPlugin.IsMe((Character)(object)__instance) && ((Character)__instance).InAttack() && !((Character)__instance).InDodge() && !((Character)__instance).IsDead() && !((Character)__instance).IsEncumbered() && ((Character)__instance).IsOnGround())
			{
				float num = ((DodgeStamina != null) ? ((float)DodgeStamina.Invoke(__instance, null)) : 0f);
				if (((Character)__instance).HaveStamina(num))
				{
					DodgeCancelPlugin.Cancel(__instance, "Dodge");
				}
			}
		}
		catch (Exception ex)
		{
			DodgeCancelPlugin.Log.LogWarning((object)("Dodge cancel failed: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(Player), "SetControls")]
public static class Controls_Patch
{
	private static bool _held;

	public static void Prefix(Player __instance, bool block, bool blockHold)
	{
		try
		{
			if (DodgeCancelPlugin.IsMe((Character)(object)__instance))
			{
				bool num = block || (blockHold && !_held);
				_held = blockHold;
				if (num && DodgeCancelPlugin.BlockOn.Value && !DodgeCancelPlugin.Skipping && ((Character)__instance).InAttack() && !((Character)__instance).InDodge() && !((Character)__instance).IsDead())
				{
					DodgeCancelPlugin.Cancel(__instance, "Block");
				}
			}
		}
		catch (Exception ex)
		{
			DodgeCancelPlugin.Log.LogWarning((object)("Block cancel failed: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class StartAttack_Patch
{
	[HarmonyPriority(800)]
	public static bool Prefix(Humanoid __instance, ref bool __result)
	{
		if (!DodgeCancelPlugin.IsMe((Character)(object)__instance) || Time.time >= DodgeCancelPlugin.NoAttackUntil)
		{
			return true;
		}
		__result = false;
		return false;
	}
}
[HarmonyPatch(typeof(CharacterAnimEvent), "CustomFixedUpdate")]
public static class AnimSpeed_Patch
{
	private static readonly FieldRef<CharacterAnimEvent, Character> Owner = AccessTools.FieldRefAccess<CharacterAnimEvent, Character>("m_character");

	private static readonly FieldRef<CharacterAnimEvent, Animator> An = AccessTools.FieldRefAccess<CharacterAnimEvent, Animator>("m_animator");

	[HarmonyPriority(0)]
	public static void Postfix(CharacterAnimEvent __instance)
	{
		if (DodgeCancelPlugin.Skipping && DodgeCancelPlugin.IsMe(Owner.Invoke(__instance)))
		{
			Animator val = An.Invoke(__instance);
			if ((Object)(object)val != (Object)null)
			{
				val.speed = Mathf.Max(1f, DodgeCancelPlugin.FastSpeed.Value);
			}
		}
	}
}
[HarmonyPatch]
public static class AnimEvents_Patch
{
	private static readonly FieldRef<CharacterAnimEvent, Character> Owner = AccessTools.FieldRefAccess<CharacterAnimEvent, Character>("m_character");

	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(CharacterAnimEvent), "OnAnimatorMove", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(CharacterAnimEvent), "Speed", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(CharacterAnimEvent), "FreezeFrame", (Type[])null, (Type[])null);
	}

	[HarmonyPriority(800)]
	public static bool Prefix(CharacterAnimEvent __instance)
	{
		if (DodgeCancelPlugin.Skipping)
		{
			return !DodgeCancelPlugin.IsMe(Owner.Invoke(__instance));
		}
		return true;
	}
}
[HarmonyPatch(typeof(Humanoid), "IsBlocking")]
public static class AirBlock_Patch
{
	private static bool _toldThisJump;

	[HarmonyPriority(0)]
	public static void Postfix(Humanoid __instance, ref bool __result)
	{
		try
		{
			if (__result || !DodgeCancelPlugin.AirBlock.Value || !DodgeCancelPlugin.IsMe((Character)(object)__instance))
			{
				return;
			}
			if (((Character)__instance).IsOnGround())
			{
				_toldThisJump = false;
			}
			else if (DodgeCancelPlugin.Blocking.Invoke((Character)(object)__instance) && !((Character)__instance).InAttack() && !((Character)__instance).InDodge() && !((Character)__instance).IsStaggering() && !((Character)__instance).IsDead() && !((Character)__instance).InPlaceMode() && !((Character)__instance).IsEncumbered() && ((DodgeCancelPlugin.Blocker != null) ? DodgeCancelPlugin.Blocker.Invoke(__instance, null) : null) != null)
			{
				__result = true;
				if (!_toldThisJump)
				{
					_toldThisJump = true;
					DodgeCancelPlugin.Note("Air block forced on (the game said no; minor action=" + ((Character)__instance).InMinorAction() + ").");
				}
			}
		}
		catch
		{
		}
	}
}