Decompiled source of FurnitureGrid v1.0.1

plugins/Dumbass.GridSnap.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
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 HarmonyLib;
using LethalCompanyInputUtils.Api;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("EasyTextEffects")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("Dumbass.GridSnap")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Grid Snap")]
[assembly: AssemblyTitle("Dumbass.GridSnap")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 Grid_Snap
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "Dumbass.GridSnap";

		public const string PLUGIN_NAME = "Grid Snap";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace GridSnap
{
	[BepInPlugin("Dumbass.GridSnap", "Grid Snap", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class GridSnapPlugin : BaseUnityPlugin
	{
		internal static ConfigEntry<bool> GridEnabled;

		internal static ConfigEntry<float> GridSize;

		internal static ConfigEntry<bool> SnapOnWalls;

		internal static ConfigEntry<float> GridSizeStep;

		internal static ConfigEntry<bool> RotationSnapEnabled;

		internal static ConfigEntry<float> RotationSnapAngle;

		internal static ConfigEntry<float> RotationSnapAngleStep;

		internal static ConfigEntry<float> GridDisplayExtent;

		internal static ConfigEntry<Color> GridLineColor;

		internal static ConfigEntry<float> GridMinorLineWidth;

		internal static ConfigEntry<float> GridMajorLineWidth;

		internal static ConfigEntry<int> GridMajorLineEvery;

		internal static ConfigEntry<bool> ShowGridOverlay;

		internal GridOverlay overlay;

		public static GridSnapPlugin Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony HarmonyInstance { get; private set; }

		internal static GridSnapInputs Inputs { get; private set; }

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			try
			{
				BindConfiguration();
				InitializeInputs();
				InitializeOverlay();
				PatchMethods();
				Logger.LogInfo((object)"Dumbass.GridSnap v1.0.0 loaded successfully!");
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Failed to initialize plugin: {arg}");
			}
		}

		private void BindConfiguration()
		{
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			GridEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Grid", "Enabled", true, "Enable grid snapping in ship build mode");
			GridSize = ((BaseUnityPlugin)this).Config.Bind<float>("Grid", "Size", 0.5f, "Grid cell size in meters");
			GridSizeStep = ((BaseUnityPlugin)this).Config.Bind<float>("Grid", "SizeStep", 0.05f, "Grid size adjustment increment");
			SnapOnWalls = ((BaseUnityPlugin)this).Config.Bind<bool>("Grid", "SnapOnWalls", false, "Enable grid snapping on walls");
			RotationSnapEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Rotation", "Enabled", true, "Enable rotation snapping");
			RotationSnapAngle = ((BaseUnityPlugin)this).Config.Bind<float>("Rotation", "AngleStep", 45f, "Rotation snap angle in degrees");
			RotationSnapAngleStep = ((BaseUnityPlugin)this).Config.Bind<float>("Rotation", "AngleStepIncrement", 15f, "Rotation angle adjustment");
			ShowGridOverlay = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowOverlay", true, "Show visual grid overlay");
			GridDisplayExtent = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "Extent", 15f, "Grid display radius in meters");
			GridLineColor = ((BaseUnityPlugin)this).Config.Bind<Color>("Display", "LineColor", new Color(0f, 1f, 1f, 0.4f), "Grid line color");
			GridMinorLineWidth = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "MinorLineWidth", 0.01f, "Minor grid line thickness");
			GridMajorLineWidth = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "MajorLineWidth", 0.03f, "Major grid line thickness");
			GridMajorLineEvery = ((BaseUnityPlugin)this).Config.Bind<int>("Display", "MajorLineEvery", 4, "Major line frequency");
		}

		private void InitializeInputs()
		{
			try
			{
				Inputs = new GridSnapInputs();
				((LcInputActions)Inputs).Enable();
				SetupInputHandlers();
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Failed to initialize inputs: {arg}");
			}
		}

		private void SetupInputHandlers()
		{
			if (Inputs.ToggleGrid != null)
			{
				Inputs.ToggleGrid.performed += delegate
				{
					ToggleGrid();
				};
			}
			if (Inputs.IncreaseGrid != null)
			{
				Inputs.IncreaseGrid.performed += delegate
				{
					AdjustGridSize(increase: true);
				};
			}
			if (Inputs.DecreaseGrid != null)
			{
				Inputs.DecreaseGrid.performed += delegate
				{
					AdjustGridSize(increase: false);
				};
			}
			if (Inputs.ToggleRotationSnap != null)
			{
				Inputs.ToggleRotationSnap.performed += delegate
				{
					ToggleRotationSnap();
				};
			}
			if (Inputs.IncreaseRotationSnapAngle != null)
			{
				Inputs.IncreaseRotationSnapAngle.performed += delegate
				{
					AdjustRotationAngle(increase: true);
				};
			}
			if (Inputs.DecreaseRotationSnapAngle != null)
			{
				Inputs.DecreaseRotationSnapAngle.performed += delegate
				{
					AdjustRotationAngle(increase: false);
				};
			}
		}

		private void InitializeOverlay()
		{
			overlay = new GridOverlay();
		}

		private void PatchMethods()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			try
			{
				HarmonyInstance = new Harmony("Dumbass.GridSnap");
				HarmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
				Logger.LogInfo((object)"Harmony patches applied successfully");
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Failed to apply Harmony patches: {arg}");
			}
		}

		private void ToggleGrid()
		{
			GridEnabled.Value = !GridEnabled.Value;
			UpdateBuildModeTip();
			Logger.LogInfo((object)("Grid snapping " + (GridEnabled.Value ? "enabled" : "disabled")));
			if ((Object)(object)ShipBuildModeManager.Instance != (Object)null && ShipBuildModeManager.Instance.InBuildMode)
			{
				overlay?.UpdateVisibility();
			}
		}

		private void AdjustGridSize(bool increase)
		{
			float value = (increase ? (GridSize.Value + GridSizeStep.Value) : Mathf.Max(GridSizeStep.Value, GridSize.Value - GridSizeStep.Value));
			GridSize.Value = value;
			overlay?.Rebuild();
			UpdateBuildModeTip();
			Logger.LogInfo((object)$"Grid size: {GridSize.Value:F2}m");
		}

		private void ToggleRotationSnap()
		{
			RotationSnapEnabled.Value = !RotationSnapEnabled.Value;
			UpdateBuildModeTip();
			Logger.LogInfo((object)("Rotation snapping " + (RotationSnapEnabled.Value ? "enabled" : "disabled")));
		}

		private void AdjustRotationAngle(bool increase)
		{
			float value = (increase ? (RotationSnapAngle.Value + RotationSnapAngleStep.Value) : Mathf.Max(1f, RotationSnapAngle.Value - RotationSnapAngleStep.Value));
			RotationSnapAngle.Value = value;
			UpdateBuildModeTip();
			Logger.LogInfo((object)$"Rotation angle: {RotationSnapAngle.Value:F0}°");
		}

		internal static void UpdateBuildModeTip()
		{
			try
			{
				if ((Object)(object)ShipBuildModeManager.Instance == (Object)null || !ShipBuildModeManager.Instance.InBuildMode)
				{
					return;
				}
				HUDManager instance = HUDManager.Instance;
				if (!((Object)(object)instance?.buildModeControlTip == (Object)null))
				{
					string text = ((TMP_Text)instance.buildModeControlTip).text;
					int num = text.IndexOf(" | Grid:");
					if (num >= 0)
					{
						text = text.Substring(0, num);
					}
					string text2 = (GridEnabled.Value ? "ON" : "OFF");
					string text3 = (RotationSnapEnabled.Value ? "ON" : "OFF");
					string text4 = $"Grid: {text2} ({GridSize.Value:F2}m) | Rot: {text3} ({RotationSnapAngle.Value:F0}°)";
					((TMP_Text)instance.buildModeControlTip).text = text + " | " + text4;
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Failed to update build mode tip: {arg}");
				}
			}
		}
	}
	public class GridSnapInputs : LcInputActions
	{
		[InputAction("<Keyboard>/z", Name = "Toggle Grid Snap")]
		public InputAction ToggleGrid { get; set; }

		[InputAction("<Keyboard>/equals", Name = "Increase Grid Size")]
		public InputAction IncreaseGrid { get; set; }

		[InputAction("<Keyboard>/minus", Name = "Decrease Grid Size")]
		public InputAction DecreaseGrid { get; set; }

		[InputAction("<Keyboard>/c", Name = "Toggle Rotation Snap")]
		public InputAction ToggleRotationSnap { get; set; }

		[InputAction("<Keyboard>/f1", Name = "Increase Rotation Angle")]
		public InputAction IncreaseRotationSnapAngle { get; set; }

		[InputAction("<Keyboard>/f2", Name = "Decrease Rotation Angle")]
		public InputAction DecreaseRotationSnapAngle { get; set; }
	}
	public class GridOverlay
	{
		private GameObject root;

		private readonly List<LineRenderer> lineRenderers = new List<LineRenderer>();

		private Material lineMaterial;

		public void UpdateVisibility()
		{
			if (!((Object)(object)root == (Object)null))
			{
				bool flag = GridSnapPlugin.ShowGridOverlay.Value && GridSnapPlugin.GridEnabled.Value;
				root.SetActive(flag);
				if (flag)
				{
					Rebuild();
				}
			}
		}

		public void Show(Transform elevator)
		{
			//IL_0027: 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)
			try
			{
				EnsureRootExists();
				root.transform.SetParent(elevator, false);
				root.transform.localPosition = Vector3.zero;
				root.transform.localRotation = Quaternion.identity;
				UpdateVisibility();
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error showing grid overlay: {arg}");
				}
			}
		}

		public void Hide()
		{
			try
			{
				if ((Object)(object)root != (Object)null)
				{
					root.SetActive(false);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error hiding grid overlay: {arg}");
				}
			}
		}

		public void Rebuild()
		{
			try
			{
				if (!((Object)(object)root == (Object)null) && root.activeSelf)
				{
					ClearLines();
					CreateGridLines();
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error rebuilding grid: {arg}");
				}
			}
		}

		private void EnsureRootExists()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if ((Object)(object)root != (Object)null)
			{
				return;
			}
			root = new GameObject("GridSnapOverlay");
			try
			{
				int num = LayerMask.NameToLayer("TransparentFX");
				if (num != -1)
				{
					root.layer = num;
				}
			}
			catch
			{
			}
			root.SetActive(false);
			CreateLineMaterial();
		}

		private void CreateLineMaterial()
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string[] array = new string[3] { "Sprites/Default", "Legacy Shaders/Transparent/Diffuse", "Unlit/Color" };
				Shader val = null;
				string[] array2 = array;
				foreach (string text in array2)
				{
					val = Shader.Find(text);
					if ((Object)(object)val != (Object)null)
					{
						break;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					ManualLogSource logger = GridSnapPlugin.Logger;
					if (logger != null)
					{
						logger.LogWarning((object)"Could not find suitable shader for grid lines");
					}
				}
				else
				{
					lineMaterial = new Material(val);
					lineMaterial.color = GridSnapPlugin.GridLineColor.Value;
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger2 = GridSnapPlugin.Logger;
				if (logger2 != null)
				{
					logger2.LogError((object)$"Error creating line material: {arg}");
				}
			}
		}

		private void ClearLines()
		{
			foreach (LineRenderer lineRenderer in lineRenderers)
			{
				if ((Object)(object)lineRenderer != (Object)null && (Object)(object)((Component)lineRenderer).gameObject != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)((Component)lineRenderer).gameObject);
				}
			}
			lineRenderers.Clear();
		}

		private void CreateGridLines()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			float value = GridSnapPlugin.GridSize.Value;
			if (value <= 0f)
			{
				return;
			}
			float value2 = GridSnapPlugin.GridDisplayExtent.Value;
			int value3 = GridSnapPlugin.GridMajorLineEvery.Value;
			int num = Mathf.CeilToInt(value2 * 2f / value);
			float num2 = 0f - value2;
			float num3 = value2;
			for (int i = 0; i <= num; i++)
			{
				float num4 = num2 + (float)i * value;
				if (!(Mathf.Abs(num4) > value2))
				{
					bool isMajor = i % value3 == 0;
					CreateLine(new Vector3(num2, 0.01f, num4), new Vector3(num3, 0.01f, num4), isMajor);
				}
			}
			for (int j = 0; j <= num; j++)
			{
				float num5 = num2 + (float)j * value;
				if (!(Mathf.Abs(num5) > value2))
				{
					bool isMajor2 = j % value3 == 0;
					CreateLine(new Vector3(num5, 0.01f, num2), new Vector3(num5, 0.01f, num3), isMajor2);
				}
			}
		}

		private void CreateLine(Vector3 start, Vector3 end, bool isMajor)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject val = new GameObject("GridLine");
				val.transform.SetParent(root.transform, false);
				val.layer = root.layer;
				LineRenderer val2 = val.AddComponent<LineRenderer>();
				if ((Object)(object)lineMaterial != (Object)null)
				{
					((Renderer)val2).material = lineMaterial;
				}
				float startWidth = (val2.endWidth = (isMajor ? GridSnapPlugin.GridMajorLineWidth.Value : GridSnapPlugin.GridMinorLineWidth.Value));
				val2.startWidth = startWidth;
				val2.positionCount = 2;
				val2.SetPosition(0, start);
				val2.SetPosition(1, end);
				val2.useWorldSpace = false;
				try
				{
					val2.numCapVertices = 0;
					val2.numCornerVertices = 0;
				}
				catch
				{
				}
				lineRenderers.Add(val2);
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error creating line: {arg}");
				}
			}
		}

		public void Cleanup()
		{
			try
			{
				ClearLines();
				if ((Object)(object)root != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)root);
				}
				if ((Object)(object)lineMaterial != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)lineMaterial);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error during cleanup: {arg}");
				}
			}
		}
	}
	[HarmonyPatch(typeof(ShipBuildModeManager))]
	public static class ShipBuildModeManager_Patches
	{
		private static FieldInfo placingObjectField;

		private static FieldInfo currentColliderField;

		private static FieldInfo placementMaskAndBlockersField;

		private static FieldInfo canConfirmPositionField;

		static ShipBuildModeManager_Patches()
		{
			try
			{
				Type typeFromHandle = typeof(ShipBuildModeManager);
				placingObjectField = AccessTools.Field(typeFromHandle, "placingObject");
				currentColliderField = AccessTools.Field(typeFromHandle, "currentCollider");
				placementMaskAndBlockersField = AccessTools.Field(typeFromHandle, "placementMaskAndBlockers");
				canConfirmPositionField = AccessTools.Field(typeFromHandle, "CanConfirmPosition");
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Failed to cache reflection fields: {arg}");
				}
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		public static bool Update_Prefix(ShipBuildModeManager __instance)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!__instance.InBuildMode || !GridSnapPlugin.RotationSnapEnabled.Value)
				{
					return true;
				}
				PlaceableShipObject placingObject = GetPlacingObject(__instance);
				if ((Object)(object)placingObject == (Object)null)
				{
					return true;
				}
				if (GetReloadBatteriesInput())
				{
					Transform ghostObject = __instance.ghostObject;
					if ((Object)(object)ghostObject != (Object)null)
					{
						ghostObject.eulerAngles += new Vector3(0f, GridSnapPlugin.RotationSnapAngle.Value, 0f);
						ValidatePlacement(__instance, placingObject);
					}
					return false;
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error in Update_Prefix: {arg}");
				}
			}
			return true;
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		public static void Update_Postfix(ShipBuildModeManager __instance)
		{
			try
			{
				if (!__instance.InBuildMode)
				{
					return;
				}
				PlaceableShipObject placingObject = GetPlacingObject(__instance);
				if ((Object)(object)placingObject == (Object)null)
				{
					return;
				}
				Transform ghostObject = __instance.ghostObject;
				if (!((Object)(object)ghostObject == (Object)null))
				{
					if (GridSnapPlugin.GridEnabled.Value && (!placingObject.AllowPlacementOnWalls || GridSnapPlugin.SnapOnWalls.Value))
					{
						ApplyGridSnapping(ghostObject);
					}
					if (GridSnapPlugin.RotationSnapEnabled.Value)
					{
						ApplyRotationSnapping(ghostObject);
					}
					ValidatePlacement(__instance, placingObject);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error in Update_Postfix: {arg}");
				}
			}
		}

		[HarmonyPatch("CreateGhostObjectAndHighlight")]
		[HarmonyPostfix]
		public static void CreateGhostObjectAndHighlight_Postfix(ShipBuildModeManager __instance)
		{
			try
			{
				GridSnapPlugin.UpdateBuildModeTip();
				Transform val = StartOfRound.Instance?.elevatorTransform;
				if ((Object)(object)val != (Object)null)
				{
					GridSnapPlugin.Instance?.overlay?.Show(val);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error in CreateGhostObjectAndHighlight_Postfix: {arg}");
				}
			}
		}

		[HarmonyPatch("CancelBuildMode")]
		[HarmonyPostfix]
		public static void CancelBuildMode_Postfix(ShipBuildModeManager __instance)
		{
			try
			{
				GridSnapPlugin.Instance?.overlay?.Hide();
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error in CancelBuildMode_Postfix: {arg}");
				}
			}
		}

		private static PlaceableShipObject GetPlacingObject(ShipBuildModeManager instance)
		{
			try
			{
				object? obj = placingObjectField?.GetValue(instance);
				return (PlaceableShipObject)((obj is PlaceableShipObject) ? obj : null);
			}
			catch
			{
				return null;
			}
		}

		private static bool GetReloadBatteriesInput()
		{
			try
			{
				IngamePlayerSettings instance = IngamePlayerSettings.Instance;
				bool? obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					PlayerInput playerInput = instance.playerInput;
					if (playerInput == null)
					{
						obj = null;
					}
					else
					{
						InputActionAsset actions = playerInput.actions;
						if (actions == null)
						{
							obj = null;
						}
						else
						{
							InputAction obj2 = actions.FindAction("ReloadBatteries", false);
							obj = ((obj2 != null) ? new bool?(obj2.WasPressedThisFrame()) : null);
						}
					}
				}
				bool? flag = obj;
				return flag.GetValueOrDefault();
			}
			catch
			{
				return false;
			}
		}

		private static void ApplyGridSnapping(Transform ghost)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Transform val = StartOfRound.Instance?.elevatorTransform;
				if (!((Object)(object)val == (Object)null))
				{
					float value = GridSnapPlugin.GridSize.Value;
					Vector3 val2 = val.InverseTransformPoint(ghost.position);
					val2.x = Mathf.Round(val2.x / value) * value;
					val2.z = Mathf.Round(val2.z / value) * value;
					ghost.position = val.TransformPoint(val2);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error applying grid snapping: {arg}");
				}
			}
		}

		private static void ApplyRotationSnapping(Transform ghost)
		{
			//IL_000e: 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)
			//IL_0016: 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)
			try
			{
				float value = GridSnapPlugin.RotationSnapAngle.Value;
				Vector3 eulerAngles = ghost.eulerAngles;
				eulerAngles.y = Mathf.Round(eulerAngles.y / value) * value;
				ghost.eulerAngles = eulerAngles;
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error applying rotation snapping: {arg}");
				}
			}
		}

		private static void ValidatePlacement(ShipBuildModeManager instance, PlaceableShipObject placingObject)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Transform ghostObject = instance.ghostObject;
				if (!((Object)(object)ghostObject == (Object)null))
				{
					BoxCollider currentCollider = GetCurrentCollider(instance, placingObject);
					if (!((Object)(object)currentCollider == (Object)null))
					{
						int placementMask = GetPlacementMask(instance);
						bool flag = CheckCollisions(ghostObject, currentCollider, placingObject, placementMask);
						bool flag2 = IsWithinShipBounds(ghostObject.position);
						bool canConfirm = !flag && flag2;
						SetCanConfirmPosition(instance, canConfirm);
						UpdateGhostMaterial(instance, flag);
					}
				}
			}
			catch (Exception arg)
			{
				ManualLogSource logger = GridSnapPlugin.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"Error validating placement: {arg}");
				}
			}
		}

		private static BoxCollider GetCurrentCollider(ShipBuildModeManager instance, PlaceableShipObject placingObject)
		{
			try
			{
				object? obj = currentColliderField?.GetValue(instance);
				BoxCollider val = (BoxCollider)((obj is BoxCollider) ? obj : null);
				return (BoxCollider)(((object)val) ?? ((object)/*isinst with value type is only supported in some contexts*/));
			}
			catch
			{
				return null;
			}
		}

		private static int GetPlacementMask(ShipBuildModeManager instance)
		{
			try
			{
				return (int)(placementMaskAndBlockersField?.GetValue(instance) ?? ((object)0));
			}
			catch
			{
				return 0;
			}
		}

		private static bool CheckCollisions(Transform ghost, BoxCollider collider, PlaceableShipObject placingObject, int placementMask)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: 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)
			//IL_001d: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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)
			try
			{
				bool flag = Physics.CheckBox(ghost.position, collider.size * 0.5f * 0.5f, ghost.rotation, placementMask, (QueryTriggerInteraction)1);
				if (!flag && placingObject.doCollisionPointCheck)
				{
					Vector3 val = ghost.position + ghost.forward * placingObject.collisionPointCheck.z + ghost.right * placingObject.collisionPointCheck.x + ghost.up * placingObject.collisionPointCheck.y;
					flag = Physics.CheckSphere(val, 1f * ((Component)ghost).transform.localScale.x, placementMask, (QueryTriggerInteraction)1);
				}
				return flag;
			}
			catch
			{
				return false;
			}
		}

		private static bool IsWithinShipBounds(Vector3 position)
		{
			//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
			{
				StartOfRound instance = StartOfRound.Instance;
				bool? obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					Collider shipInnerRoomBounds = instance.shipInnerRoomBounds;
					if (shipInnerRoomBounds == null)
					{
						obj = null;
					}
					else
					{
						Bounds bounds = shipInnerRoomBounds.bounds;
						obj = ((Bounds)(ref bounds)).Contains(position);
					}
				}
				bool? flag = obj;
				return flag.GetValueOrDefault();
			}
			catch
			{
				return true;
			}
		}

		private static void SetCanConfirmPosition(ShipBuildModeManager instance, bool canConfirm)
		{
			try
			{
				canConfirmPositionField?.SetValue(instance, canConfirm);
			}
			catch
			{
			}
		}

		private static void UpdateGhostMaterial(ShipBuildModeManager instance, bool blocked)
		{
			try
			{
				if ((Object)(object)instance.ghostObjectRenderer != (Object)null)
				{
					((Renderer)instance.ghostObjectRenderer).sharedMaterial = (blocked ? instance.ghostObjectRed : instance.ghostObjectGreen);
				}
			}
			catch
			{
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}