Decompiled source of BackroomsNoclip v0.1.0

BackroomsNoclip/BackroomsNoclip.dll

Decompiled 4 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
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("BackroomsNoclip")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BackroomsNoclip")]
[assembly: AssemblyTitle("BackroomsNoclip")]
[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 BackroomsNoclip
{
	[BepInPlugin("com.backroomsnoclip", "Backrooms Noclip", "0.1.0")]
	public sealed class BackroomsNoclipPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.backroomsnoclip";

		public const string PluginName = "Backrooms Noclip";

		public const string PluginVersion = "0.1.0";

		private const string MessageName = "BackroomsNoclip.BeginFall.v1";

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

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

		private ConfigEntry<float> _chance;

		private ConfigEntry<float> _cooldown;

		private ConfigEntry<float> _fallDuration;

		private ConfigEntry<bool> _interior;

		private ConfigEntry<bool> _exterior;

		private NetworkManager _registeredManager;

		private float _nextAttemptAt;

		private bool _sessionTimerStarted;

		private readonly HashSet<int> _activePlayerIndices = new HashSet<int>();

		private void Awake()
		{
			_chance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Chance", 0.2f, "Chance percentual por tentativa (0.2 = 0,2%).");
			_cooldown = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Cooldown", 15f, "Intervalo, em segundos, entre tentativas do host.");
			_fallDuration = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FallDuration", 0.5f, "Tempo, em segundos, que o jogador cai antes do teleporte.");
			_interior = ((BaseUnityPlugin)this).Config.Bind<bool>("Locations", "Interior", true, "Permite eventos dentro das instalações.");
			_exterior = ((BaseUnityPlugin)this).Config.Bind<bool>("Locations", "Exterior", false, "Permite eventos do lado de fora das instalações (a nave é excluída).");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Backrooms Noclip carregado. O host controla os sorteios.");
		}

		private void Update()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			UpdateMessageRegistration(singleton);
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				_sessionTimerStarted = false;
			}
			else if (singleton.IsServer)
			{
				if (!_sessionTimerStarted)
				{
					_nextAttemptAt = Time.time + Mathf.Max(0f, _cooldown.Value);
					_sessionTimerStarted = true;
				}
				else if (!(Time.time < _nextAttemptAt))
				{
					_nextAttemptAt = Time.time + Mathf.Max(0.1f, _cooldown.Value);
					PerformHostAttempt(singleton);
				}
			}
		}

		private void UpdateMessageRegistration(NetworkManager manager)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			if ((Object)(object)_registeredManager == (Object)(object)manager)
			{
				return;
			}
			UnregisterMessageHandler();
			if ((Object)(object)manager == (Object)null || !manager.IsListening)
			{
				return;
			}
			try
			{
				manager.CustomMessagingManager.RegisterNamedMessageHandler("BackroomsNoclip.BeginFall.v1", new HandleNamedMessageDelegate(OnFallMessage));
				_registeredManager = manager;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Canal multiplayer do Backrooms Noclip registrado.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Não foi possível registrar o canal multiplayer: " + ex.Message));
			}
		}

		private void UnregisterMessageHandler()
		{
			if ((Object)(object)_registeredManager == (Object)null)
			{
				return;
			}
			try
			{
				if (_registeredManager.IsListening)
				{
					_registeredManager.CustomMessagingManager.UnregisterNamedMessageHandler("BackroomsNoclip.BeginFall.v1");
				}
			}
			catch
			{
			}
			_registeredManager = null;
		}

		private void OnFallMessage(ulong senderClientId, FastBufferReader reader)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || senderClientId != 0L)
			{
				return;
			}
			try
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				Array playerArray = GetPlayerArray();
				if (playerArray != null && num >= 0 && num < playerArray.Length)
				{
					object value = playerArray.GetValue(num);
					if (value != null && IsOwnedByLocalClient(value, singleton))
					{
						BeginLocalFall(num, value);
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Falha ao processar pedido de noclip: " + ex));
			}
		}

		private unsafe void PerformHostAttempt(NetworkManager manager)
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			Array playerArray = GetPlayerArray();
			if (playerArray == null || playerArray.Length == 0)
			{
				return;
			}
			List<int> list = new List<int>();
			for (int i = 0; i < playerArray.Length; i++)
			{
				object value = playerArray.GetValue(i);
				if (value != null && IsEligible(value, requireGrounded: false, checkLocation: true))
				{
					list.Add(i);
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			int num = list[Random.Range(0, list.Count)];
			float num2 = Mathf.Clamp(_chance.Value, 0f, 100f);
			if (Random.value >= num2 / 100f)
			{
				return;
			}
			object value2 = playerArray.GetValue(num);
			if (!TryGetOwnerClientId(value2, out var ownerClientId))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Não foi possível descobrir o dono do jogador selecionado.");
				return;
			}
			if (ownerClientId == manager.LocalClientId)
			{
				BeginLocalFall(num, value2);
				return;
			}
			try
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
					manager.CustomMessagingManager.SendNamedMessage("BackroomsNoclip.BeginFall.v1", ownerClientId, val, (NetworkDelivery)2);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Noclip sorteado para o jogador de índice " + num + ". Pedido enviado ao cliente " + ownerClientId + "."));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Não foi possível enviar o evento ao cliente: " + ex));
			}
		}

		private bool IsEligible(object player, bool requireGrounded, bool checkLocation)
		{
			if (!ReadBool(player, "isPlayerControlled", fallback: false) || ReadBool(player, "isPlayerDead", fallback: true))
			{
				return false;
			}
			if (requireGrounded && (ReadBool(player, "isClimbingLadder", fallback: false) || ReadBool(player, "inSpecialInteractAnimation", fallback: false) || ReadBool(player, "isUnderwater", fallback: false) || ReadBool(player, "isInElevator", fallback: false) || ReadBool(player, "isInHangarShipRoom", fallback: false) || ReadBool(player, "isFreeCamera", fallback: false) || ReadBool(player, "isPlayerSliding", fallback: false) || ReadBool(player, "jetpackControls", fallback: false) || ReadBool(player, "inVehicleAnimation", fallback: false) || ReadBool(player, "disableMoveInput", fallback: false) || ReadBool(player, "isJumping", fallback: false) || ReadBool(player, "isFallingFromJump", fallback: false) || ReadBool(player, "isFallingNoJump", fallback: false) || ReadBool(player, "teleportedLastFrame", fallback: false)))
			{
				return false;
			}
			bool flag = ReadBool(player, "isInsideFactory", fallback: false);
			bool flag2 = ReadBool(player, "isInHangarShipRoom", fallback: false) || ReadBool(player, "isInElevator", fallback: false);
			bool flag3 = !flag && !flag2;
			if (checkLocation)
			{
				if (flag && !_interior.Value)
				{
					return false;
				}
				if (flag3 && !_exterior.Value)
				{
					return false;
				}
				if (!flag && !flag3)
				{
					return false;
				}
			}
			if (!requireGrounded)
			{
				return true;
			}
			CharacterController playerController = GetPlayerController(player);
			if ((Object)(object)playerController != (Object)null && ((Collider)playerController).enabled)
			{
				return playerController.isGrounded;
			}
			return false;
		}

		private void BeginLocalFall(int playerIndex, object player)
		{
			if (_activePlayerIndices.Contains(playerIndex))
			{
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !IsOwnedByLocalClient(player, singleton) || !IsEligible(player, requireGrounded: true, checkLocation: false))
			{
				return;
			}
			if (!TryResolveBackroomsTeleport(out var instance, out var method, out var error))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("BackroomsFixed não está pronto para receber o teleporte: " + error));
				return;
			}
			CharacterController playerController = GetPlayerController(player);
			if (!((Object)(object)playerController == (Object)null))
			{
				Collider val = FindFloorCollider(player, playerController);
				if ((Object)(object)val == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Noclip cancelado: não encontrei um colisor de piso seguro abaixo do jogador.");
					return;
				}
				_activePlayerIndices.Add(playerIndex);
				((MonoBehaviour)this).StartCoroutine(FallThenTeleport(playerIndex, player, playerController, val, instance, method));
			}
		}

		private IEnumerator FallThenTeleport(int playerIndex, object player, CharacterController controller, Collider floor, object backroomsInstance, MethodInfo teleportMethod)
		{
			Component playerComponent = (Component)((player is Component) ? player : null);
			if ((Object)(object)playerComponent == (Object)null || (Object)(object)controller == (Object)null || (Object)(object)floor == (Object)null)
			{
				_activePlayerIndices.Remove(playerIndex);
				yield break;
			}
			Vector3 startPosition = playerComponent.transform.position;
			bool wasAlreadyIgnored = false;
			bool collisionChanged = false;
			float oldFallValue = ReadFloat(player, "fallValue", 0f);
			float oldFallValueUncapped = ReadFloat(player, "fallValueUncapped", 0f);
			try
			{
				wasAlreadyIgnored = Physics.GetIgnoreCollision((Collider)(object)controller, floor);
				if (!wasAlreadyIgnored)
				{
					Physics.IgnoreCollision((Collider)(object)controller, floor, true);
					collisionChanged = true;
				}
				SetFloat(player, "fallValue", Mathf.Min(oldFallValue, -2f));
				SetFloat(player, "fallValueUncapped", Mathf.Min(oldFallValueUncapped, -2f));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Não foi possível iniciar a queda controlada: " + ex));
				RestoreFallState(controller, floor, collisionChanged, wasAlreadyIgnored, player, oldFallValue, oldFallValueUncapped);
				_activePlayerIndices.Remove(playerIndex);
				yield break;
			}
			yield return (object)new WaitForSecondsRealtime(Mathf.Clamp(_fallDuration.Value, 0.05f, 5f));
			bool flag = false;
			try
			{
				teleportMethod.Invoke(backroomsInstance, new object[1] { playerIndex });
				flag = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("BackroomsFixed recebeu o pedido de teleporte do jogador " + playerIndex + "."));
			}
			catch (TargetInvocationException ex2)
			{
				Exception? obj = ex2.InnerException ?? ex2;
				((BaseUnityPlugin)this).Logger.LogError((object)("O ServerRpc do BackroomsFixed falhou: " + obj));
			}
			catch (Exception ex3)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Falha ao chamar o ServerRpc do BackroomsFixed: " + ex3));
			}
			if (flag)
			{
				float deadline = Time.realtimeSinceStartup + 4f;
				while (Time.realtimeSinceStartup < deadline && (Object)(object)playerComponent != (Object)null && !(Vector3.Distance(playerComponent.transform.position, startPosition) > 2f))
				{
					yield return null;
				}
			}
			else if ((Object)(object)playerComponent != (Object)null)
			{
				playerComponent.transform.position = startPosition + Vector3.up * 0.15f;
			}
			RestoreFallState(controller, floor, collisionChanged, wasAlreadyIgnored, player, oldFallValue, oldFallValueUncapped);
			_activePlayerIndices.Remove(playerIndex);
		}

		private static void RestoreFallState(CharacterController controller, Collider floor, bool collisionChanged, bool wasAlreadyIgnored, object player, float oldFallValue, float oldFallValueUncapped)
		{
			try
			{
				if (collisionChanged && (Object)(object)controller != (Object)null && (Object)(object)floor != (Object)null)
				{
					Physics.IgnoreCollision((Collider)(object)controller, floor, wasAlreadyIgnored);
				}
			}
			catch
			{
			}
			SetFloat(player, "fallValue", oldFallValue);
			SetFloat(player, "fallValueUncapped", oldFallValueUncapped);
		}

		private Collider FindFloorCollider(object player, CharacterController controller)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			Component val = (Component)((player is Component) ? player : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			Bounds bounds = ((Collider)controller).bounds;
			Vector3 center = ((Bounds)(ref bounds)).center;
			float num = ((Bounds)(ref bounds)).extents.y + 0.3f;
			RaycastHit[] array = Physics.RaycastAll(center, Vector3.down, num, -5, (QueryTriggerInteraction)1);
			Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
			for (int num2 = 0; num2 < array.Length; num2++)
			{
				Collider collider = ((RaycastHit)(ref array[num2])).collider;
				if (!((Object)(object)collider == (Object)null) && collider.enabled && !((Object)(object)collider == (Object)(object)controller) && !((Component)collider).transform.IsChildOf(val.transform) && !(((RaycastHit)(ref array[num2])).normal.y < 0.45f))
				{
					return collider;
				}
			}
			return null;
		}

		private static bool TryResolveBackroomsTeleport(out object instance, out MethodInfo method, out string error)
		{
			instance = null;
			method = null;
			error = null;
			Type type = FindLoadedType("Backrooms.Backrooms");
			if (type == null)
			{
				error = "a classe Backrooms.Backrooms não foi encontrada. Verifique se o BackroomsFixed está instalado e carregado.";
				return false;
			}
			FieldInfo field = type.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				instance = field.GetValue(null);
			}
			if (instance == null)
			{
				PropertyInfo property = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null)
				{
					instance = property.GetValue(null, null);
				}
			}
			if (instance == null)
			{
				error = "Backrooms.Backrooms.Instance ainda está nulo; o ambiente pode não ter sido criado.";
				return false;
			}
			method = type.GetMethod("TeleportToBackroomsServerRpc", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null);
			if (method == null)
			{
				error = "TeleportToBackroomsServerRpc(int) não foi encontrado na DLL carregada.";
				return false;
			}
			return true;
		}

		private Array GetPlayerArray()
		{
			object singleton = GetSingleton("StartOfRound");
			if (singleton == null)
			{
				return null;
			}
			return ReadMember(singleton, "allPlayerScripts") as Array;
		}

		private static CharacterController GetPlayerController(object player)
		{
			object obj = ReadMember(player, "thisController");
			CharacterController val = (CharacterController)((obj is CharacterController) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			Component val2 = (Component)((player is Component) ? player : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return val2.GetComponent<CharacterController>();
		}

		private static bool IsOwnedByLocalClient(object player, NetworkManager manager)
		{
			if (TryGetOwnerClientId(player, out var ownerClientId))
			{
				return ownerClientId == manager.LocalClientId;
			}
			return false;
		}

		private static bool TryGetOwnerClientId(object player, out ulong ownerClientId)
		{
			ownerClientId = 0uL;
			if (player == null)
			{
				return false;
			}
			object obj = ReadMember(player, "OwnerClientId");
			if (obj == null)
			{
				return false;
			}
			try
			{
				ownerClientId = Convert.ToUInt64(obj);
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static object GetSingleton(string typeName)
		{
			Type type = FindLoadedType(typeName);
			if (type == null)
			{
				return null;
			}
			PropertyInfo property = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				return property.GetValue(null, null);
			}
			FieldInfo field = type.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (!(field != null))
			{
				return null;
			}
			return field.GetValue(null);
		}

		private static Type FindLoadedType(string fullName)
		{
			Type type = Type.GetType(fullName, throwOnError: false);
			if (type != null)
			{
				return type;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				Type type2 = assemblies[i].GetType(fullName, throwOnError: false);
				if (type2 != null)
				{
					return type2;
				}
			}
			return null;
		}

		private static object ReadMember(object target, string name)
		{
			if (target == null)
			{
				return null;
			}
			Type type = target.GetType();
			FieldInfo fieldInfo = FindField(type, name);
			if (fieldInfo != null)
			{
				return fieldInfo.GetValue(target);
			}
			PropertyInfo propertyInfo = FindProperty(type, name);
			if (!(propertyInfo != null))
			{
				return null;
			}
			return propertyInfo.GetValue(target, null);
		}

		private static bool ReadBool(object target, string name, bool fallback)
		{
			object obj = ReadMember(target, name);
			if (!(obj is bool))
			{
				return fallback;
			}
			return (bool)obj;
		}

		private static float ReadFloat(object target, string name, float fallback)
		{
			object obj = ReadMember(target, name);
			if (obj == null)
			{
				return fallback;
			}
			try
			{
				return Convert.ToSingle(obj);
			}
			catch
			{
				return fallback;
			}
		}

		private static void SetFloat(object target, string name, float value)
		{
			if (target != null)
			{
				FieldInfo fieldInfo = FindField(target.GetType(), name);
				if (fieldInfo != null && fieldInfo.FieldType == typeof(float))
				{
					fieldInfo.SetValue(target, value);
				}
			}
		}

		private static FieldInfo FindField(Type type, string name)
		{
			while (type != null)
			{
				FieldInfo field = type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field;
				}
				type = type.BaseType;
			}
			return null;
		}

		private static PropertyInfo FindProperty(Type type, string name)
		{
			while (type != null)
			{
				PropertyInfo property = type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null)
				{
					return property;
				}
				type = type.BaseType;
			}
			return null;
		}

		private void OnDestroy()
		{
			UnregisterMessageHandler();
		}
	}
}