Decompiled source of FurnitureAnywhere v1.1.0

FurnitureAnywhere.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
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.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("slivkonsin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("FurnitureAnywhere")]
[assembly: AssemblyTitle("FurnitureAnywhere")]
[assembly: AssemblyVersion("1.1.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 FurnitureAnywhere
{
	internal static class Net
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnSettings;
		}

		private const string MsgName = "slivkonsin.FurnitureAnywhere.Settings";

		private const float Heartbeat = 5f;

		private static CustomMessagingManager _registered;

		private static bool _isClient;

		private static bool _gotHost;

		private static bool _hostOutside;

		private static bool _hostTerrain;

		private static string _lastSent;

		private static float _nextSend;

		public static bool OutsideAllowed
		{
			get
			{
				if (!_isClient)
				{
					return Plugin.OutsideShip.Value;
				}
				if (_gotHost)
				{
					return _hostOutside;
				}
				return false;
			}
		}

		public static bool TerrainAllowed
		{
			get
			{
				if (OutsideAllowed)
				{
					if (!_isClient)
					{
						return Plugin.OnTerrain.Value;
					}
					return _hostTerrain;
				}
				return false;
			}
		}

		public unsafe static void Update()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null)
			{
				_registered = null;
				_isClient = false;
				_gotHost = false;
				return;
			}
			if (_registered != singleton.CustomMessagingManager)
			{
				_registered = singleton.CustomMessagingManager;
				CustomMessagingManager registered = _registered;
				object obj = <>O.<0>__OnSettings;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnSettings;
					<>O.<0>__OnSettings = val;
					obj = (object)val;
				}
				registered.RegisterNamedMessageHandler("slivkonsin.FurnitureAnywhere.Settings", (HandleNamedMessageDelegate)obj);
				_gotHost = false;
				_lastSent = null;
				_nextSend = 0f;
			}
			_isClient = !singleton.IsServer;
			if (_isClient)
			{
				return;
			}
			string text = "1|" + (Plugin.OutsideShip.Value ? "1" : "0") + "|" + (Plugin.OnTerrain.Value ? "1" : "0");
			if (text == _lastSent && Time.realtimeSinceStartup < _nextSend)
			{
				return;
			}
			_lastSent = text;
			_nextSend = Time.realtimeSinceStartup + 5f;
			if (singleton.ConnectedClientsIds.Count <= 1)
			{
				return;
			}
			try
			{
				FastBufferWriter val2 = default(FastBufferWriter);
				((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize(text, false), (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(text, false);
					_registered.SendNamedMessageToAll("slivkonsin.FurnitureAnywhere.Settings", val2, (NetworkDelivery)2);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val2))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't send settings to the other players: " + ex.Message));
			}
		}

		private static void OnSettings(ulong sender, FastBufferReader r)
		{
			try
			{
				if (sender != 0L)
				{
					return;
				}
				string text = default(string);
				((FastBufferReader)(ref r)).ReadValueSafe(ref text, false);
				string[] array = text.Split('|');
				if (array.Length >= 3 && !(array[0] != "1"))
				{
					bool flag = array[1] == "1";
					bool flag2 = array[2] == "1";
					if (!_gotHost || flag != _hostOutside || flag2 != _hostTerrain)
					{
						Plugin.Log.LogInfo((object)$"Using the host's settings (outside the ship: {flag}, on terrain: {flag2}).");
					}
					_hostOutside = flag;
					_hostTerrain = flag2;
					_gotHost = true;
					DiagnosticsTelemetry.HostSettingsReceived = true;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Couldn't read the host's settings: " + ex.Message));
			}
		}
	}
	internal static class Patches
	{
		private struct StoreState
		{
			public PlaceableShipObject Obj;

			public bool OffShip;
		}

		private static readonly FieldRef<ShipBuildModeManager, int> PlacementMask = AccessTools.FieldRefAccess<ShipBuildModeManager, int>("placementMask");

		private static readonly FieldRef<ShipBuildModeManager, bool> CanConfirmPosition = AccessTools.FieldRefAccess<ShipBuildModeManager, bool>("CanConfirmPosition");

		private static readonly FieldRef<ShipBuildModeManager, PlaceableShipObject> PlacingObject = AccessTools.FieldRefAccess<ShipBuildModeManager, PlaceableShipObject>("placingObject");

		private static readonly FieldRef<ShipBuildModeManager, RaycastHit> RayHit = AccessTools.FieldRefAccess<ShipBuildModeManager, RaycastHit>("rayHit");

		private static readonly MethodInfo BoundsContains = AccessTools.Method(typeof(Bounds), "Contains", new Type[1] { typeof(Vector3) }, (Type[])null);

		private static readonly FieldInfo InShipRoomField = AccessTools.Field(typeof(PlayerControllerB), "isInHangarShipRoom");

		private static Collider _doorBlocker;

		private static StartOfRound _doorBlockerRound;

		private static bool _doorBlockerSearched;

		private static bool _doorBlockerOff;

		private static int _addedBits;

		private static readonly MethodInfo CheckSphere = AccessTools.Method(typeof(Physics), "CheckSphere", new Type[4]
		{
			typeof(Vector3),
			typeof(float),
			typeof(int),
			typeof(QueryTriggerInteraction)
		}, (Type[])null);

		private static readonly HashSet<string> _failedOnce = new HashSet<string>();

		public static void Apply(Harmony h)
		{
			Type typeFromHandle = typeof(ShipBuildModeManager);
			Patch(h, "build from outside", AccessTools.Method(typeFromHandle, "PlayerMeetsConditionsToBuild", (Type[])null, (Type[])null), null, null, "BuildConditionsTranspiler");
			Patch(h, "place outside", AccessTools.Method(typeFromHandle, "Update", (Type[])null, (Type[])null), "UpdatePrefix", "UpdatePostfix", "UpdateTranspiler");
			Patch(h, "far furniture check", AccessTools.Method(typeFromHandle, "PlaceShipObject", (Type[])null, (Type[])null), "PlaceShipObjectPrefix");
			Patch(h, "store from outside (host)", AccessTools.Method(typeFromHandle, "StoreObjectServerRpc", (Type[])null, (Type[])null), "StorePrefix", "StoreServerPostfix");
			Patch(h, "store from outside", AccessTools.Method(typeFromHandle, "StoreShipObjectClientRpc", (Type[])null, (Type[])null), "StorePrefix", "StoreClientPostfix");
			Patch(h, "scrap on outside furniture", AccessTools.Method(typeof(PlayerControllerB), "PlaceGrabbableObject", (Type[])null, (Type[])null), null, "PlaceGrabbablePostfix");
			Patch(h, "keep scrap near the ship", AccessTools.Method(typeof(StartOfRound), "LoadShipGrabbableItems", (Type[])null, (Type[])null), null, null, "LoadItemsTranspiler");
		}

		private static void Patch(Harmony h, string what, MethodBase target, string prefix = null, string postfix = null, string transpiler = null)
		{
			try
			{
				if (target == null)
				{
					throw new MissingMethodException("game method not found");
				}
				h.Patch(target, M(prefix), M(postfix), M(transpiler), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				DiagnosticsTelemetry.Errors++;
				Plugin.Log.LogWarning((object)("Couldn't set up \"" + what + "\", that part stays vanilla: " + ex.Message));
			}
			static HarmonyMethod M(string n)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				if (n != null)
				{
					return new HarmonyMethod(typeof(Patches), n, (Type[])null);
				}
				return null;
			}
		}

		private static IEnumerable<CodeInstruction> Swap(IEnumerable<CodeInstruction> code, Func<CodeInstruction, bool> match, string with, string what)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(code);
			MethodInfo operand = AccessTools.Method(typeof(Patches), with, (Type[])null, (Type[])null);
			int num = 0;
			foreach (CodeInstruction item in list)
			{
				if (match(item))
				{
					item.opcode = OpCodes.Call;
					item.operand = operand;
					num++;
				}
			}
			if (num == 0)
			{
				Plugin.Log.LogWarning((object)("Couldn't find the " + what + " check in the game code (game update or another mod?), that part stays vanilla."));
			}
			return list;
		}

		private static IEnumerable<CodeInstruction> BuildConditionsTranspiler(IEnumerable<CodeInstruction> code)
		{
			return Swap(code, (CodeInstruction ci) => CodeInstructionExtensions.LoadsField(ci, InShipRoomField, false), "CanBuildFrom", "\"standing in the ship\"");
		}

		private static bool CanBuildFrom(PlayerControllerB p)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (p.isInHangarShipRoom)
			{
				return true;
			}
			try
			{
				if (!Net.OutsideAllowed || p.isInsideFactory || (Object)(object)StartOfRound.Instance == (Object)null)
				{
					return false;
				}
				float num = (Net.TerrainAllowed ? 30f : 6f);
				return Ship.DistanceTo(((Component)p).transform.position) <= num;
			}
			catch (Exception e)
			{
				Fail("build check", e);
				return false;
			}
		}

		private static void SyncDoorBlocker()
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.elevatorTransform == (Object)null)
			{
				_doorBlockerSearched = false;
				_doorBlocker = null;
				return;
			}
			if (!_doorBlockerSearched || (Object)(object)_doorBlockerRound != (Object)(object)instance)
			{
				_doorBlockerSearched = true;
				_doorBlockerRound = instance;
				_doorBlockerOff = false;
				Transform val = instance.elevatorTransform.Find("PlacementBlockers");
				Transform val2 = (((Object)(object)val != (Object)null) ? val.Find("PlacementBlocker") : null);
				if ((Object)(object)val2 == (Object)null)
				{
					GameObject obj = GameObject.Find("Environment/HangarShip/PlacementBlockers/PlacementBlocker");
					val2 = ((obj != null) ? obj.transform : null);
				}
				_doorBlocker = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<Collider>() : null);
				if ((Object)(object)_doorBlocker == (Object)null)
				{
					Plugin.Log.LogWarning((object)"Couldn't find the doorway's \"no placing\" box (ship changed by a game update or another mod?), the doorway stays blocked.");
				}
			}
			if (!((Object)(object)_doorBlocker == (Object)null))
			{
				bool outsideAllowed = Net.OutsideAllowed;
				if (outsideAllowed != _doorBlockerOff)
				{
					_doorBlocker.enabled = !outsideAllowed;
					_doorBlockerOff = outsideAllowed;
				}
			}
		}

		private static void UpdatePrefix(ShipBuildModeManager __instance)
		{
			SyncDoorBlocker();
			SyncMaskBit(__instance, 33554432, Net.TerrainAllowed);
			SyncMaskBit(__instance, 67108864, Net.OutsideAllowed);
		}

		private static void SyncMaskBit(ShipBuildModeManager mgr, int bit, bool want)
		{
			ref int reference = ref PlacementMask.Invoke(mgr);
			if (want && (reference & bit) == 0)
			{
				reference |= bit;
				_addedBits |= bit;
			}
			else if (!want && (_addedBits & bit) != 0)
			{
				reference &= ~bit;
				_addedBits &= ~bit;
			}
		}

		private static IEnumerable<CodeInstruction> UpdateTranspiler(IEnumerable<CodeInstruction> code)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(Swap(code, (CodeInstruction ci) => CodeInstructionExtensions.Calls(ci, BoundsContains), "CanPlaceAt", "\"inside the ship\""));
			int num = 0;
			int num2 = 0;
			for (int num3 = 0; num3 < list.Count; num3++)
			{
				if (list[num3].opcode == OpCodes.Ldc_R4 && list[num3].operand is float num4 && Mathf.Approximately(num4, 0.57f))
				{
					list[num3].opcode = OpCodes.Call;
					list[num3].operand = AccessTools.Method(typeof(Patches), "BoxScale", (Type[])null, (Type[])null);
					num++;
				}
				else
				{
					if (!CodeInstructionExtensions.Calls(list[num3], CheckSphere))
					{
						continue;
					}
					for (int num5 = num3 - 1; num5 >= Math.Max(0, num3 - 4); num5--)
					{
						if (list[num5].opcode == OpCodes.Ldc_R4 && list[num5].operand is float num6 && Mathf.Approximately(num6, 1f))
						{
							list[num5].opcode = OpCodes.Call;
							list[num5].operand = AccessTools.Method(typeof(Patches), "SphereRadius", (Type[])null, (Type[])null);
							num2++;
							break;
						}
					}
				}
			}
			if (num == 0 || num2 == 0)
			{
				Plugin.Log.LogWarning((object)$"Couldn't find all of the wall clipping checks in the game code (box {num}, sphere {num2}), the missing part stays vanilla.");
			}
			return list;
		}

		private static float BoxScale()
		{
			if (!Net.OutsideAllowed)
			{
				return 0.57f;
			}
			return 0.4f;
		}

		private static float SphereRadius()
		{
			if (!Net.OutsideAllowed)
			{
				return 1f;
			}
			return 0.55f;
		}

		private static bool CanPlaceAt(ref Bounds innerRoom, Vector3 p)
		{
			//IL_0001: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			if (((Bounds)(ref innerRoom)).Contains(p))
			{
				return true;
			}
			try
			{
				if (!Net.OutsideAllowed)
				{
					return false;
				}
				if (Ship.DistanceTo(p) > 30f)
				{
					return false;
				}
				ShipBuildModeManager instance = ShipBuildModeManager.Instance;
				PlaceableShipObject val = (((Object)(object)instance != (Object)null) ? PlacingObject.Invoke(instance) : null);
				float lookDown = (((Object)(object)val != (Object)null) ? val.yOffset : 0f) + 1.5f;
				if (Ship.IsOnShip(p, lookDown, null, out var surface) || ((Object)(object)instance != (Object)null && (Object)(object)val != (Object)null && val.AllowPlacementOnWalls && Ship.IsShipCollider(((RaycastHit)(ref RayHit.Invoke(instance))).collider)))
				{
					DiagnosticsTelemetry.LastSurface = surface;
					return true;
				}
				DiagnosticsTelemetry.LastSurface = surface;
				return Net.TerrainAllowed;
			}
			catch (Exception e)
			{
				Fail("placement check", e);
				return false;
			}
		}

		private static void UpdatePostfix(ShipBuildModeManager __instance)
		{
			if (__instance.InBuildMode && Net.OutsideAllowed && !CanConfirmPosition.Invoke(__instance) && (Object)(object)__instance.ghostObjectRenderer != (Object)null && (Object)(object)__instance.ghostObjectRed != (Object)null)
			{
				((Renderer)__instance.ghostObjectRenderer).sharedMaterial = __instance.ghostObjectRed;
			}
		}

		private static bool PlaceShipObjectPrefix(Vector3 placementPosition, PlaceableShipObject placeableObject, bool placementSFX)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)placeableObject == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null)
				{
					return true;
				}
				if (placementSFX)
				{
					Bounds bounds = StartOfRound.Instance.shipInnerRoomBounds.bounds;
					if (!((Bounds)(ref bounds)).Contains(placementPosition))
					{
						DiagnosticsTelemetry.PlacedOutside++;
					}
					return true;
				}
				if (Ship.DistanceTo(placementPosition) <= 30f)
				{
					return true;
				}
				Ship.SendHome(placeableObject);
				DiagnosticsTelemetry.SentHomeTooFar++;
				Plugin.Log.LogInfo((object)$"{Name(placeableObject)} was more than {30f} m from the ship, put it back in its default spot.");
				return false;
			}
			catch (Exception e)
			{
				Fail("far furniture check", e);
				return true;
			}
		}

		private static void StorePrefix(NetworkObjectReference objectRef, out StoreState __state)
		{
			__state = default(StoreState);
			try
			{
				NetworkObject val = default(NetworkObject);
				if (!((Object)(object)StartOfRound.Instance == (Object)null) && ((NetworkObjectReference)(ref objectRef)).TryGet(ref val, (NetworkManager)null) && !((Object)(object)val == (Object)null))
				{
					PlaceableShipObject componentInChildren = ((Component)val).GetComponentInChildren<PlaceableShipObject>();
					if (!((Object)(object)componentInChildren == (Object)null) && !StartOfRound.Instance.unlockablesList.unlockables[componentInChildren.unlockableID].inStorage)
					{
						__state.Obj = componentInChildren;
						__state.OffShip = !Ship.IsOnShip(componentInChildren, out var _);
					}
				}
			}
			catch (Exception e)
			{
				Fail("store check", e);
			}
		}

		private static void StoreServerPostfix(StoreState __state)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && singleton.IsServer)
			{
				AfterStore(__state);
			}
		}

		private static void StoreClientPostfix(StoreState __state)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && !singleton.IsServer)
			{
				AfterStore(__state);
			}
		}

		private static void AfterStore(StoreState s)
		{
			try
			{
				if (s.OffShip && !((Object)(object)s.Obj == (Object)null) && StartOfRound.Instance.unlockablesList.unlockables[s.Obj.unlockableID].inStorage)
				{
					Ship.SendHome(s.Obj);
					DiagnosticsTelemetry.SentHomeOnStore++;
					Plugin.Log.LogInfo((object)(Name(s.Obj) + " was stored from outside the ship, it will come back out inside."));
				}
			}
			catch (Exception e)
			{
				Fail("store", e);
			}
		}

		private static void PlaceGrabbablePostfix(PlayerControllerB __instance, Transform parentObject, GrabbableObject placeObject)
		{
			try
			{
				if (!((Object)(object)placeObject == (Object)null) && !((Object)(object)parentObject == (Object)null) && !placeObject.isInShipRoom && Net.OutsideAllowed && !((Object)(object)((Component)parentObject).GetComponentInParent<AutoParentToShip>() == (Object)null))
				{
					__instance.SetItemInElevator(true, true, placeObject);
					DiagnosticsTelemetry.ScrapOnFurniture++;
				}
			}
			catch (Exception e)
			{
				Fail("scrap on furniture", e);
			}
		}

		private static IEnumerable<CodeInstruction> LoadItemsTranspiler(IEnumerable<CodeInstruction> code)
		{
			return Swap(code, (CodeInstruction ci) => CodeInstructionExtensions.Calls(ci, BoundsContains), "KeepItemAt", "\"scrap outside the ship\"");
		}

		private static bool KeepItemAt(ref Bounds shipBounds, Vector3 p)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (((Bounds)(ref shipBounds)).Contains(p))
			{
				return true;
			}
			try
			{
				if (!Net.OutsideAllowed || Ship.DistanceTo(p) > 30f)
				{
					return false;
				}
				DiagnosticsTelemetry.ScrapKeptOutside++;
				return true;
			}
			catch (Exception e)
			{
				Fail("scrap load check", e);
				return false;
			}
		}

		private static string Name(PlaceableShipObject o)
		{
			try
			{
				return StartOfRound.Instance.unlockablesList.unlockables[o.unlockableID].unlockableName;
			}
			catch
			{
				return ((Object)o).name;
			}
		}

		private static void Fail(string what, Exception e)
		{
			DiagnosticsTelemetry.Errors++;
			if (_failedOnce.Add(what))
			{
				Plugin.Log.LogWarning((object)$"Error in {what}: {e}");
			}
		}
	}
	internal static class PersistentTerminalCompat
	{
		private const float NearTerminal = 20f;

		private static Terminal _terminal;

		public static void Apply(Harmony h)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_0071: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("PersistentTerminal.Patches.PlayerControllerPatches");
			if (type == null)
			{
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "UpdateTerminalPerformanceState", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"PersistentTerminal found, but not the part that hides the screen (newer version?). The screen may stay off for a terminal outside the ship.");
				return;
			}
			try
			{
				h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(PersistentTerminalCompat), "Prefix", (Type[])null), new HarmonyMethod(typeof(PersistentTerminalCompat), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)"PersistentTerminal support on (terminal screen works outside the ship).");
			}
			catch (Exception ex)
			{
				DiagnosticsTelemetry.Errors++;
				Plugin.Log.LogWarning((object)("PersistentTerminal support off: " + ex.Message));
			}
		}

		private static void Prefix(PlayerControllerB player, out bool __state)
		{
			//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)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			__state = false;
			try
			{
				if ((Object)(object)player == (Object)null || player.isInHangarShipRoom || !Net.OutsideAllowed || (Object)(object)StartOfRound.Instance == (Object)null)
				{
					return;
				}
				if ((Object)(object)_terminal == (Object)null)
				{
					_terminal = Object.FindObjectOfType<Terminal>();
				}
				if (!((Object)(object)_terminal == (Object)null))
				{
					Vector3 position = ((Component)_terminal).transform.position;
					Bounds bounds = StartOfRound.Instance.shipInnerRoomBounds.bounds;
					if (!((Bounds)(ref bounds)).Contains(position) && !player.isInsideFactory && !(Vector3.Distance(((Component)player).transform.position, position) > 20f))
					{
						player.isInHangarShipRoom = true;
						__state = true;
					}
				}
			}
			catch (Exception ex)
			{
				DiagnosticsTelemetry.Errors++;
				Plugin.Log.LogWarning((object)("PersistentTerminal support: " + ex.Message));
			}
		}

		private static void Postfix(PlayerControllerB player, bool __state)
		{
			if (__state && (Object)(object)player != (Object)null)
			{
				player.isInHangarShipRoom = false;
			}
		}
	}
	[BepInPlugin("slivkonsin.FurnitureAnywhere", "Furniture Anywhere", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "slivkonsin.FurnitureAnywhere";

		public const string Name = "Furniture Anywhere";

		public const string Version = "1.1.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> OutsideShip;

		internal static ConfigEntry<bool> OnTerrain;

		private void Awake()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_007d: Expected O, but got Unknown
			//IL_0082: 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_008d: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			OutsideShip = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Place outside the ship", true, "Lets you place furniture on the outside of the ship too, like the catwalk and the roof. The host's setting is used.");
			OnTerrain = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Place on terrain", false, "Lets you place furniture anywhere near the ship, even on the ground (up to " + 30f + " m away). It still moves with the ship. The host's setting is used.");
			Harmony val = new Harmony("slivkonsin.FurnitureAnywhere");
			Patches.Apply(val);
			ShipRide.Apply(val);
			PersistentTerminalCompat.Apply(val);
			GameObject val2 = new GameObject("FurnitureAnywhere");
			Object.DontDestroyOnLoad((Object)val2);
			((Object)val2).hideFlags = (HideFlags)61;
			val2.AddComponent<Runner>();
			Log.LogInfo((object)"Furniture Anywhere 1.1.0 loaded.");
		}
	}
	internal sealed class Runner : MonoBehaviour
	{
		private void Update()
		{
			try
			{
				Net.Update();
			}
			catch (Exception ex)
			{
				DiagnosticsTelemetry.Errors++;
				Plugin.Log.LogWarning((object)("Settings sync: " + ex.Message));
			}
		}
	}
	internal static class Ship
	{
		public const float MaxDistance = 30f;

		public const float ShipOnlyBuildRange = 6f;

		public const int VanillaPlacementMask = 2305;

		public const int TerrainLayerMask = 33554432;

		public const int FurnitureLayerMask = 67108864;

		public static StartOfRound Round => StartOfRound.Instance;

		public static bool IsFurniture(Collider c)
		{
			if ((Object)(object)c != (Object)null)
			{
				if (!((Object)(object)((Component)c).GetComponent<PlaceableShipObject>() != (Object)null))
				{
					return (Object)(object)((Component)c).GetComponentInParent<AutoParentToShip>() != (Object)null;
				}
				return true;
			}
			return false;
		}

		public static float DistanceTo(Vector3 p)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			Collider shipBounds = Round.shipBounds;
			Vector3 val;
			if (shipBounds.enabled && ((Component)shipBounds).gameObject.activeInHierarchy)
			{
				val = shipBounds.ClosestPoint(p);
			}
			else
			{
				Bounds bounds = shipBounds.bounds;
				val = ((Bounds)(ref bounds)).ClosestPoint(p);
			}
			return Vector3.Distance(val, p);
		}

		public static bool IsShipCollider(Collider c)
		{
			if ((Object)(object)c != (Object)null && (Object)(object)Round != (Object)null && (Object)(object)Round.elevatorTransform != (Object)null)
			{
				return ((Component)c).transform.IsChildOf(Round.elevatorTransform);
			}
			return false;
		}

		public static bool IsOnShip(Vector3 p, float lookDown, Transform ignore, out string surface)
		{
			//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_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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)
			//IL_003f: 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)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			surface = "";
			Bounds bounds = Round.shipInnerRoomBounds.bounds;
			if (((Bounds)(ref bounds)).Contains(p))
			{
				surface = "inner room";
				return true;
			}
			RaycastHit[] array = Physics.RaycastAll(p + Vector3.up * 0.1f, Vector3.down, lookDown + 0.1f, 100665601, (QueryTriggerInteraction)1);
			RaycastHit? val = null;
			RaycastHit[] array2 = array;
			RaycastHit value2;
			for (int i = 0; i < array2.Length; i++)
			{
				RaycastHit value = array2[i];
				if ((Object)(object)ignore != (Object)null && ((Component)((RaycastHit)(ref value)).collider).transform.IsChildOf(ignore))
				{
					continue;
				}
				if (val.HasValue)
				{
					float distance = ((RaycastHit)(ref value)).distance;
					value2 = val.Value;
					if (!(distance < ((RaycastHit)(ref value2)).distance))
					{
						continue;
					}
				}
				val = value;
			}
			if (!val.HasValue)
			{
				surface = "nothing";
				return false;
			}
			value2 = val.Value;
			surface = ((Object)((RaycastHit)(ref value2)).collider).name;
			value2 = val.Value;
			if (!IsShipCollider(((RaycastHit)(ref value2)).collider))
			{
				value2 = val.Value;
				return IsFurniture(((RaycastHit)(ref value2)).collider);
			}
			return true;
		}

		public static bool IsOnShip(PlaceableShipObject o, out string surface)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_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_0044: Unknown result type (might be due to invalid IL or missing references)
			Collider placeObjectCollider = o.placeObjectCollider;
			Vector3 p;
			Bounds bounds;
			if (!((Object)(object)placeObjectCollider != (Object)null))
			{
				p = ((Component)o).transform.position;
			}
			else
			{
				bounds = placeObjectCollider.bounds;
				p = ((Bounds)(ref bounds)).center;
			}
			float num;
			if (!((Object)(object)placeObjectCollider != (Object)null))
			{
				num = 2f;
			}
			else
			{
				bounds = placeObjectCollider.bounds;
				num = ((Bounds)(ref bounds)).extents.y + 1.5f;
			}
			float lookDown = num;
			Transform ignore = (((Object)(object)o.parentObjectSecondary != (Object)null) ? o.parentObjectSecondary : (((Object)(object)o.parentObject != (Object)null) ? ((Component)o.parentObject).transform : ((Component)o).transform));
			return IsOnShip(p, lookDown, ignore, out surface);
		}

		public static void SendHome(PlaceableShipObject o)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			ShipBuildModeManager instance = ShipBuildModeManager.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)o == (Object)null)
			{
				return;
			}
			instance.ResetShipObjectToDefaultPosition(o);
			if ((Object)(object)o.parentObjectSecondary == (Object)null && (Object)(object)o.parentObject != (Object)null)
			{
				o.parentObject.MoveToOffset();
			}
			UnlockableItem val = Round.unlockablesList.unlockables[o.unlockableID];
			if (!((Object)(object)o.placeObjectCollider == (Object)null) && !((Object)(object)o.mainMesh == (Object)null))
			{
				val.placedPosition = ((Component)o.placeObjectCollider).transform.position;
				Vector3 eulerAngles = ((Component)o.mainMesh).transform.eulerAngles;
				if (eulerAngles == Vector3.zero)
				{
					((Vector3)(ref eulerAngles))..ctor(0f, 0.001f, 0f);
				}
				val.placedRotation = eulerAngles;
				val.hasBeenMoved = true;
			}
		}
	}
	internal static class ShipRide
	{
		private static readonly MethodInfo BoundsContains = AccessTools.Method(typeof(Bounds), "Contains", new Type[1] { typeof(Vector3) }, (Type[])null);

		private static readonly FieldInfo ShipBoundsField = AccessTools.Field(typeof(StartOfRound), "shipBounds");

		private static readonly FieldInfo InnerBoundsField = AccessTools.Field(typeof(StartOfRound), "shipInnerRoomBounds");

		private static int _frame = -1;

		private static bool _onShipStuff;

		private static bool _warned;

		public static void Apply(Harmony h)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "LateUpdate", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					throw new MissingMethodException("StartOfRound.LateUpdate not found");
				}
				h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ShipRide), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				DiagnosticsTelemetry.Errors++;
				Plugin.Log.LogWarning((object)("Couldn't set up \"ride along on furniture\", that part stays vanilla: " + ex.Message));
			}
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(code);
			MethodInfo operand = AccessTools.Method(typeof(ShipRide), "ShipContains", (Type[])null, (Type[])null);
			bool flag = false;
			int num = 0;
			foreach (CodeInstruction item in list)
			{
				if (CodeInstructionExtensions.LoadsField(item, ShipBoundsField, false))
				{
					flag = true;
				}
				else if (CodeInstructionExtensions.LoadsField(item, InnerBoundsField, false))
				{
					flag = false;
				}
				else if (CodeInstructionExtensions.Calls(item, BoundsContains))
				{
					if (flag)
					{
						item.opcode = OpCodes.Call;
						item.operand = operand;
						num++;
					}
					flag = false;
				}
			}
			if (num == 0)
			{
				Plugin.Log.LogWarning((object)"Couldn't find the \"standing in the ship\" check in the game code, riding along on furniture stays vanilla.");
			}
			return list;
		}

		private static bool ShipContains(ref Bounds shipBounds, Vector3 p)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (((Bounds)(ref shipBounds)).Contains(p))
			{
				return true;
			}
			try
			{
				if (!Net.OutsideAllowed)
				{
					return false;
				}
				PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				if (!((Object)(object)val == (Object)null) && !val.isPlayerDead)
				{
					Vector3 val2 = ((Component)val).transform.position - p;
					if (!(((Vector3)(ref val2)).sqrMagnitude > 1f))
					{
						if (_frame != Time.frameCount)
						{
							_frame = Time.frameCount;
							_onShipStuff = StandingOnShipStuff(val);
							DiagnosticsTelemetry.RidingOnFurniture = _onShipStuff;
						}
						return _onShipStuff;
					}
				}
				return false;
			}
			catch (Exception ex)
			{
				DiagnosticsTelemetry.Errors++;
				if (!_warned)
				{
					_warned = true;
					Plugin.Log.LogWarning((object)("Error in ride along check: " + ex));
				}
				return false;
			}
		}

		private static bool StandingOnShipStuff(PlayerControllerB lp)
		{
			//IL_000e: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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)
			if (lp.isInsideFactory || Ship.DistanceTo(((Component)lp).transform.position) > 35f)
			{
				return false;
			}
			int num = StartOfRound.Instance.collidersAndRoomMaskAndDefault | 0x4000000;
			RaycastHit val = default(RaycastHit);
			if (!Physics.SphereCast(((Component)lp).transform.position + Vector3.up * 0.5f, 0.3f, Vector3.down, ref val, 0.6f, num, (QueryTriggerInteraction)1))
			{
				return false;
			}
			if (!Ship.IsFurniture(((RaycastHit)(ref val)).collider))
			{
				return Ship.IsShipCollider(((RaycastHit)(ref val)).collider);
			}
			return true;
		}
	}
	public static class DiagnosticsTelemetry
	{
		public static bool HostSettingsReceived;

		public static int PlacedOutside;

		public static int SentHomeTooFar;

		public static int SentHomeOnStore;

		public static int ScrapKeptOutside;

		public static int ScrapOnFurniture;

		public static bool RidingOnFurniture;

		public static string LastSurface = "";

		public static int Errors;
	}
}