Decompiled source of QuestFreecam v1.0.0

Mods/QuestFreecam.dll

Decompiled 4 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BoneLib;
using BoneLib.BoneMenu;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.Input;
using Il2CppSLZ.Marrow.Utilities;
using Il2CppSLZ.VRMK;
using Il2CppSystem;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using QuestFreecam;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(FreecamController), "QuestFreecam", "1.0.0", "QuestFreecam", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: MelonAdditionalDependencies(new string[] { "BoneLib" })]
[assembly: HarmonyDontPatchAll]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("QuestFreecam")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("QuestFreecam")]
[assembly: AssemblyTitle("QuestFreecam")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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;
		}
	}
}
namespace QuestFreecam
{
	internal sealed class AvatarVisibilityUnlocker
	{
		private readonly record struct MeshState(Renderer Mesh, bool Enabled, bool Hidden, ShadowCastingMode Shadows)
		{
			[CompilerGenerated]
			public void Deconstruct(out Renderer Mesh, out bool Enabled, out bool Hidden, out ShadowCastingMode Shadows)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Expected I4, but got Unknown
				Mesh = this.Mesh;
				Enabled = this.Enabled;
				Hidden = this.Hidden;
				Shadows = (ShadowCastingMode)(int)this.Shadows;
			}
		}

		private readonly record struct HeadPose(Vector3 Position, Quaternion Rotation)
		{
			public HeadPose(Vector3 Position, Quaternion Rotation)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: 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)
				this.Position = Position;
				this.Rotation = Rotation;
			}

			public HeadPose(Transform bone)
				: this(bone.localPosition, bone.localRotation)
			{
			}//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)


			public void Apply(Transform bone)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				bone.SetLocalPositionAndRotation(Position, Rotation);
			}
		}

		private readonly record struct HeadState(Transform Bone, Vector3? HiddenScale, HeadPose? BeforeStockUpdate, HeadPose? HiddenPose);

		private readonly RigBinding _binding;

		private readonly int _originalMask;

		private readonly List<MeshState> _meshes = new List<MeshState>();

		private readonly List<HeadState> _heads = new List<HeadState>();

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

		public AvatarVisibilityUnlocker(RigBinding binding, int originalMask)
		{
			_binding = binding;
			_originalMask = originalMask;
			Avatar avatar = binding.Avatar;
			Add(avatar.bodyMeshes);
			Add(avatar.headMeshes);
			Add(avatar.hairMeshes);
			Animator animator = avatar.animator;
			if (Native.Alive((Object?)(object)animator) && animator.isHuman)
			{
				AddHead(animator.GetBoneTransform((HumanBodyBones)10));
			}
			ArtRig componentInChildren = ((Component)binding.Manager).GetComponentInChildren<ArtRig>();
			if (Native.Alive((Object?)(object)componentInChildren))
			{
				AddHead(componentInChildren.artHead);
			}
		}

		private void Add(Il2CppReferenceArray<SkinnedMeshRenderer>? meshes)
		{
			if (meshes != null && !((Il2CppObjectBase)meshes).WasCollected)
			{
				for (int i = 0; i < ((Il2CppArrayBase<SkinnedMeshRenderer>)(object)meshes).Length; i++)
				{
					Add((Renderer?)(object)((Il2CppArrayBase<SkinnedMeshRenderer>)(object)meshes)[i]);
				}
			}
		}

		private void Add(Renderer? mesh)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (Native.Alive((Object?)(object)mesh) && ((Component)mesh).transform.IsChildOf(((Component)_binding.Avatar).transform) && _known.Add(((Object)mesh).GetInstanceID()))
			{
				_meshes.Add(new MeshState(mesh, mesh.enabled, mesh.forceRenderingOff, mesh.shadowCastingMode));
			}
		}

		private void AddHead(Transform? head)
		{
			if (!Native.Alive((Object?)(object)head) || !head.IsChildOf(((Component)_binding.Avatar).transform) || Native.Same((Object?)(object)head, (Object?)(object)((Rig)_binding.Physics).m_head) || Native.Alive((Object?)(object)((Component)head).GetComponent<Rigidbody>()))
			{
				return;
			}
			foreach (HeadState head2 in _heads)
			{
				if (Native.Same((Object?)(object)head2.Bone, (Object?)(object)head))
				{
					return;
				}
			}
			_heads.Add(new HeadState(head, null, null, null));
			Il2CppArrayBase<Renderer> componentsInChildren = ((Component)head).GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Renderer val = componentsInChildren[i];
				if (Native.Alive((Object?)(object)val) && (((Il2CppObjectBase)val).TryCast<MeshRenderer>() != null || ((Il2CppObjectBase)val).TryCast<SkinnedMeshRenderer>() != null))
				{
					Add(val);
				}
			}
		}

		public void BeforeHeadUpdate()
		{
			for (int i = 0; i < _heads.Count; i++)
			{
				HeadState headState = _heads[i];
				if (Native.Alive((Object?)(object)headState.Bone))
				{
					_heads[i] = headState with
					{
						BeforeStockUpdate = new HeadPose(headState.Bone)
					};
				}
			}
		}

		public void AfterHeadUpdate()
		{
			for (int i = 0; i < _heads.Count; i++)
			{
				HeadState headState = _heads[i];
				if (!Native.Alive((Object?)(object)headState.Bone))
				{
					continue;
				}
				HeadPose? beforeStockUpdate = headState.BeforeStockUpdate;
				if (beforeStockUpdate.HasValue)
				{
					HeadPose valueOrDefault = beforeStockUpdate.GetValueOrDefault();
					HeadPose headPose = new HeadPose(headState.Bone);
					_heads[i] = headState with
					{
						BeforeStockUpdate = null,
						HiddenPose = headPose
					};
					if (valueOrDefault != headPose)
					{
						valueOrDefault.Apply(headState.Bone);
					}
				}
			}
			Apply();
		}

		public void Apply()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Invalid comparison between Unknown and I4
			int num = 0;
			for (int i = 0; i < _heads.Count; i++)
			{
				HeadState headState = _heads[i];
				if (Native.Alive((Object?)(object)headState.Bone))
				{
					Vector3 localScale = headState.Bone.localScale;
					if (Collapsed(localScale))
					{
						_heads[i] = headState with
						{
							HiddenScale = localScale
						};
						headState.Bone.localScale = Vector3.one;
					}
				}
			}
			foreach (MeshState mesh2 in _meshes)
			{
				Renderer mesh = mesh2.Mesh;
				if (Native.Alive((Object?)(object)mesh))
				{
					num |= 1 << ((Component)mesh).gameObject.layer;
					if (!mesh.enabled)
					{
						mesh.enabled = true;
					}
					if (mesh.forceRenderingOff)
					{
						mesh.forceRenderingOff = false;
					}
					if ((int)mesh.shadowCastingMode != 1)
					{
						mesh.shadowCastingMode = (ShadowCastingMode)1;
					}
				}
			}
			Camera camera = _binding.Camera;
			if (Native.Alive((Object?)(object)camera) && (camera.cullingMask & num) != num)
			{
				camera.cullingMask |= num;
			}
		}

		public void Restore(Action<string> log)
		{
			foreach (MeshState saved in _meshes)
			{
				Native.Restore(delegate
				{
					//IL_005a: Unknown result type (might be due to invalid IL or missing references)
					if (Native.Alive((Object?)(object)saved.Mesh))
					{
						saved.Mesh.enabled = saved.Enabled;
						saved.Mesh.forceRenderingOff = saved.Hidden;
						saved.Mesh.shadowCastingMode = saved.Shadows;
					}
				}, log);
			}
			foreach (HeadState saved2 in _heads)
			{
				Native.Restore(delegate
				{
					//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_003b: Unknown result type (might be due to invalid IL or missing references)
					if (Native.Alive((Object?)(object)saved2.Bone))
					{
						Vector3? hiddenScale = saved2.HiddenScale;
						if (hiddenScale.HasValue)
						{
							Vector3 valueOrDefault = hiddenScale.GetValueOrDefault();
							saved2.Bone.localScale = valueOrDefault;
						}
						saved2.HiddenPose?.Apply(saved2.Bone);
					}
				}, log);
			}
			Native.Restore(delegate
			{
				if (Native.Alive((Object?)(object)_binding.Camera))
				{
					_binding.Camera.cullingMask = _originalMask;
				}
			}, log);
		}

		private static bool Collapsed(Vector3 scale)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (Mathf.Abs(scale.x) <= 0.05f && Mathf.Abs(scale.y) <= 0.05f)
			{
				return Mathf.Abs(scale.z) <= 0.05f;
			}
			return false;
		}
	}
	public sealed class FreecamController : MelonMod
	{
		private readonly PressEdge _toggleEdge = new PressEdge();

		private readonly PressEdge _leftSnap = new PressEdge();

		private readonly PressEdge _rightSnap = new PressEdge();

		private Settings _settings;

		private RigBinding? _candidate;

		private RigManager? _lastRig;

		private RigManager? _retiredRig;

		private FreecamRig? _rig;

		private AvatarVisibilityUnlocker? _avatar;

		private OverlaySuppressor? _overlays;

		private int _originalMask;

		private double? _pendingUntil;

		private double _scanAt;

		private double _fallbackAt;

		private bool _waitingForLevel;

		private bool _ready;

		private bool _nativeFailure;

		private ToggleCombo _lastCombo;

		private EventInfo? _referencesFound;

		private Delegate? _referencesCallback;

		internal static FreecamController? Instance { get; private set; }

		public override void OnInitializeMelon()
		{
			_settings = new Settings();
			try
			{
				((MelonBase)this).HarmonyInstance.PatchAll(typeof(FreecamController).Assembly);
				Hooking.OnLevelLoading += LevelLoading;
				Hooking.OnLevelLoaded += LevelLoaded;
				Hooking.OnLevelUnloaded += LevelUnloaded;
				Hooking.OnSwitchAvatarPrefix += AvatarChanging;
				Hooking.OnSwitchAvatarPostfix += AvatarChanged;
				Hooking.OnPlayerResurrected += PlayerResurrected;
				SubscribeReferencesFound();
				_lastCombo = _settings.Combo;
				Instance = this;
				_ready = true;
				RestartDiscovery();
				((MelonBase)this).LoggerInstance.Msg("QuestFreecam ready. BoneMenu > Quest Freecam.");
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Error("Could not install QuestFreecam hooks: " + ex.GetBaseException().Message);
				((MelonBase)this).OnDeinitializeMelon();
			}
		}

		public override void OnUpdate()
		{
			if (!_ready)
			{
				return;
			}
			try
			{
				double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
				if (_nativeFailure)
				{
					_nativeFailure = false;
					Reset("native tracking changed");
				}
				if (!_settings.Enabled || !Application.isFocused)
				{
					Exit("disabled or headset focus lost");
					ClearIntent();
				}
				FreecamRig rig = _rig;
				if (rig != null && (!rig.Binding.Current() || !rig.Owned))
				{
					Reset("local rig or stereo camera changed");
				}
				if (realtimeSinceStartupAsDouble >= _scanAt)
				{
					_scanAt = realtimeSinceStartupAsDouble + 0.25;
					_settings.EnsureMenu(ToggleFromMenu, ApplySettings);
					Discover(realtimeSinceStartupAsDouble);
				}
				if (_settings.Enabled && Application.isFocused)
				{
					FreecamInput freecamInput = ReadInput();
					ToggleCombo combo = _settings.Combo;
					if (combo != _lastCombo)
					{
						_toggleEdge.Reset();
					}
					_lastCombo = combo;
					bool down;
					bool flag = freecamInput.TryChord(combo, out down);
					if (_toggleEdge.Read(down, flag && !IsPaused()))
					{
						RequestToggle(realtimeSinceStartupAsDouble);
					}
				}
				DeliverIntent(realtimeSinceStartupAsDouble);
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		public override void OnLateUpdate()
		{
			FreecamRig rig = _rig;
			if (rig == null)
			{
				return;
			}
			try
			{
				if (!rig.Binding.Current() || !rig.Owned || !HeadPose.TryRead(out var pose))
				{
					Reset("tracking unavailable");
					return;
				}
				if (IsPaused())
				{
					rig.PauseFlight();
					_leftSnap.Reset();
					_rightSnap.Reset();
					rig.ApplyPose(pose);
				}
				else
				{
					FreecamInput input = ReadInput();
					bool flag = _leftSnap.Read(input.Left.Primary, input.Left.Connected);
					bool flag2 = _rightSnap.Read(input.Right.Primary, input.Right.Connected);
					rig.Fly(pose, input, _settings, flag || flag2, Time.unscaledDeltaTime);
				}
				_avatar?.Apply();
				_overlays?.Apply(Time.realtimeSinceStartupAsDouble);
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		private static FreecamInput ReadInput()
		{
			XRApi xr = MarrowGame.xr;
			if (xr != null && !((Il2CppObjectBase)xr).WasCollected)
			{
				return new FreecamInput(HandInput.Read(xr.LeftController), HandInput.Read(xr.RightController));
			}
			return default(FreecamInput);
		}

		private static bool IsPaused()
		{
			OpenControllerRig controllerRig = Player.ControllerRig;
			if (Native.Alive((Object?)(object)controllerRig))
			{
				if (!((ControllerRig)controllerRig).IsPaused)
				{
					return controllerRig._isPlatformPaused;
				}
				return true;
			}
			return false;
		}

		private void Discover(double now)
		{
			RigManager rigManager = Player.RigManager;
			if (!Native.Alive((Object?)(object)rigManager) || Native.Same((Object?)(object)rigManager, (Object?)(object)_retiredRig))
			{
				_candidate = null;
				return;
			}
			FreecamRig rig = _rig;
			if (rig != null)
			{
				RigBinding binding = rig.Binding;
				Camera val = RigBinding.FindCamera(binding.Manager, binding.Controls, allowMainCamera: false);
				if (Native.Alive((Object?)(object)val) && !Native.Same((Object?)(object)val, (Object?)(object)binding.Camera))
				{
					Reset("the game supplied a replacement headset camera");
				}
				return;
			}
			_candidate = RigBinding.Find(rigManager, now >= _fallbackAt);
			if (_waitingForLevel && (object)_candidate != null)
			{
				_waitingForLevel = false;
				((MelonBase)this).LoggerInstance.Msg("Recovered a new playable stereo rig.");
			}
			if (!_waitingForLevel)
			{
				_lastRig = rigManager;
			}
		}

		private void ToggleFromMenu()
		{
			try
			{
				RequestToggle(Time.realtimeSinceStartupAsDouble);
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		private void RequestToggle(double now)
		{
			if (_rig != null)
			{
				Exit("toggled off");
				return;
			}
			double? pendingUntil = _pendingUntil;
			if (pendingUntil.HasValue)
			{
				_pendingUntil = null;
				((MelonBase)this).LoggerInstance.Msg("Freecam request cancelled.");
			}
			else if (_ready && _settings.Enabled)
			{
				_pendingUntil = now + 12.0;
				_scanAt = 0.0;
				Discover(now);
				DeliverIntent(now);
				pendingUntil = _pendingUntil;
				if (pendingUntil.HasValue)
				{
					((MelonBase)this).LoggerInstance.Msg("Freecam queued until the headset rig and gameplay input are ready.");
				}
			}
		}

		private void DeliverIntent(double now)
		{
			double? pendingUntil = _pendingUntil;
			if (!pendingUntil.HasValue)
			{
				return;
			}
			double valueOrDefault = pendingUntil.GetValueOrDefault();
			if (now >= valueOrDefault)
			{
				_pendingUntil = null;
				((MelonBase)this).LoggerInstance.Warning("Freecam request expired while waiting for a playable headset.");
			}
			else
			{
				if (_waitingForLevel || !_settings.Enabled || !Application.isFocused || IsPaused())
				{
					return;
				}
				RigBinding candidate = _candidate;
				if ((object)candidate != null && candidate.Current() && HeadPose.TryRead(out var pose))
				{
					_pendingUntil = null;
					_originalMask = candidate.Camera.cullingMask;
					FreecamRig rig = new FreecamRig(candidate, pose);
					_rig = rig;
					rig.Attach(pose, delegate
					{
						PostStockEyeTracking(rig);
					});
					_leftSnap.Reset();
					_rightSnap.Reset();
					ApplySettings();
					if (_rig != null)
					{
						((MelonBase)this).LoggerInstance.Msg("Freecam active on " + ((Object)candidate.Camera).name + ".");
					}
				}
			}
		}

		private void ApplySettings()
		{
			try
			{
				if (!_settings.Enabled)
				{
					ClearIntent();
					Exit("disabled in BoneMenu");
					return;
				}
				FreecamRig rig = _rig;
				if (rig == null)
				{
					return;
				}
				if (_settings.FullAvatar)
				{
					if (_avatar == null)
					{
						_avatar = new AvatarVisibilityUnlocker(rig.Binding, _originalMask);
					}
					_avatar.Apply();
				}
				else
				{
					_avatar?.Restore(LogRestoreError);
					_avatar = null;
				}
				if (_settings.IgnoreEffects)
				{
					if (_overlays == null)
					{
						_overlays = new OverlaySuppressor(rig.Binding.Camera);
					}
					_overlays.Apply(Time.realtimeSinceStartupAsDouble);
				}
				else
				{
					_overlays?.Restore(LogRestoreError);
					_overlays = null;
				}
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		private void LevelLoading(LevelInfo _)
		{
			BeginTransition();
		}

		private void LevelUnloaded()
		{
			BeginTransition();
		}

		private void BeginTransition()
		{
			if (_waitingForLevel)
			{
				_scanAt = 0.0;
				return;
			}
			RigManager val = _rig?.Binding.Manager ?? _lastRig ?? Player.RigManager;
			if (Native.Alive((Object?)(object)val))
			{
				_retiredRig = val;
			}
			_lastRig = null;
			_waitingForLevel = true;
			Reset("level transition");
		}

		private void LevelLoaded(LevelInfo _)
		{
			if (!_waitingForLevel && _lastRig != null)
			{
				ClearIntent();
			}
			_waitingForLevel = false;
			InvalidateBinding("level loaded");
		}

		private void AvatarChanging(Avatar _)
		{
			InvalidateBinding("avatar changing");
		}

		private void AvatarChanged(Avatar _)
		{
			InvalidateBinding("avatar changed");
		}

		private void PlayerResurrected(RigManager manager)
		{
			if (Native.Same((Object?)(object)manager, (Object?)(object)Player.RigManager))
			{
				Reset("player respawned");
			}
		}

		private void RestartDiscovery()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			_scanAt = 0.0;
			_fallbackAt = Time.realtimeSinceStartupAsDouble + (double)(((int)Application.platform == 11) ? 5 : 0);
		}

		private void ClearIntent()
		{
			_pendingUntil = null;
			_toggleEdge.Reset();
		}

		private void Reset(string reason)
		{
			ClearIntent();
			InvalidateBinding(reason);
		}

		private void InvalidateBinding(string reason)
		{
			Exit(reason);
			_candidate = null;
			RestartDiscovery();
		}

		private void Exit(string reason)
		{
			FreecamRig rig = _rig;
			if (rig != null)
			{
				_rig = null;
				AvatarVisibilityUnlocker avatar = _avatar;
				OverlaySuppressor overlays = _overlays;
				_avatar = null;
				_overlays = null;
				Native.Restore(delegate
				{
					rig.Restore(LogRestoreError);
				}, LogRestoreError);
				Native.Restore(delegate
				{
					avatar?.Restore(LogRestoreError);
				}, LogRestoreError);
				Native.Restore(delegate
				{
					overlays?.Restore(LogRestoreError);
				}, LogRestoreError);
				_leftSnap.Reset();
				_rightSnap.Reset();
				_scanAt = 0.0;
				((MelonBase)this).LoggerInstance.Msg("Freecam released: " + reason + ".");
			}
		}

		private void Fail(Exception error)
		{
			if (!Native.Lost(error))
			{
				((MelonBase)this).LoggerInstance.Error(error.GetBaseException().Message);
			}
			Reset("rig operation failed");
		}

		private void LogRestoreError(string error)
		{
			((MelonBase)this).LoggerInstance.Warning("Freecam restore: " + error);
		}

		private void SubscribeReferencesFound()
		{
			_referencesFound = typeof(Hooking).GetEvent("OnPlayerReferencesFound");
			if (!(_referencesFound?.EventHandlerType != typeof(Action)))
			{
				_referencesCallback = (Action)delegate
				{
					_scanAt = 0.0;
				};
				_referencesFound.AddEventHandler(null, _referencesCallback);
			}
		}

		public override void OnDeinitializeMelon()
		{
			_ready = false;
			if (Instance == this)
			{
				Instance = null;
			}
			ClearIntent();
			Exit("mod unloaded");
			Hooking.OnLevelLoading -= LevelLoading;
			Hooking.OnLevelLoaded -= LevelLoaded;
			Hooking.OnLevelUnloaded -= LevelUnloaded;
			Hooking.OnSwitchAvatarPrefix -= AvatarChanging;
			Hooking.OnSwitchAvatarPostfix -= AvatarChanged;
			Hooking.OnPlayerResurrected -= PlayerResurrected;
			if ((object)_referencesCallback != null)
			{
				Native.Restore(delegate
				{
					_referencesFound?.RemoveEventHandler(null, _referencesCallback);
				}, LogRestoreError);
			}
			Native.Restore(delegate
			{
				((MelonBase)this).HarmonyInstance.UnpatchSelf();
			}, LogRestoreError);
			Native.Restore(delegate
			{
				_settings.RemoveMenu();
			}, LogRestoreError);
			_candidate = null;
			_lastRig = null;
			_retiredRig = null;
		}

		internal void RetireIfLocal(RigManager manager)
		{
			if (Native.Same((Object?)(object)(_rig?.Binding.Manager ?? _lastRig), (Object?)(object)manager))
			{
				BeginTransition();
			}
		}

		internal bool BlocksStick(ControllerRig controls)
		{
			if (!_nativeFailure && _settings.Freeze)
			{
				FreecamRig rig = _rig;
				if (rig != null)
				{
					return Native.Same((Object?)(object)rig.Binding.Controls, (Object?)(object)controls);
				}
			}
			return false;
		}

		internal void UpdateAvatarHead(PlayerAvatarArt art, bool before)
		{
			if (_avatar == null)
			{
				return;
			}
			FreecamRig rig = _rig;
			if (rig == null)
			{
				return;
			}
			try
			{
				if (Native.Alive((Object?)(object)art) && Native.Same((Object?)(object)art._openCtrlRig, (Object?)(object)rig.Binding.Controls) && rig.Binding.Current())
				{
					if (before)
					{
						_avatar.BeforeHeadUpdate();
					}
					else
					{
						_avatar.AfterHeadUpdate();
					}
				}
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		private void PostStockEyeTracking(FreecamRig rig)
		{
			if (_nativeFailure || _rig != rig)
			{
				return;
			}
			try
			{
				if (rig.Owned && HeadPose.TryRead(out var pose))
				{
					rig.ApplyPose(pose);
				}
				else
				{
					_nativeFailure = true;
				}
			}
			catch (Exception ex)
			{
				_nativeFailure = true;
				if (!Native.Lost(ex))
				{
					((MelonBase)this).LoggerInstance.Warning("Headset tracking: " + ex.GetBaseException().Message);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ControllerRig), "GetPrimaryAxis")]
	internal static class PrimaryStickPatch
	{
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void HideAxis(ControllerRig __instance, ref Vector2 __result)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			FreecamController? instance = FreecamController.Instance;
			if (instance != null && instance.BlocksStick(__instance))
			{
				__result = Vector2.zero;
			}
		}
	}
	[HarmonyPatch(typeof(OpenControllerRig), "ProcessSecondaryThumbstick", new Type[]
	{
		typeof(Vector2),
		typeof(float)
	})]
	internal static class SecondaryStickPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static void HideTurn(OpenControllerRig __instance, ref Vector2 __0)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			FreecamController? instance = FreecamController.Instance;
			if (instance != null && instance.BlocksStick((ControllerRig)(object)__instance))
			{
				__0 = Vector2.zero;
			}
		}
	}
	[HarmonyPatch(typeof(RigManager), "OnDestroy")]
	internal static class RetiringRigPatch
	{
		[HarmonyPrefix]
		private static void ReleaseBeforeDestroy(RigManager __instance)
		{
			FreecamController.Instance?.RetireIfLocal(__instance);
		}
	}
	[HarmonyPatch(typeof(PlayerAvatarArt), "UpdateAvatarHead")]
	internal static class AvatarArtPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static void CaptureHead(PlayerAvatarArt __instance)
		{
			FreecamController.Instance?.UpdateAvatarHead(__instance, before: true);
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void ShowAvatar(PlayerAvatarArt __instance)
		{
			FreecamController.Instance?.UpdateAvatarHead(__instance, before: false);
		}
	}
	internal readonly record struct HandInput(bool Connected, Vector2 Stick, bool Click, bool Grip, bool Primary, bool Secondary, bool Trigger)
	{
		public static HandInput Read(XRController? hand)
		{
			//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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (hand == null || ((Il2CppObjectBase)hand).WasCollected || !((XRDevice)hand).IsConnected)
			{
				return default(HandInput);
			}
			Vector2 val = hand.Joystick2DAxis;
			if (!float.IsFinite(val.x) || !float.IsFinite(val.y))
			{
				val = Vector2.zero;
			}
			return new HandInput(Connected: true, val, hand.JoystickButton, hand.GripButton || hand.Grip >= 0.65f, hand.AButton, hand.BButton, hand.TriggerButton || hand.Trigger >= 0.65f);
		}
	}
	internal readonly record struct FreecamInput(HandInput Left, HandInput Right)
	{
		public bool TryChord(ToggleCombo combo, out bool down)
		{
			down = combo switch
			{
				ToggleCombo.RightGripClick => Right.Grip && Right.Click, 
				ToggleCombo.LeftYTrigger => Left.Secondary && Left.Trigger, 
				ToggleCombo.RightBTrigger => Right.Secondary && Right.Trigger, 
				_ => Left.Grip && Left.Click, 
			};
			if ((combo != ToggleCombo.RightGripClick && combo != ToggleCombo.RightBTrigger) || 1 == 0)
			{
				return Left.Connected;
			}
			return Right.Connected;
		}
	}
	internal sealed class PressEdge
	{
		private bool _released;

		public bool Read(bool down, bool available)
		{
			if (!available)
			{
				_released = false;
				return false;
			}
			bool result = _released && down;
			_released = !down;
			return result;
		}

		public void Reset()
		{
			_released = false;
		}
	}
	internal readonly record struct HeadPose(Vector3 Position, Quaternion Rotation)
	{
		public static bool TryRead(out HeadPose pose)
		{
			//IL_003f: 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)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			pose = default(HeadPose);
			XRApi xr = MarrowGame.xr;
			if (xr == null || ((Il2CppObjectBase)xr).WasCollected)
			{
				return false;
			}
			XRHMD hMD = xr.HMD;
			if (hMD == null || ((Il2CppObjectBase)hMD).WasCollected || !((XRDevice)hMD).IsConnected || !((XRDevice)hMD).IsTracking)
			{
				return false;
			}
			Vector3 position = ((XRDevice)hMD).Position;
			Quaternion rotation = ((XRDevice)hMD).Rotation;
			float num = Quaternion.Dot(rotation, rotation);
			if (!float.IsFinite(((Vector3)(ref position)).sqrMagnitude) || !float.IsFinite(num) || num < 0.5f)
			{
				return false;
			}
			pose = new HeadPose(position, rotation);
			return true;
		}
	}
	internal sealed class FreecamRig
	{
		private readonly RigBinding _binding;

		private readonly Transform _eye;

		private readonly Transform _originalParent;

		private readonly Transform _originalHeadset;

		private readonly Vector3 _savedPosition;

		private readonly Vector3 _savedScale;

		private readonly Vector3 _hmdOrigin;

		private readonly Quaternion _savedRotation;

		private readonly Quaternion _inverseHmdYaw;

		private readonly int _sibling;

		private GameObject? _anchor;

		private GameObject? _trackingReference;

		private Action? _stockPoseCallback;

		private Vector3 _velocity;

		private bool _snapReady;

		private TurnMode? _lastTurnMode;

		public RigBinding Binding => _binding;

		public bool Owned
		{
			get
			{
				if (Native.Alive((Object?)(object)_anchor) && Native.Alive((Object?)(object)_eye) && Native.Alive((Object?)(object)_originalParent) && Native.Same((Object?)(object)_eye.parent, (Object?)(object)_anchor.transform))
				{
					return Native.Same((Object?)(object)_binding.Controls.headset, (Object?)(object)ExpectedHeadset);
				}
				return false;
			}
		}

		private Transform ExpectedHeadset
		{
			get
			{
				if (!Native.Alive((Object?)(object)_trackingReference))
				{
					return _originalHeadset;
				}
				return _trackingReference.transform;
			}
		}

		public FreecamRig(RigBinding binding, HeadPose pose)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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)
			//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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			_binding = binding;
			_eye = ((Component)binding.Camera).transform;
			_originalParent = _eye.parent;
			_originalHeadset = binding.Controls.headset;
			if (!Native.Alive((Object?)(object)_originalParent) || !Native.Alive((Object?)(object)_originalHeadset))
			{
				throw new InvalidOperationException("The headset tracking hierarchy is not ready.");
			}
			_savedPosition = _eye.localPosition;
			_savedRotation = _eye.localRotation;
			_savedScale = _eye.localScale;
			_sibling = _eye.GetSiblingIndex();
			_hmdOrigin = pose.Position;
			_inverseHmdYaw = Quaternion.Inverse(Quaternion.LookRotation(Flat(pose.Rotation * Vector3.forward, Vector3.forward)));
		}

		public void Attach(HeadPose pose, Action syncTrackedPose)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_001b: 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)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: 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)
			_anchor = new GameObject("QuestFreecamAnchor");
			Scene scene = ((Component)_originalParent).gameObject.scene;
			if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded)
			{
				Scene scene2 = _anchor.scene;
				if (((Scene)(ref scene2)).handle != ((Scene)(ref scene)).handle && ((Scene)(ref scene)).name != "DontDestroyOnLoad")
				{
					SceneManager.MoveGameObjectToScene(_anchor, scene);
				}
			}
			if (Native.Same((Object?)(object)_eye, (Object?)(object)_originalHeadset))
			{
				_trackingReference = new GameObject("QuestFreecamTrackingReference");
				Transform transform = _trackingReference.transform;
				transform.SetParent(_originalParent, false);
				transform.localPosition = _savedPosition;
				transform.localRotation = _savedRotation;
				transform.localScale = _savedScale;
				_binding.Controls.headset = transform;
			}
			_eye.SetParent(_anchor.transform, false);
			if (!Owned)
			{
				throw new InvalidOperationException("Could not acquire the headset tracking hierarchy.");
			}
			_eye.localScale = _savedScale;
			Place(pose, inFront: false);
			_stockPoseCallback = Action.op_Implicit(syncTrackedPose);
			OpenControllerRig controls = _binding.Controls;
			controls.onLastCameraUpdate += _stockPoseCallback;
		}

		public void Fly(HeadPose pose, FreecamInput input, Settings settings, bool recenter, float deltaTime)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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_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_00fb: 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)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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_0076: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			if (recenter)
			{
				Place(pose, inFront: true);
				return;
			}
			Transform transform = _anchor.transform;
			float num = Mathf.Clamp(deltaTime, 0f, 0.05f);
			float num2 = Turn(input.Right.Stick.x, settings.Turn, settings.TurnSpeed, num);
			if (!Mathf.Approximately(num2, 0f))
			{
				Vector3 val = pose.Position - _hmdOrigin;
				Vector3 val2 = transform.TransformPoint(val);
				transform.rotation = Quaternion.AngleAxis(num2, Vector3.up) * transform.rotation;
				transform.position += val2 - transform.TransformPoint(val);
			}
			Vector3 val3 = Flat(transform.rotation * pose.Rotation * Vector3.forward, transform.forward);
			Vector3 val4 = Vector3.Cross(Vector3.up, val3);
			Vector2 val5 = DeadZone(input.Left.Stick);
			Vector2 val6 = DeadZone(new Vector2(0f, input.Right.Stick.y));
			Vector3 val7 = val3 * val5.y + val4 * val5.x + Vector3.up * val6.y;
			float num3 = (input.Left.Trigger ? 0.35f : (input.Right.Trigger ? 2.5f : 1f));
			Vector3 val8 = Vector3.ClampMagnitude(val7, 1f) * (settings.Speed * num3);
			float smoothing = settings.Smoothing;
			float num4 = ((smoothing == 0f) ? 1f : (1f - Mathf.Exp((0f - num) / smoothing)));
			_velocity = Vector3.Lerp(_velocity, val8, num4);
			transform.position += _velocity * num;
			ApplyPose(pose);
		}

		public void PauseFlight()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			_velocity = Vector3.zero;
			_snapReady = false;
		}

		public void ApplyPose(HeadPose pose)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//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_0025: Unknown result type (might be due to invalid IL or missing references)
			_eye.localPosition = pose.Position - _hmdOrigin;
			_eye.localRotation = pose.Rotation;
		}

		private void Place(HeadPose pose, bool inFront)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_007d: 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_0084: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			Transform head = ((Rig)_binding.Physics).m_head;
			Transform pelvis = ((Rig)_binding.Physics).m_pelvis;
			Vector3 val = Flat(pelvis.forward, Flat(((Component)_binding.Manager).transform.forward, Vector3.forward));
			Vector3 val2 = Vector3.Cross(Vector3.up, val);
			Vector3 val4;
			if (!inFront)
			{
				Vector3 val3 = -val + 0.7f * val2;
				val4 = ((Vector3)(ref val3)).normalized;
			}
			else
			{
				val4 = val;
			}
			Vector3 val5 = val4;
			Vector3 val6 = Vector3.Lerp(pelvis.position, head.position, 0.78f);
			Transform transform = _anchor.transform;
			Quaternion val7 = Quaternion.LookRotation(-val5, Vector3.up) * _inverseHmdYaw;
			Vector3 val8 = val6 + val5 * (inFront ? 2f : 1.8f);
			transform.SetPositionAndRotation(val8 - val7 * (pose.Position - _hmdOrigin), val7);
			_velocity = Vector3.zero;
			ApplyPose(pose);
		}

		private float Turn(float x, TurnMode mode, float speed, float dt)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (_lastTurnMode != mode)
			{
				_snapReady = false;
			}
			_lastTurnMode = mode;
			if (mode == TurnMode.Smooth)
			{
				return DeadZone(new Vector2(x, 0f)).x * speed * dt;
			}
			if (Mathf.Abs(x) <= 0.22f)
			{
				_snapReady = true;
			}
			if (!_snapReady || Mathf.Abs(x) < 0.7f)
			{
				return 0f;
			}
			_snapReady = false;
			return Mathf.Sign(x) * 30f;
		}

		private static Vector2 DeadZone(Vector2 stick)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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)
			float magnitude = ((Vector2)(ref stick)).magnitude;
			if (!(magnitude <= 0.18f))
			{
				return stick * (Mathf.InverseLerp(0.18f, 1f, magnitude) / magnitude);
			}
			return Vector2.zero;
		}

		private static Vector3 Flat(Vector3 forward, Vector3 fallback)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			forward.y = 0f;
			if (!(((Vector3)(ref forward)).sqrMagnitude >= 0.0001f))
			{
				return fallback;
			}
			return ((Vector3)(ref forward)).normalized;
		}

		public void Restore(Action<string> log)
		{
			Native.Restore(delegate
			{
				if (_stockPoseCallback != null && Native.Alive((Object?)(object)_binding.Controls))
				{
					OpenControllerRig controls = _binding.Controls;
					controls.onLastCameraUpdate -= _stockPoseCallback;
				}
				_stockPoseCallback = null;
			}, log);
			Native.Restore(RestoreEye, log);
			Native.Restore(delegate
			{
				if (Native.Alive((Object?)(object)_trackingReference) && Native.Alive((Object?)(object)_binding.Controls) && Native.Same((Object?)(object)_binding.Controls.headset, (Object?)(object)_trackingReference.transform))
				{
					Transform val = (Native.Alive((Object?)(object)_originalHeadset) ? _originalHeadset : null);
					if (val == null && Native.Alive((Object?)(object)_binding.Manager))
					{
						Camera? obj = RigBinding.FindCamera(_binding.Manager, _binding.Controls, allowMainCamera: false);
						val = ((obj != null) ? ((Component)obj).transform : null);
					}
					_binding.Controls.headset = val;
				}
			}, log);
			Native.Restore(delegate
			{
				if (Native.Alive((Object?)(object)_trackingReference) && (!Native.Alive((Object?)(object)_binding.Controls) || !Native.Same((Object?)(object)_binding.Controls.headset, (Object?)(object)_trackingReference.transform)))
				{
					Object.Destroy((Object)(object)_trackingReference);
				}
			}, log);
			Native.Restore(delegate
			{
				if (Native.Alive((Object?)(object)_anchor) && (!Native.Alive((Object?)(object)_eye) || !Native.Same((Object?)(object)_eye.parent, (Object?)(object)_anchor.transform)))
				{
					Object.Destroy((Object)(object)_anchor);
				}
			}, log);
		}

		private void RestoreEye()
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			if (!Native.Alive((Object?)(object)_eye) || !Native.Alive((Object?)(object)_anchor) || !Native.Same((Object?)(object)_eye.parent, (Object?)(object)_anchor.transform))
			{
				return;
			}
			if (!Native.Alive((Object?)(object)_originalParent))
			{
				Transform val = (Native.Alive((Object?)(object)_binding.Controls) ? _binding.Controls.vrRoot : null);
				if (!Native.Alive((Object?)(object)val) || Native.Same((Object?)(object)val, (Object?)(object)_eye) || val.IsChildOf(_eye))
				{
					_eye.SetParent((Transform)null, true);
					return;
				}
				_eye.SetParent(val, false);
			}
			else
			{
				_eye.SetParent(_originalParent, false);
				_eye.SetSiblingIndex(_sibling);
			}
			_eye.localPosition = _savedPosition;
			_eye.localRotation = _savedRotation;
			_eye.localScale = _savedScale;
		}
	}
	internal static class Native
	{
		public static bool Alive([NotNullWhen(true)] Object? value)
		{
			if (value == null)
			{
				return false;
			}
			try
			{
				return !((Il2CppObjectBase)value).WasCollected && value != (Object)null;
			}
			catch (Exception error) when (Lost(error))
			{
				return false;
			}
		}

		public static bool Same(Object? left, Object? right)
		{
			try
			{
				return Alive(left) && Alive(right) && left == right;
			}
			catch (Exception error) when (Lost(error))
			{
				return false;
			}
		}

		public static bool Lost(Exception error)
		{
			Exception baseException = error.GetBaseException();
			if (!(baseException is ObjectCollectedException))
			{
				if (baseException.GetType().Name == "Il2CppException")
				{
					return baseException.Message.Contains("MissingReferenceException", StringComparison.Ordinal);
				}
				return false;
			}
			return true;
		}

		public static void Restore(Action action, Action<string> log)
		{
			try
			{
				action();
			}
			catch (Exception error) when (Lost(error))
			{
			}
			catch (Exception ex)
			{
				log(ex.GetBaseException().Message);
			}
		}
	}
	internal sealed class OverlaySuppressor
	{
		private const int UiLayer = 5;

		private readonly Camera _camera;

		private readonly List<(MeshRenderer Renderer, bool WasHidden)> _hidden = new List<(MeshRenderer, bool)>();

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

		private double _nextScan;

		private int _directChildren = -1;

		public OverlaySuppressor(Camera camera)
		{
			_camera = camera;
		}

		public void Apply(double now)
		{
			if (!Native.Alive((Object?)(object)_camera))
			{
				return;
			}
			int childCount = ((Component)_camera).transform.childCount;
			if (now >= _nextScan || childCount != _directChildren)
			{
				_directChildren = childCount;
				_nextScan = now + 0.12;
				for (int num = _hidden.Count - 1; num >= 0; num--)
				{
					var (val, forceRenderingOff) = _hidden[num];
					if (!Native.Alive((Object?)(object)val) || !IsAttached(val))
					{
						if (Native.Alive((Object?)(object)val))
						{
							((Renderer)val).forceRenderingOff = forceRenderingOff;
						}
						_hidden.RemoveAt(num);
					}
				}
				_known.Clear();
				foreach (var item3 in _hidden)
				{
					MeshRenderer item = item3.Renderer;
					_known.Add(((Object)item).GetInstanceID());
				}
				Il2CppArrayBase<MeshRenderer> componentsInChildren = ((Component)_camera).GetComponentsInChildren<MeshRenderer>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					MeshRenderer val2 = componentsInChildren[i];
					if (Native.Alive((Object?)(object)val2) && IsAttached(val2) && IsScreenEffect(val2) && _known.Add(((Object)val2).GetInstanceID()))
					{
						_hidden.Add((val2, ((Renderer)val2).forceRenderingOff));
					}
				}
			}
			foreach (var item4 in _hidden)
			{
				MeshRenderer item2 = item4.Renderer;
				if (Native.Alive((Object?)(object)item2) && !((Renderer)item2).forceRenderingOff)
				{
					((Renderer)item2).forceRenderingOff = true;
				}
			}
		}

		private bool IsAttached(MeshRenderer mesh)
		{
			if (((Component)mesh).gameObject.layer == 5)
			{
				return ((Component)mesh).transform.IsChildOf(((Component)_camera).transform);
			}
			return false;
		}

		private static bool IsScreenEffect(MeshRenderer mesh)
		{
			Transform val = ((Component)mesh).transform;
			while (Native.Alive((Object?)(object)val) && (Object)(object)((Component)val).GetComponent<Camera>() == (Object)null)
			{
				string name = ((Object)val).name;
				if (Contains(name, "ImpactBlackout") || Contains(name, "QuestBlackOut") || Contains(name, "blackout") || Contains(name, "vignette") || Contains(name, "scotoma"))
				{
					return true;
				}
				val = val.parent;
			}
			Material sharedMaterial = ((Renderer)mesh).sharedMaterial;
			if (Native.Alive((Object?)(object)sharedMaterial))
			{
				if (!Contains(((Object)sharedMaterial).name, "ImpactBlackout"))
				{
					return Contains(((Object)sharedMaterial).name, "QuestBlackOut");
				}
				return true;
			}
			return false;
		}

		private static bool Contains(string value, string keyword)
		{
			return value.Contains(keyword, StringComparison.OrdinalIgnoreCase);
		}

		public void Restore(Action<string> log)
		{
			foreach (var item in _hidden)
			{
				var (mesh, wasHidden) = item;
				Native.Restore(delegate
				{
					if (Native.Alive((Object?)(object)mesh))
					{
						((Renderer)mesh).forceRenderingOff = wasHidden;
					}
				}, log);
			}
			_hidden.Clear();
			_known.Clear();
		}
	}
	internal sealed record RigBinding(RigManager Manager, OpenControllerRig Controls, PhysicsRig Physics, Avatar Avatar, Camera Camera)
	{
		public static RigBinding? Find(RigManager? manager, bool allowMainCamera)
		{
			if (!Native.Alive((Object?)(object)manager) || !((Behaviour)manager).isActiveAndEnabled)
			{
				return null;
			}
			OpenControllerRig controllerRig = Player.ControllerRig;
			PhysicsRig physicsRig = manager.physicsRig;
			Avatar avatar = manager.avatar;
			if (!Native.Alive((Object?)(object)controllerRig) || !((Behaviour)controllerRig).isActiveAndEnabled || !Native.Same((Object?)(object)controllerRig, (Object?)(object)manager.ControllerRig) || !Native.Alive((Object?)(object)physicsRig) || !Native.Alive((Object?)(object)avatar) || !Native.Alive((Object?)(object)((Rig)physicsRig).m_head) || !Native.Alive((Object?)(object)((Rig)physicsRig).m_pelvis))
			{
				return null;
			}
			Camera val = FindCamera(manager, controllerRig, allowMainCamera);
			if (!Native.Alive((Object?)(object)val))
			{
				return null;
			}
			return new RigBinding(manager, controllerRig, physicsRig, avatar, val);
		}

		public bool Current()
		{
			if (Native.Same((Object?)(object)Manager, (Object?)(object)Player.RigManager) && Native.Same((Object?)(object)Controls, (Object?)(object)Player.ControllerRig) && Native.Same((Object?)(object)Controls, (Object?)(object)Manager.ControllerRig) && ((Behaviour)Manager).isActiveAndEnabled && ((Behaviour)Controls).isActiveAndEnabled && Native.Same((Object?)(object)Physics, (Object?)(object)Manager.physicsRig) && Native.Same((Object?)(object)Avatar, (Object?)(object)Manager.avatar) && Native.Alive((Object?)(object)((Rig)Physics).m_head) && Native.Alive((Object?)(object)((Rig)Physics).m_pelvis))
			{
				return Usable(Camera);
			}
			return false;
		}

		public static bool Usable([NotNullWhen(true)] Camera? camera)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			if (Native.Alive((Object?)(object)camera) && ((Behaviour)camera).isActiveAndEnabled && (int)camera.stereoTargetEye == 3 && (camera.stereoEnabled || ((Object)camera).name == "Headset"))
			{
				return (Object)(object)camera.targetTexture == (Object)null;
			}
			return false;
		}

		public static Camera? FindCamera(RigManager manager, OpenControllerRig controls, bool allowMainCamera)
		{
			Transform transform = ((Component)manager).transform;
			Transform headset = controls.headset;
			if (Native.Alive((Object?)(object)headset))
			{
				Camera component = ((Component)headset).GetComponent<Camera>();
				if (Usable(component) && ((Object)component).name == "Headset" && ((Component)component).transform.IsChildOf(transform))
				{
					return component;
				}
			}
			Camera result = null;
			Il2CppReferenceArray<Camera> allCameras = Camera.allCameras;
			for (int i = 0; i < ((Il2CppArrayBase<Camera>)(object)allCameras).Length; i++)
			{
				Camera val = ((Il2CppArrayBase<Camera>)(object)allCameras)[i];
				if (Usable(val) && ((Component)val).transform.IsChildOf(transform))
				{
					if (((Object)val).name == "Headset")
					{
						return val;
					}
					if (allowMainCamera && ((Object)val).name == "Main Camera")
					{
						result = val;
					}
				}
			}
			return result;
		}
	}
	internal enum ToggleCombo
	{
		LeftGripClick,
		RightGripClick,
		LeftYTrigger,
		RightBTrigger
	}
	internal enum TurnMode
	{
		Smooth,
		Snap
	}
	internal sealed class Settings
	{
		private static readonly Color Accent = new Color(0.7f, 0.62f, 1f);

		private static readonly string[] ComboLabels = new string[4] { "Left Grip + L-Click", "Right Grip + R-Click", "Left Y + Left Trigger", "Right B + Right Trigger" };

		private static readonly string[] TurnLabels = new string[2] { "Smooth Turn", "Snap Turn (30 deg)" };

		private readonly MelonPreferences_Entry<bool> _enabled;

		private readonly MelonPreferences_Entry<bool> _fullAvatar;

		private readonly MelonPreferences_Entry<bool> _ignoreEffects;

		private readonly MelonPreferences_Entry<bool> _freeze;

		private readonly MelonPreferences_Entry<ToggleCombo> _combo;

		private readonly MelonPreferences_Entry<TurnMode> _turnMode;

		private readonly MelonPreferences_Entry<float> _speed;

		private readonly MelonPreferences_Entry<float> _smoothing;

		private readonly MelonPreferences_Entry<float> _turnSpeed;

		private Page? _root;

		private Page? _page;

		public bool Enabled => _enabled.Value;

		public ToggleCombo Combo
		{
			get
			{
				if ((uint)_combo.Value > 3u)
				{
					return ToggleCombo.LeftGripClick;
				}
				return _combo.Value;
			}
		}

		public float Speed => Bounded(_speed.Value, 1f, 15f, 4.5f);

		public float Smoothing => Bounded(_smoothing.Value, 0f, 1f, 0.15f);

		public TurnMode Turn
		{
			get
			{
				if (_turnMode.Value != TurnMode.Snap)
				{
					return TurnMode.Smooth;
				}
				return TurnMode.Snap;
			}
		}

		public float TurnSpeed => Bounded(_turnSpeed.Value, 30f, 180f, 90f);

		public bool FullAvatar => _fullAvatar.Value;

		public bool IgnoreEffects => _ignoreEffects.Value;

		public bool Freeze => _freeze.Value;

		public Settings()
		{
			MelonPreferences_Category val = MelonPreferences.CreateCategory("QuestFreecam");
			_enabled = val.CreateEntry<bool>("ModEnabled", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_combo = val.CreateEntry<ToggleCombo>("ToggleButtonCombo", ToggleCombo.LeftGripClick, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_speed = val.CreateEntry<float>("BaseFlightSpeed", 4.5f, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_smoothing = val.CreateEntry<float>("MovementSmoothing", 0.15f, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_turnMode = val.CreateEntry<TurnMode>("TurnMode", TurnMode.Smooth, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_turnSpeed = val.CreateEntry<float>("TurnSpeed", 90f, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_fullAvatar = val.CreateEntry<bool>("FullAvatarAndHeadVisible", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_ignoreEffects = val.CreateEntry<bool>("IgnoreScreenEffectsInFreecam", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			_freeze = val.CreateEntry<bool>("FreezeAvatarLocomotionInFreecam", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
		}

		public void EnsureMenu(Action toggle, Action apply)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			Page root = Page.Root;
			if (root != null && _root != root)
			{
				RemoveMenu();
				_root = root;
				Page? obj = (_page = root.CreatePage("Quest Freecam", Accent, 0, true));
				AddBool(obj, "Mod Enabled", _enabled, apply);
				obj.CreateFunction("Toggle Freecam Now", Accent, toggle);
				AddSelector(obj, "Toggle Button Combo", ComboLabels, (int)Combo, delegate(int value)
				{
					_combo.Value = (ToggleCombo)value;
				}, apply);
				obj.CreateFloat("Base Flight Speed", Color.white, Speed, 0.5f, 1f, 15f, (Action<float>)delegate(float value)
				{
					Save(_speed, value);
				});
				obj.CreateFloat("Movement Smoothing", Color.white, Smoothing, 0.05f, 0f, 1f, (Action<float>)delegate(float value)
				{
					Save(_smoothing, value);
				});
				AddSelector(obj, "Turn Mode", TurnLabels, (int)Turn, delegate(int value)
				{
					_turnMode.Value = (TurnMode)value;
				}, apply);
				obj.CreateFloat("Turn Speed", Color.white, TurnSpeed, 5f, 30f, 180f, (Action<float>)delegate(float value)
				{
					Save(_turnSpeed, value);
				});
				AddBool(obj, "Full Avatar & Head Visible", _fullAvatar, apply);
				AddBool(obj, "Ignore Screen Effects In Freecam", _ignoreEffects, apply);
				AddBool(obj, "Freeze Avatar Locomotion In Freecam", _freeze, apply);
			}
		}

		public void RemoveMenu()
		{
			if (_page != null)
			{
				Page? root = _root;
				if (root != null)
				{
					root.RemovePage(_page);
				}
			}
			_page = null;
			_root = null;
		}

		private static void AddSelector(Page page, string name, string[] labels, int selected, Action<int> select, Action apply)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			Page val = page.CreatePage(name, Color.white, 0, true);
			FunctionElement[] choices = (FunctionElement[])(object)new FunctionElement[labels.Length];
			for (int i = 0; i < labels.Length; i++)
			{
				int index = i;
				choices[i] = val.CreateFunction(labels[i], (i == selected) ? Accent : Color.white, (Action)delegate
				{
					//IL_0013: 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)
					FunctionElement[] array = choices;
					for (int j = 0; j < array.Length; j++)
					{
						((Element)array[j]).ElementColor = Color.white;
					}
					((Element)choices[index]).ElementColor = Accent;
					select(index);
					apply();
					MelonPreferences.Save();
				});
			}
		}

		private static void AddBool(Page page, string label, MelonPreferences_Entry<bool> entry, Action apply)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			page.CreateBool(label, Color.white, entry.Value, (Action<bool>)delegate(bool value)
			{
				entry.Value = value;
				apply();
				MelonPreferences.Save();
			});
		}

		private static void Save<T>(MelonPreferences_Entry<T> entry, T value)
		{
			entry.Value = value;
			MelonPreferences.Save();
		}

		private static float Bounded(float value, float min, float max, float fallback)
		{
			if (!float.IsFinite(value))
			{
				return fallback;
			}
			return Mathf.Clamp(value, min, max);
		}
	}
}