Decompiled source of GojoInfinity v1.0.0

BepInEx\plugins\GojoInfinity\GojoInfinity.dll

Decompiled 17 minutes 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.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[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("GojoInfinity")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("GojoInfinity")]
[assembly: AssemblyTitle("GojoInfinity")]
[assembly: AssemblyVersion("1.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 GojoInfinity
{
	internal static class InfinityService
	{
		private sealed class FrozenState
		{
			internal Vector3 Position;

			internal Quaternion Rotation;

			internal bool Seen;

			internal bool WasEnabled;

			internal bool WasAgentStopped;

			internal bool HasAnimator;

			internal float AnimatorSpeed;

			internal Rigidbody Body;

			internal bool WasKinematic;
		}

		internal static bool Active;

		private static readonly Dictionary<EnemyAI, FrozenState> Frozen = new Dictionary<EnemyAI, FrozenState>();

		private static readonly Dictionary<EnemyAI, Collider[]> ColliderCache = new Dictionary<EnemyAI, Collider[]>();

		internal static PlayerControllerB GetLocalPlayer()
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return null;
			}
			return instance.localPlayerController;
		}

		internal static void Toggle()
		{
			Active = !Active;
			if (!Active)
			{
				UnfreezeAll();
			}
			Plugin.Log.LogInfo((object)("Infinity barrier " + (Active ? "expanded" : "released") + "."));
			ShowHudMessage(Active);
		}

		internal static void UpdateBarrier()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled.Value || !Active || !Plugin.FreezeEnemies.Value)
			{
				UnfreezeAll();
				return;
			}
			PlayerControllerB localPlayer = GetLocalPlayer();
			if ((Object)(object)localPlayer == (Object)null || localPlayer.isPlayerDead || !localPlayer.isPlayerControlled || !((NetworkBehaviour)localPlayer).IsSpawned || IsPlayerHeldByEnemy(localPlayer))
			{
				UnfreezeAll();
				return;
			}
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null || instance.SpawnedEnemies == null)
			{
				UnfreezeAll();
				return;
			}
			Vector3 point = ((Component)localPlayer).transform.position + Vector3.up * 1f;
			float value = Plugin.Radius.Value;
			float num = value + 0.75f;
			foreach (FrozenState value3 in Frozen.Values)
			{
				value3.Seen = false;
			}
			foreach (EnemyAI spawnedEnemy in instance.SpawnedEnemies)
			{
				if ((Object)(object)spawnedEnemy == (Object)null || spawnedEnemy.isEnemyDead || !((NetworkBehaviour)spawnedEnemy).IsSpawned)
				{
					continue;
				}
				bool flag = Frozen.ContainsKey(spawnedEnemy);
				if (!(GetDistanceToEnemy(point, spawnedEnemy) > (flag ? num : value)))
				{
					if (!Frozen.TryGetValue(spawnedEnemy, out var value2))
					{
						value2 = Freeze(spawnedEnemy);
						Frozen[spawnedEnemy] = value2;
					}
					value2.Seen = true;
					LockTransform(spawnedEnemy, value2);
				}
			}
			List<EnemyAI> list = null;
			foreach (KeyValuePair<EnemyAI, FrozenState> item in Frozen)
			{
				if (!item.Value.Seen || !((Object)(object)item.Key != (Object)null) || item.Key.isEnemyDead)
				{
					if (list == null)
					{
						list = new List<EnemyAI>();
					}
					list.Add(item.Key);
				}
			}
			if (list != null)
			{
				foreach (EnemyAI item2 in list)
				{
					Unfreeze(item2);
				}
			}
			if (ColliderCache.Count > 200)
			{
				CleanupColliderCache();
			}
		}

		internal static bool IsFrozen(EnemyAI enemy)
		{
			if ((Object)(object)enemy != (Object)null)
			{
				return Frozen.ContainsKey(enemy);
			}
			return false;
		}

		internal static bool IsEnemyInsideBarrier(EnemyAI enemy)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled.Value || !Active || !Plugin.FreezeEnemies.Value || (Object)(object)enemy == (Object)null)
			{
				return false;
			}
			PlayerControllerB localPlayer = GetLocalPlayer();
			if ((Object)(object)localPlayer == (Object)null || localPlayer.isPlayerDead || !localPlayer.isPlayerControlled)
			{
				return false;
			}
			return GetDistanceToEnemy(((Component)localPlayer).transform.position + Vector3.up * 1f, enemy) <= Plugin.Radius.Value;
		}

		private static bool IsPlayerHeldByEnemy(PlayerControllerB player)
		{
			Transform parent = ((Component)player).transform.parent;
			if ((Object)(object)parent != (Object)null)
			{
				return (Object)(object)((Component)parent).GetComponentInParent<EnemyAI>() != (Object)null;
			}
			return false;
		}

		internal static bool ShouldProtect(PlayerControllerB player)
		{
			if (!Plugin.Enabled.Value || !Active || !Plugin.BlockDamage.Value || (Object)(object)player == (Object)null)
			{
				return false;
			}
			if (!((NetworkBehaviour)player).IsSpawned || !((NetworkBehaviour)player).IsOwner || player.isPlayerDead || !player.isPlayerControlled || IsPlayerHeldByEnemy(player))
			{
				return false;
			}
			if (player.health <= 0)
			{
				return false;
			}
			PlayerControllerB localPlayer = GetLocalPlayer();
			if ((Object)(object)localPlayer != (Object)null && (Object)(object)player != (Object)(object)localPlayer)
			{
				return false;
			}
			return HasEnemyWithinRadius(player);
		}

		internal static void UnfreezeAll()
		{
			if (Frozen.Count == 0)
			{
				return;
			}
			foreach (EnemyAI item in new List<EnemyAI>(Frozen.Keys))
			{
				Unfreeze(item);
			}
			Frozen.Clear();
		}

		private static FrozenState Freeze(EnemyAI enemy)
		{
			//IL_000c: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			FrozenState frozenState = new FrozenState
			{
				Position = ((Component)enemy).transform.position,
				Rotation = ((Component)enemy).transform.rotation,
				Seen = true,
				WasEnabled = ((Behaviour)enemy).enabled
			};
			NavMeshAgent agent = enemy.agent;
			if ((Object)(object)agent != (Object)null)
			{
				frozenState.WasAgentStopped = agent.isStopped;
				agent.isStopped = true;
				agent.velocity = Vector3.zero;
				agent.ResetPath();
			}
			Rigidbody component = ((Component)enemy).GetComponent<Rigidbody>();
			if ((Object)(object)component != (Object)null)
			{
				frozenState.Body = component;
				frozenState.WasKinematic = component.isKinematic;
				component.isKinematic = true;
				component.velocity = Vector3.zero;
				component.angularVelocity = Vector3.zero;
			}
			Animator creatureAnimator = enemy.creatureAnimator;
			if ((Object)(object)creatureAnimator != (Object)null)
			{
				frozenState.HasAnimator = true;
				frozenState.AnimatorSpeed = creatureAnimator.speed;
				creatureAnimator.speed = 0f;
			}
			if (frozenState.WasEnabled)
			{
				((Behaviour)enemy).enabled = false;
			}
			if (Plugin.DebugLogging.Value)
			{
				Plugin.Log.LogDebug((object)$"Froze {((Object)enemy).name} at {frozenState.Position}.");
			}
			return frozenState;
		}

		private static void LockTransform(EnemyAI enemy, FrozenState state)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)enemy == (Object)null))
			{
				((Component)enemy).transform.position = state.Position;
				((Component)enemy).transform.rotation = state.Rotation;
				if ((Object)(object)enemy.agent != (Object)null)
				{
					enemy.agent.velocity = Vector3.zero;
				}
			}
		}

		private static void Unfreeze(EnemyAI enemy)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (!Frozen.TryGetValue(enemy, out var value))
			{
				return;
			}
			Frozen.Remove(enemy);
			if (!((Object)(object)enemy == (Object)null))
			{
				if ((Object)(object)value.Body != (Object)null)
				{
					value.Body.isKinematic = value.WasKinematic;
				}
				if (value.HasAnimator && (Object)(object)enemy.creatureAnimator != (Object)null)
				{
					enemy.creatureAnimator.speed = value.AnimatorSpeed;
				}
				if ((Object)(object)enemy.agent != (Object)null)
				{
					enemy.agent.isStopped = value.WasAgentStopped;
					enemy.agent.velocity = Vector3.zero;
				}
				if (value.WasEnabled && !((Behaviour)enemy).enabled)
				{
					((Behaviour)enemy).enabled = true;
				}
				if (Plugin.DebugLogging.Value)
				{
					Plugin.Log.LogDebug((object)("Unfroze " + ((Object)enemy).name + "."));
				}
			}
		}

		private static bool HasEnemyWithinRadius(PlayerControllerB player)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null || instance.SpawnedEnemies == null)
			{
				return false;
			}
			Vector3 point = ((Component)player).transform.position + Vector3.up * 1f;
			float value = Plugin.Radius.Value;
			foreach (EnemyAI spawnedEnemy in instance.SpawnedEnemies)
			{
				if (!((Object)(object)spawnedEnemy == (Object)null) && !spawnedEnemy.isEnemyDead && ((NetworkBehaviour)spawnedEnemy).IsSpawned && GetDistanceToEnemy(point, spawnedEnemy) <= value)
				{
					return true;
				}
			}
			return false;
		}

		private static float GetDistanceToEnemy(Vector3 point, EnemyAI enemy)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			float num = Vector3.Distance(point, ((Component)enemy).transform.position);
			Collider[] colliders = GetColliders(enemy);
			foreach (Collider val in colliders)
			{
				if (!((Object)(object)val == (Object)null) && val.enabled && !val.isTrigger)
				{
					Vector3 val2 = val.ClosestPoint(point);
					float num2 = Vector3.Distance(point, val2);
					if (num2 < num)
					{
						num = num2;
					}
				}
			}
			return num;
		}

		private static Collider[] GetColliders(EnemyAI enemy)
		{
			if (ColliderCache.TryGetValue(enemy, out var value) && value != null)
			{
				return value;
			}
			value = ((Component)enemy).GetComponentsInChildren<Collider>();
			ColliderCache[enemy] = value;
			return value;
		}

		private static void CleanupColliderCache()
		{
			List<EnemyAI> list = null;
			foreach (EnemyAI key in ColliderCache.Keys)
			{
				if ((Object)(object)key == (Object)null || key.isEnemyDead)
				{
					if (list == null)
					{
						list = new List<EnemyAI>();
					}
					list.Add(key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (EnemyAI item in list)
			{
				ColliderCache.Remove(item);
			}
		}

		private static void ShowHudMessage(bool active)
		{
			if (!Plugin.ShowHudMessage.Value || (Object)(object)HUDManager.Instance == (Object)null)
			{
				return;
			}
			try
			{
				HUDManager.Instance.DisplayTip("INFINITY", active ? "Barrier expanded" : "Barrier released", false, false, "GojoInfinityTip");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("Could not show HUD tip: " + ex.Message));
			}
		}
	}
	internal static class Patches
	{
		[HarmonyPrefix]
		internal static bool DamagePlayerPrefix(PlayerControllerB __instance)
		{
			return !InfinityService.ShouldProtect(__instance);
		}

		[HarmonyPrefix]
		internal static bool KillPlayerPrefix(PlayerControllerB __instance)
		{
			return !InfinityService.ShouldProtect(__instance);
		}

		[HarmonyPrefix]
		internal static bool DamagePlayerClientRpcPrefix(PlayerControllerB __instance)
		{
			return !InfinityService.ShouldProtect(__instance);
		}

		[HarmonyPrefix]
		internal static bool KillPlayerClientRpcPrefix(PlayerControllerB __instance)
		{
			return !InfinityService.ShouldProtect(__instance);
		}

		[HarmonyPrefix]
		internal static bool EnemyCollisionPrefix(EnemyAICollisionDetect __instance)
		{
			if ((Object)(object)__instance == (Object)null || (Object)(object)__instance.mainScript == (Object)null)
			{
				return true;
			}
			if (!InfinityService.IsFrozen(__instance.mainScript))
			{
				return !InfinityService.IsEnemyInsideBarrier(__instance.mainScript);
			}
			return false;
		}

		[HarmonyPrefix]
		internal static bool EnemyOnCollidePrefix(EnemyAI __instance)
		{
			if (!InfinityService.IsFrozen(__instance))
			{
				return !InfinityService.IsEnemyInsideBarrier(__instance);
			}
			return false;
		}
	}
	[BepInPlugin("com.gojoinfinity.client", "Gojo Infinity", "1.0.0")]
	[BepInProcess("Lethal Company.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.gojoinfinity.client";

		public const string PluginName = "Gojo Infinity";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> StartActive;

		internal static ConfigEntry<string> ToggleKey;

		internal static ConfigEntry<float> Radius;

		internal static ConfigEntry<bool> FreezeEnemies;

		internal static ConfigEntry<bool> BlockDamage;

		internal static ConfigEntry<bool> ShowHudMessage;

		internal static ConfigEntry<bool> DebugLogging;

		private Harmony _harmony;

		private bool _warnedInvalidKey;

		private void Awake()
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch for the mod.");
			StartActive = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "StartActive", true, "Whether Infinity is expanded when the game starts.");
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ToggleKey", "Digit4", "Input System key used to release/re-expand Infinity. Default is Digit4 (the 4 key). Numpad4 also works with the default. Examples: Digit4, Numpad4, F5.");
			Radius = ((BaseUnityPlugin)this).Config.Bind<float>("Barrier", "Radius", 2f, new ConfigDescription("Radius of the Infinity barrier in metres. Enemies inside are frozen and cannot hurt you.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>()));
			FreezeEnemies = ((BaseUnityPlugin)this).Config.Bind<bool>("Barrier", "FreezeEnemies", true, "Freeze enemies that enter the barrier.");
			BlockDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("Barrier", "BlockDamage", true, "Block damage while an enemy is inside the barrier.");
			ShowHudMessage = ((BaseUnityPlugin)this).Config.Bind<bool>("Effects", "ShowHudMessage", true, "Show a small HUD tip when Infinity is released or expanded.");
			DebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Advanced", "DebugLogging", false, "Log freeze/unfreeze events to the BepInEx console.");
			InfinityService.Active = StartActive.Value;
			_harmony = new Harmony("com.gojoinfinity.client");
			PatchMethod(typeof(PlayerControllerB), "DamagePlayer", "DamagePlayerPrefix");
			PatchMethod(typeof(PlayerControllerB), "KillPlayer", "KillPlayerPrefix");
			PatchMethod(typeof(PlayerControllerB), "DamagePlayerClientRpc", "DamagePlayerClientRpcPrefix");
			PatchMethod(typeof(PlayerControllerB), "KillPlayerClientRpc", "KillPlayerClientRpcPrefix");
			PatchMethod(typeof(EnemyAICollisionDetect), "OnTriggerStay", "EnemyCollisionPrefix");
			PatchMethod(typeof(EnemyAI), "OnCollideWithPlayer", "EnemyOnCollidePrefix");
			Log.LogInfo((object)("Gojo Infinity v1.0.0 loaded. Infinity is " + (InfinityService.Active ? "expanded" : "released") + "."));
		}

		private void Update()
		{
			if (IsTogglePressed())
			{
				PlayerControllerB localPlayer = InfinityService.GetLocalPlayer();
				if (!((Object)(object)localPlayer == (Object)null) && !localPlayer.isPlayerDead && localPlayer.isPlayerControlled && !localPlayer.isTypingChat && !localPlayer.inTerminalMenu && !Cursor.visible)
				{
					InfinityService.Toggle();
				}
			}
		}

		private void LateUpdate()
		{
			InfinityService.UpdateBarrier();
		}

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

		private bool IsTogglePressed()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			if (Keyboard.current == null)
			{
				return false;
			}
			Key val = ParseToggleKey();
			if ((int)val == 0)
			{
				return false;
			}
			if (((ButtonControl)Keyboard.current[val]).wasPressedThisFrame)
			{
				return true;
			}
			if ((int)val == 44)
			{
				return ((ButtonControl)Keyboard.current[(Key)88]).wasPressedThisFrame;
			}
			return false;
		}

		private Key ParseToggleKey()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			string text = ToggleKey.Value;
			if (string.IsNullOrWhiteSpace(text))
			{
				text = "Digit4";
			}
			if (text == "4")
			{
				text = "Digit4";
			}
			if (Enum.TryParse<Key>(text, ignoreCase: true, out Key result) && (int)result != 0)
			{
				return result;
			}
			if (!_warnedInvalidKey)
			{
				_warnedInvalidKey = true;
				Log.LogWarning((object)("Unknown ToggleKey '" + ToggleKey.Value + "'; falling back to Digit4 (the 4 key)."));
			}
			return (Key)44;
		}

		private void PatchMethod(Type type, string methodName, string prefixName)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogWarning((object)("Could not find " + type.Name + "." + methodName + "; that patch was skipped."));
				return;
			}
			try
			{
				_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Patches), prefixName, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)("Patched " + type.Name + "." + methodName + "."));
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Failed to patch {type.Name}.{methodName}: {arg}");
			}
		}
	}
}