Decompiled source of CCTVBodyAnchorFix v1.0.0

CCTVBodyAnchorFix.dll

Decompiled 2 hours ago
using System;
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 UnityEngine;

[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("CCTVBodyAnchorFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CCTVBodyAnchorFix")]
[assembly: AssemblyTitle("CCTVBodyAnchorFix")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace CCTVBodyAnchorFix;

[DefaultExecutionOrder(32001)]
internal sealed class CameraBodyAnchorGuard : MonoBehaviour
{
	private const float ReferenceFollowRadiusM = 0.05f;

	private const float ReferenceFollowRate = 0.35f;

	private const float PostureSettleSeconds = 0.6f;

	private const float RecentExitSeconds = 10f;

	private const float HoldScanIntervalSeconds = 0.5f;

	private const float LogIntervalSeconds = 5f;

	private PlayerControllerB _player;

	private MonoBehaviour _hold;

	private Vector3 _standingReference;

	private Vector3 _crouchingReference;

	private bool _hasStandingReference;

	private bool _hasCrouchingReference;

	private bool _sessionWasActive;

	private bool _sessionSeen;

	private float _sessionEndedAt = float.NegativeInfinity;

	private bool _posture;

	private float _postureChangedAt = float.NegativeInfinity;

	private float _driftingSince = -1f;

	private float _startedAt;

	private float _nextHoldScanAt;

	private float _nextStopAttemptAt;

	private float _nextLogAt;

	private void Awake()
	{
		_startedAt = Time.unscaledTime;
	}

	private void LateUpdate()
	{
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_020e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0210: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: Unknown result type (might be due to invalid IL or missing references)
		//IL_0217: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.Enabled.Value)
		{
			return;
		}
		LethalCctvProbe.Resolve();
		if (!LethalCctvProbe.Found)
		{
			return;
		}
		PlayerControllerB val = ResolvePlayer();
		if ((Object)(object)val == (Object)null || val.isPlayerDead)
		{
			ResetDrift();
			return;
		}
		Transform cameraContainerTransform = val.cameraContainerTransform;
		if ((Object)(object)cameraContainerTransform == (Object)null)
		{
			return;
		}
		float unscaledTime = Time.unscaledTime;
		if (LethalCctvProbe.IsSessionActive())
		{
			_sessionWasActive = true;
			_sessionSeen = true;
			ResetDrift();
			return;
		}
		if (_sessionWasActive)
		{
			_sessionWasActive = false;
			_sessionEndedAt = unscaledTime;
			_hold = null;
		}
		if (val.inSpecialInteractAnimation || val.enteringSpecialAnimation)
		{
			ResetDrift();
			return;
		}
		if (unscaledTime >= _nextHoldScanAt)
		{
			_nextHoldScanAt = unscaledTime + 0.5f;
			_hold = LethalCctvProbe.FindActiveHold(cameraContainerTransform);
		}
		if ((Object)(object)_hold != (Object)null)
		{
			float num = Mathf.Clamp(Plugin.StaleHoldSeconds.Value, 0f, 10f);
			float num2 = (_sessionSeen ? _sessionEndedAt : _startedAt);
			if (num > 0f && unscaledTime - num2 >= num && unscaledTime >= _nextStopAttemptAt)
			{
				_nextStopAttemptAt = unscaledTime + 0.5f;
				if (LethalCctvProbe.TryStopHold(_hold, out var stoppedType))
				{
					_hold = null;
					Log("Stopped a LethalCCTV camera hold that was still running after the station closed (" + stoppedType + ").");
				}
			}
			if ((Object)(object)_hold != (Object)null)
			{
				ResetDrift();
				return;
			}
		}
		bool isCrouching = val.isCrouching;
		if (isCrouching != _posture)
		{
			_posture = isCrouching;
			_postureChangedAt = unscaledTime;
			ResetDrift();
		}
		bool flag = unscaledTime - _postureChangedAt >= 0.6f;
		bool num3 = (isCrouching ? _hasCrouchingReference : _hasStandingReference);
		Vector3 val2 = (isCrouching ? _crouchingReference : _standingReference);
		Vector3 localPosition = cameraContainerTransform.localPosition;
		if (!num3)
		{
			if ((!_sessionSeen || !(unscaledTime - _sessionEndedAt < 10f)) && flag)
			{
				SetReference(isCrouching, localPosition);
			}
		}
		else
		{
			if (!flag)
			{
				return;
			}
			Vector3 val3 = localPosition - val2;
			float magnitude = ((Vector3)(ref val3)).magnitude;
			float num4 = Mathf.Clamp(Plugin.SnapDistanceMeters.Value, 0.05f, 5f);
			if (magnitude > num4)
			{
				if (_driftingSince < 0f)
				{
					_driftingSince = unscaledTime;
				}
				float num5 = Mathf.Clamp(Plugin.CorrectionDelaySeconds.Value, 0f, 5f);
				if (unscaledTime - _driftingSince >= num5)
				{
					cameraContainerTransform.localPosition = val2;
					ResetDrift();
					Log("Re-anchored the camera to the body; it was " + magnitude.ToString("0.00") + " m off.");
				}
			}
			else
			{
				ResetDrift();
				if (magnitude <= 0.05f)
				{
					SetReference(isCrouching, Vector3.Lerp(val2, localPosition, 0.35f));
				}
			}
		}
	}

	private PlayerControllerB ResolvePlayer()
	{
		GameNetworkManager instance = GameNetworkManager.Instance;
		PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null);
		if ((Object)(object)val != (Object)(object)_player)
		{
			_player = val;
			_hold = null;
			_hasStandingReference = false;
			_hasCrouchingReference = false;
			_sessionWasActive = false;
			_sessionSeen = false;
			_sessionEndedAt = float.NegativeInfinity;
			_posture = false;
			_postureChangedAt = float.NegativeInfinity;
			ResetDrift();
		}
		return _player;
	}

	private void SetReference(bool crouching, Vector3 value)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		if (crouching)
		{
			_crouchingReference = value;
			_hasCrouchingReference = true;
		}
		else
		{
			_standingReference = value;
			_hasStandingReference = true;
		}
	}

	private void ResetDrift()
	{
		_driftingSince = -1f;
	}

	private void Log(string message)
	{
		if (Plugin.LogCorrections.Value && !(Time.unscaledTime < _nextLogAt))
		{
			_nextLogAt = Time.unscaledTime + 5f;
			if (Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)("[CCTVBodyAnchorFix] " + message));
			}
		}
	}
}
internal static class LethalCctvProbe
{
	private const string MonitorFocusTypeName = "Y4NGZCompany.ShipSystems.Surveillance.MonitorFocus";

	private const string StabilizerSimpleName = "CCTVLocalCameraPositionStabilizer";

	private const BindingFlags StaticFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

	private static Type _focusType;

	private static PropertyInfo _isFocused;

	private static PropertyInfo _isExitInProgress;

	private static PropertyInfo _isEntrySettleActive;

	private static float _nextResolveAt;

	internal static bool Found => _focusType != null;

	internal static void Resolve()
	{
		if (_focusType != null || Time.unscaledTime < _nextResolveAt)
		{
			return;
		}
		_nextResolveAt = Time.unscaledTime + 1f;
		Assembly[] assemblies;
		try
		{
			assemblies = AppDomain.CurrentDomain.GetAssemblies();
		}
		catch
		{
			return;
		}
		for (int i = 0; i < assemblies.Length; i++)
		{
			if (!(_focusType == null))
			{
				break;
			}
			try
			{
				Type type = assemblies[i].GetType("Y4NGZCompany.ShipSystems.Surveillance.MonitorFocus", throwOnError: false);
				if (!(type == null))
				{
					_isFocused = type.GetProperty("IsFocused", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					_isExitInProgress = type.GetProperty("IsFocusExitInProgress", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					_isEntrySettleActive = type.GetProperty("IsEntryPoseSettleActive", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (_isFocused != null)
					{
						_focusType = type;
					}
				}
			}
			catch
			{
			}
		}
	}

	internal static bool IsSessionActive()
	{
		if (_focusType == null)
		{
			return false;
		}
		if (!ReadBool(_isFocused) && !ReadBool(_isExitInProgress))
		{
			return ReadBool(_isEntrySettleActive);
		}
		return true;
	}

	internal static MonoBehaviour FindActiveHold(Transform container)
	{
		if ((Object)(object)container == (Object)null)
		{
			return null;
		}
		MonoBehaviour[] components;
		try
		{
			components = ((Component)container).GetComponents<MonoBehaviour>();
		}
		catch
		{
			return null;
		}
		foreach (MonoBehaviour val in components)
		{
			if (!((Object)(object)val == (Object)null) && !(((object)val).GetType().Name != "CCTVLocalCameraPositionStabilizer") && !ReadInstanceBool(((object)val).GetType(), val, "IsStopped"))
			{
				return val;
			}
		}
		return null;
	}

	internal static bool TryStopHold(MonoBehaviour hold, out string stoppedType)
	{
		stoppedType = null;
		if ((Object)(object)hold == (Object)null)
		{
			return false;
		}
		Type type = ((object)hold).GetType();
		MethodInfo method = type.GetMethod("StopNow", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		if (method == null)
		{
			return false;
		}
		try
		{
			method.Invoke(hold, null);
			stoppedType = type.FullName;
			return true;
		}
		catch
		{
			return false;
		}
	}

	private static bool ReadBool(PropertyInfo property)
	{
		if (property == null)
		{
			return false;
		}
		try
		{
			object value = property.GetValue(null, null);
			return value is bool && (bool)value;
		}
		catch
		{
			return false;
		}
	}

	private static bool ReadInstanceBool(Type type, object instance, string name)
	{
		try
		{
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property == null)
			{
				return false;
			}
			object value = property.GetValue(instance, null);
			return value is bool && (bool)value;
		}
		catch
		{
			return false;
		}
	}
}
[BepInPlugin("com.cctvbodyanchorfix.lethalcompany", "CCTV Camera Body Anchor Fix", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	public const string PluginGuid = "com.cctvbodyanchorfix.lethalcompany";

	public const string PluginName = "CCTV Camera Body Anchor Fix";

	public const string PluginVersion = "1.0.0";

	private const string LethalCctvGuid = "com.y4ngz.company.lethalcctv";

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<float> SnapDistanceMeters;

	internal static ConfigEntry<float> CorrectionDelaySeconds;

	internal static ConfigEntry<float> StaleHoldSeconds;

	internal static ConfigEntry<bool> LogCorrections;

	internal static Plugin Instance { get; private set; }

	internal static ManualLogSource Log { get; private set; }

	private void Awake()
	{
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Keep the local first-person camera attached to the player body. When LethalCCTV leaves the camera container parked away from the body after a station or mainframe session, it is moved back. On by default.");
		SnapDistanceMeters = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Maximum Camera Offset (m)", 0.3f, "How far, in metres, the camera may sit from its normal body-local position before it counts as separated. Head bob and crouch sit well inside this. 0.05 to 5, default 0.3.");
		CorrectionDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Correction Delay (s)", 0.75f, "How long the camera must stay separated before it is moved back, so the CCTV exit animation is never cut short. 0 to 5, default 0.75.");
		StaleHoldSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Stale Hold Cleanup (s)", 2f, "After the station or mainframe closes, wait this long before stopping a leftover LethalCCTV camera hold that is still running. 0 disables the cleanup, default 2.");
		LogCorrections = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Log Corrections", true, "Write one line to the BepInEx log when the camera is re-anchored or a stale hold is stopped. On by default.");
		LethalCctvProbe.Resolve();
		GameObject val = new GameObject("CCTVBodyAnchorFix_Host")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)val);
		val.AddComponent<CameraBodyAnchorGuard>();
		((BaseUnityPlugin)this).Logger.LogInfo((object)("CCTV Camera Body Anchor Fix 1.0.0 loaded. LethalCCTV station state: " + (LethalCctvProbe.Found ? "detected." : "not detected, idle until it is.")));
	}
}