Decompiled source of DynamicShipDoorHealth v1.0.0

DynamicShipDoorHealth.dll

Decompiled a day ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DynamicShipDoorHealth.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[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("Khameli0n")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Standalone Dynamic Ship Door Health, Monster Barge-Ins, and Closed-Door Enemy Barrier mod for Lethal Company.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DynamicShipDoorHealth")]
[assembly: AssemblyTitle("DynamicShipDoorHealth")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 DynamicShipDoorHealth
{
	public static class Configuration
	{
		public static ConfigEntry<bool> ShipDoorInfinitePower { get; private set; }

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

		public static void Init(ConfigFile cfg)
		{
			ShipDoorInfinitePower = cfg.Bind<bool>("ShipDoor", "ShipDoorInfinitePower", true, "Removes the ship door power timer and overheating, replacing it with a dynamic integrity health pool that monsters can batter down and barge open.");
			EnableDoorwayEnemyBarrier = cfg.Bind<bool>("ShipDoor", "EnableDoorwayEnemyBarrier", true, "Spawns a solid collider and NavMesh carving obstacle across the closed ship doorway so enemies cannot walk through while battering the door.");
		}
	}
	[BepInPlugin("com.khameli0n.dynamicshipdoorhealth", "DynamicShipDoorHealth", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PLUGIN_GUID = "com.khameli0n.dynamicshipdoorhealth";

		public const string PLUGIN_NAME = "DynamicShipDoorHealth";

		public const string PLUGIN_VERSION = "1.0.0";

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		public static Harmony HarmonyInstance { get; private set; }

		private void Awake()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Configuration.Init(((BaseUnityPlugin)this).Config);
			HarmonyInstance = new Harmony("com.khameli0n.dynamicshipdoorhealth");
			try
			{
				HarmonyInstance.CreateClassProcessor(typeof(ShipDoorPatches)).Patch();
				Log.LogInfo((object)string.Format("{0} v{1} loaded (DoorHealth={2}, DoorwayBarrier={3}).", "DynamicShipDoorHealth", "1.0.0", Configuration.ShipDoorInfinitePower.Value, Configuration.EnableDoorwayEnemyBarrier.Value));
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("Failed to apply patches for {0}: {1}", "DynamicShipDoorHealth", arg));
			}
		}
	}
}
namespace DynamicShipDoorHealth.Patches
{
	[HarmonyPatch]
	public static class ShipDoorPatches
	{
		private static bool hasLoggedDoorHeartbeat;

		private static bool hasLoggedBarrierHeartbeat;

		private static GameObject doorBarrierObject;

		private static NavMeshObstacle doorNavObstacle;

		private static BoxCollider doorBarrierCollider;

		private static float impactAudioTimer;

		private static float doorScanTimer;

		private static int cachedAttackingCount;

		private static float cachedDps;

		private static int lastDisplayedMeter = -1;

		private static readonly MethodInfo SetScreenDisplayMethod = typeof(HangarShipDoor).GetMethod("SetScreenDisplay", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		[HarmonyPatch(typeof(HangarShipDoor), "Update")]
		[HarmonyPrefix]
		public static bool HangarShipDoor_Update_Prefix(HangarShipDoor __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return false;
			}
			if (!Configuration.ShipDoorInfinitePower.Value)
			{
				return true;
			}
			if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.inShipPhase)
			{
				__instance.overheated = false;
				__instance.doorPower = 1f;
				DeactivateDoorBarrier();
				UpdateDoorPowerDisplay(__instance, 100);
				return true;
			}
			if (!hasLoggedDoorHeartbeat)
			{
				hasLoggedDoorHeartbeat = true;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"[ShipDoor] Diagnostic Heartbeat: Dynamic door integrity health pool & monster battering active.");
				}
			}
			try
			{
				SetScreenDisplayMethod?.Invoke(__instance, null);
			}
			catch
			{
			}
			__instance.overheated = false;
			__instance.buttonsEnabled = true;
			if ((Object)(object)__instance.triggerScript != (Object)null)
			{
				__instance.triggerScript.interactable = true;
			}
			bool flag = (Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.shipHasLanded;
			if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.hangarDoorsClosed && flag)
			{
				UpdateDoorBarrierState();
				doorScanTimer += Time.deltaTime;
				if (doorScanTimer >= 0.15f)
				{
					doorScanTimer = 0f;
					ScanNearbyAttackingEnemies(__instance);
				}
				if (cachedAttackingCount > 0)
				{
					__instance.doorPower = Mathf.Clamp01(__instance.doorPower - cachedDps * Time.deltaTime);
					PlayDoorImpactFeedback();
					if (__instance.doorPower <= 0f)
					{
						TriggerBargeInOpen(__instance);
					}
				}
				else if (__instance.doorPower < 1f)
				{
					__instance.doorPower = Mathf.Clamp01(__instance.doorPower + 0.05f * Time.deltaTime);
				}
			}
			else
			{
				__instance.doorPower = 1f;
				DeactivateDoorBarrier();
			}
			UpdateDoorPowerDisplay(__instance, Mathf.RoundToInt(__instance.doorPower * 100f));
			return false;
		}

		[HarmonyPatch(typeof(StartOfRound), "SetShipDoorsClosed")]
		[HarmonyPostfix]
		public static void SetShipDoorsClosed_Postfix(bool closed)
		{
			if (closed && Configuration.ShipDoorInfinitePower.Value)
			{
				lastDisplayedMeter = -1;
				HangarShipDoor val = Object.FindObjectOfType<HangarShipDoor>();
				if ((Object)(object)val != (Object)null)
				{
					val.doorPower = 1f;
					UpdateDoorPowerDisplay(val, 100);
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "SetShipDoorsOverheatServerRpc")]
		[HarmonyPrefix]
		public static bool CancelOverheatServerRpc()
		{
			return !Configuration.ShipDoorInfinitePower.Value;
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		public static void StartOfRound_Start_Postfix()
		{
			ResetDoorTracking();
			if (!Configuration.EnableDoorwayEnemyBarrier.Value)
			{
				return;
			}
			try
			{
				SetupDoorwayBarrier();
				if (!hasLoggedBarrierHeartbeat)
				{
					hasLoggedBarrierHeartbeat = true;
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)"[ShipDoor] Diagnostic Heartbeat: Closed-doorway NavMesh obstacle & collider barrier initialized.");
					}
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"[ShipDoor] Error setting up doorway barrier: {arg}");
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "ShipLeave")]
		[HarmonyPostfix]
		public static void StartOfRound_ShipLeave_Postfix()
		{
			ResetDoorTracking();
			DeactivateDoorBarrier();
		}

		private static void ResetDoorTracking()
		{
			impactAudioTimer = 0f;
			doorScanTimer = 0f;
			cachedAttackingCount = 0;
			cachedDps = 0f;
			lastDisplayedMeter = -1;
		}

		private static void ScanNearbyAttackingEnemies(HangarShipDoor door)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			cachedAttackingCount = 0;
			cachedDps = 0f;
			Vector3 doorCheckPosition = GetDoorCheckPosition(door);
			EnemyAI[] array = Object.FindObjectsOfType<EnemyAI>();
			if (array == null)
			{
				return;
			}
			EnemyAI[] array2 = array;
			foreach (EnemyAI val in array2)
			{
				if (!((Object)(object)val == (Object)null) && !val.isEnemyDead && ((Component)val).gameObject.activeInHierarchy && val.isOutside && Vector3.Distance(((Component)val).transform.position, doorCheckPosition) <= 6.5f)
				{
					cachedAttackingCount++;
					cachedDps += GetEnemyDoorDamagePerSecond(val);
				}
			}
		}

		private static Vector3 GetDoorCheckPosition(HangarShipDoor door)
		{
			//IL_0057: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)StartOfRound.Instance != (Object)null)
			{
				if ((Object)(object)StartOfRound.Instance.shipDoorNode != (Object)null)
				{
					return StartOfRound.Instance.shipDoorNode.position;
				}
				if ((Object)(object)StartOfRound.Instance.outsideDoorPosition != (Object)null)
				{
					return StartOfRound.Instance.outsideDoorPosition.position;
				}
			}
			return ((Component)door).transform.position;
		}

		private static float GetEnemyDoorDamagePerSecond(EnemyAI enemy)
		{
			string text = (((Object)(object)enemy.enemyType != (Object)null) ? enemy.enemyType.enemyName : string.Empty).ToLower();
			if (text.Contains("mouth") || text.Contains("dog") || text.Contains("forest") || text.Contains("giant") || text.Contains("worm") || text.Contains("radmech") || text.Contains("mech") || text.Contains("crawler") || text.Contains("thumper"))
			{
				return 0.12f;
			}
			if (text.Contains("mask") || text.Contains("baboon") || text.Contains("spider") || text.Contains("nutcracker") || text.Contains("butler") || text.Contains("centipede"))
			{
				return 0.07f;
			}
			return 0.04f;
		}

		private static void PlayDoorImpactFeedback()
		{
			impactAudioTimer += Time.deltaTime;
			if (impactAudioTimer < 0.5f)
			{
				return;
			}
			impactAudioTimer = 0f;
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.shipDoorAudioSource != (Object)null && instance.shutDoorMetal != null && instance.shutDoorMetal.Length != 0)
			{
				AudioClip val = instance.shutDoorMetal[Random.Range(0, instance.shutDoorMetal.Length)];
				instance.shipDoorAudioSource.PlayOneShot(val, 1f);
			}
			PlayerControllerB val2 = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)val2 != (Object)null && val2.isInHangarShipRoom)
			{
				HUDManager instance2 = HUDManager.Instance;
				if (instance2 != null)
				{
					instance2.ShakeCamera((ScreenShakeType)0);
				}
			}
		}

		private static void TriggerBargeInOpen(HangarShipDoor door)
		{
			door.PlayDoorAnimation(false);
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsServer)
			{
				StartOfRound.Instance.SetDoorsClosedServerRpc(false);
			}
			else
			{
				StartOfRound.Instance.SetShipDoorsClosed(false);
			}
			DeactivateDoorBarrier();
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.shipDoorAudioSource != (Object)null && (Object)(object)instance.openingHangarDoorAudio != (Object)null)
			{
				instance.shipDoorAudioSource.PlayOneShot(instance.openingHangarDoorAudio, 1f);
			}
			HUDManager instance2 = HUDManager.Instance;
			if (instance2 != null)
			{
				instance2.ShakeCamera((ScreenShakeType)1);
			}
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"[ShipDoor] Diagnostic Heartbeat: Monsters BARGED OPEN the ship door! Door integrity 0%.");
			}
		}

		private static void UpdateDoorPowerDisplay(HangarShipDoor door, int percent)
		{
			if (lastDisplayedMeter != percent)
			{
				lastDisplayedMeter = percent;
				if ((Object)(object)door.doorPowerDisplay != (Object)null)
				{
					((TMP_Text)door.doorPowerDisplay).text = $"{percent}%";
				}
			}
		}

		private static void SetupDoorwayBarrier()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)StartOfRound.Instance == (Object)null) && !((Object)(object)doorBarrierObject != (Object)null))
			{
				Transform val = StartOfRound.Instance.shipDoorNode ?? StartOfRound.Instance.outsideDoorPosition;
				if (!((Object)(object)val == (Object)null))
				{
					doorBarrierObject = new GameObject("DynamicShipDoor_EnemyBarrier");
					doorBarrierObject.transform.SetParent(StartOfRound.Instance.elevatorTransform, false);
					doorBarrierObject.transform.position = val.position;
					doorBarrierObject.transform.rotation = val.rotation;
					doorBarrierObject.layer = LayerMask.NameToLayer("Room");
					doorNavObstacle = doorBarrierObject.AddComponent<NavMeshObstacle>();
					doorNavObstacle.carving = true;
					doorNavObstacle.carveOnlyStationary = false;
					doorNavObstacle.shape = (NavMeshObstacleShape)1;
					doorNavObstacle.size = new Vector3(3.2f, 3.5f, 0.8f);
					doorNavObstacle.center = Vector3.up * 1.5f;
					doorBarrierCollider = doorBarrierObject.AddComponent<BoxCollider>();
					doorBarrierCollider.size = new Vector3(3.2f, 3.5f, 0.8f);
					doorBarrierCollider.center = Vector3.up * 1.5f;
					((Collider)doorBarrierCollider).isTrigger = false;
					doorBarrierObject.SetActive(false);
				}
			}
		}

		private static void UpdateDoorBarrierState()
		{
			if (!Configuration.EnableDoorwayEnemyBarrier.Value || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				return;
			}
			if ((Object)(object)doorBarrierObject == (Object)null)
			{
				SetupDoorwayBarrier();
			}
			if ((Object)(object)doorBarrierObject != (Object)null)
			{
				bool hangarDoorsClosed = StartOfRound.Instance.hangarDoorsClosed;
				if (doorBarrierObject.activeSelf != hangarDoorsClosed)
				{
					doorBarrierObject.SetActive(hangarDoorsClosed);
				}
			}
		}

		private static void DeactivateDoorBarrier()
		{
			if ((Object)(object)doorBarrierObject != (Object)null && doorBarrierObject.activeSelf)
			{
				doorBarrierObject.SetActive(false);
			}
		}
	}
}