Decompiled source of QuestGraphics v1.0.0

Mods/QuestGraphics.dll

Decompiled 13 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 Il2CppSLZ.Data;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.Pool;
using Il2CppSLZ.VFX;
using Il2CppSLZ.VRMK;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using QuestGraphics;
using UnityEngine;
using UnityEngine.XR;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(QuestGraphicsMod), "QuestGraphics", "1.0.0", "QuestGraphics", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("QuestGraphics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("QuestGraphics")]
[assembly: AssemblyTitle("QuestGraphics")]
[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 QuestGraphics
{
	internal sealed class ClutterHooks : IDisposable
	{
		private readonly record struct EjectionState(bool PreviousSpent, FirearmCartridge? PreviousThrown, FirearmCartridge? CaseArt);

		private readonly Harmony harmony;

		private readonly List<MethodBase> installed = new List<MethodBase>();

		private static QuestGraphicsMod? mod;

		[ThreadStatic]
		private static bool ejectingSpent;

		[ThreadStatic]
		private static FirearmCartridge? thrownCartridge;

		internal ClutterHooks(Harmony harmony)
		{
			this.harmony = harmony;
		}

		internal void Install(QuestGraphicsMod owner)
		{
			try
			{
				Patch(typeof(DecalProjector), "SetColliderColorAndCreate", new Type[2]
				{
					typeof(Collider),
					typeof(Color)
				}, null, "DecalHit");
				Patch(typeof(DecalProjector), "SetVariablesAndCreate", new Type[3]
				{
					typeof(MaterialLevel),
					typeof(Collider),
					typeof(Color)
				}, null, "MaterialDecalHit");
				Patch(typeof(DecalProjector), "OnDisable", Type.EmptyTypes, "DecalDisabled");
				Patch(typeof(Gun), "EjectCartridge", Type.EmptyTypes, "BeginEjection", null, "EndEjection");
				Patch(typeof(FirearmCartridge), "ForceInDirection", new Type[3]
				{
					typeof(Vector3),
					typeof(Vector3),
					typeof(Rigidbody)
				}, null, "LaunchedCartridge");
				Patch(typeof(SpawnFragment), "UpdateFragmentPhysics", new Type[5]
				{
					typeof(Nullable<Vector3>),
					typeof(Nullable<Vector3>),
					typeof(Nullable<float>),
					typeof(Nullable<Vector3>),
					typeof(Nullable<float>)
				}, null, "SpawnedFragment");
				string[] array = new string[4] { "OnSpawn", "OnRecycleEvent", "OnDespawnEvent", "OnDestroy" };
				foreach (string name in array)
				{
					Patch(typeof(Poolee), name, Type.EmptyTypes, "PoolChanged");
				}
				mod = owner;
			}
			catch
			{
				Dispose();
				throw;
			}
		}

		private void Patch(Type type, string name, Type[] arguments, string? prefix = null, string? postfix = null, string? finalizer = null)
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, name, arguments, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
			installed.Add(methodInfo);
			harmony.Patch((MethodBase)methodInfo, GetHook(prefix), GetHook(postfix), (HarmonyMethod)null, GetHook(finalizer), (HarmonyMethod)null);
		}

		private static HarmonyMethod? GetHook(string? name)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			if (name != null)
			{
				return new HarmonyMethod(typeof(ClutterHooks), name, (Type[])null);
			}
			return null;
		}

		public void Dispose()
		{
			mod = null;
			foreach (MethodBase item in installed)
			{
				harmony.Unpatch(item, (HarmonyPatchType)0, harmony.Id);
			}
			installed.Clear();
		}

		private static void DecalHit(DecalProjector __instance, Collider __0)
		{
			mod?.DecalHit(__instance, __0);
		}

		private static void MaterialDecalHit(DecalProjector __instance, Collider __1)
		{
			mod?.DecalHit(__instance, __1);
		}

		private static void DecalDisabled(DecalProjector __instance)
		{
			mod?.ForgetDecal(__instance);
		}

		private static void PoolChanged(Poolee __instance)
		{
			mod?.ForgetPool(__instance);
		}

		private static void SpawnedFragment(SpawnFragment __instance)
		{
			mod?.FragmentSpawned(__instance);
		}

		private static void BeginEjection(Gun __instance, out EjectionState __state)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Invalid comparison between Unknown and I4
			bool previousSpent = ejectingSpent;
			FirearmCartridge previousThrown = thrownCartridge;
			ejectingSpent = false;
			thrownCartridge = null;
			FirearmCartridge caseArt = null;
			try
			{
				QuestGraphicsMod? questGraphicsMod = mod;
				ejectingSpent = questGraphicsMod != null && questGraphicsMod.Tracking && NativeLife.Alive((Object?)(object)__instance) && (int)__instance.cartridgeState == 2;
				if (ejectingSpent)
				{
					caseArt = __instance._chamberedCartridgeCaseArt;
				}
			}
			catch (Exception ex)
			{
				mod?.ReportClutterFault(ex);
			}
			__state = new EjectionState(previousSpent, previousThrown, caseArt);
		}

		private static void LaunchedCartridge(FirearmCartridge __instance)
		{
			QuestGraphicsMod? questGraphicsMod = mod;
			if (questGraphicsMod != null && questGraphicsMod.Tracking)
			{
				if (ejectingSpent)
				{
					thrownCartridge = __instance;
				}
				else
				{
					mod.CartridgeEjected(__instance, spent: false);
				}
			}
		}

		private static void EndEjection(Gun __instance, EjectionState __state, Exception? __exception)
		{
			FirearmCartridge val = thrownCartridge ?? __state.CaseArt;
			bool flag = ejectingSpent;
			ejectingSpent = __state.PreviousSpent;
			thrownCartridge = __state.PreviousThrown;
			if (__exception != null || !flag)
			{
				return;
			}
			QuestGraphicsMod? questGraphicsMod = mod;
			if (questGraphicsMod == null || !questGraphicsMod.Tracking)
			{
				return;
			}
			try
			{
				if (NativeLife.Alive((Object?)(object)val) && NativeLife.Alive((Object?)(object)__instance) && !((Component)val).transform.IsChildOf(((Component)__instance).transform))
				{
					mod.CartridgeEjected(val, spent: true);
				}
			}
			catch (Exception ex)
			{
				mod.ReportClutterFault(ex);
			}
		}
	}
	internal sealed class FrameTimeGuard
	{
		private const float WindowSeconds = 1.5f;

		private const float Step = 0.05f;

		private readonly float[] samples = new float[1024];

		private int first;

		private int count;

		private double sum;

		private float lastHealthyAt = float.NaN;

		private float nextStep;

		internal float SmoothedFrameMs
		{
			get
			{
				if (count != 0)
				{
					return (float)(1000.0 * sum / (double)count);
				}
				return 0f;
			}
		}

		internal bool Warm => sum >= 1.5;

		internal bool UnderLoad { get; private set; }

		internal void Reset()
		{
			first = (count = 0);
			sum = 0.0;
			lastHealthyAt = float.NaN;
			nextStep = 0f;
			UnderLoad = false;
		}

		internal void Sample(float delta)
		{
			if (!(delta > 0f))
			{
				return;
			}
			if (delta > 0.5f)
			{
				Reset();
				return;
			}
			if (count == samples.Length)
			{
				Shift();
			}
			samples[(first + count) % samples.Length] = delta;
			count++;
			sum += delta;
			while (count > 1 && sum - (double)samples[first] >= 1.5)
			{
				Shift();
			}
		}

		private void Shift()
		{
			sum -= samples[first];
			first = (first + 1) % samples.Length;
			count--;
		}

		internal float Evaluate(float now, float refreshHz, float current, float target, bool dynamic)
		{
			if (!Warm)
			{
				return current;
			}
			float num = 1000f / refreshHz + 0.4888897f;
			float num2 = num - 0.3f;
			float smoothedFrameMs = SmoothedFrameMs;
			if (smoothedFrameMs > num)
			{
				UnderLoad = true;
				lastHealthyAt = float.NaN;
				if (!dynamic || now < nextStep)
				{
					return current;
				}
				nextStep = now + 0.45f;
				return Math.Max(Math.Min(1f, target), current - 0.05f);
			}
			if (smoothedFrameMs > num2)
			{
				lastHealthyAt = float.NaN;
				return current;
			}
			if (float.IsNaN(lastHealthyAt))
			{
				lastHealthyAt = now;
			}
			if (now - lastHealthyAt < 3f)
			{
				return current;
			}
			UnderLoad = false;
			if (!dynamic || now < nextStep)
			{
				return current;
			}
			nextStep = now + 0.85f;
			return Math.Min(target, current + 0.05f);
		}
	}
	internal static class NativeLife
	{
		internal static bool Alive([NotNullWhen(true)] Object? obj)
		{
			try
			{
				return obj != null && !((Il2CppObjectBase)obj).WasCollected && obj != (Object)null;
			}
			catch (Exception ex) when (Lost(ex))
			{
				return false;
			}
		}

		internal static bool Lost(Exception ex)
		{
			Exception baseException = ex.GetBaseException();
			if (!(baseException is ObjectCollectedException))
			{
				if (baseException.GetType().Name == "Il2CppException")
				{
					return baseException.Message.Contains("MissingReferenceException", StringComparison.Ordinal);
				}
				return false;
			}
			return true;
		}
	}
	public sealed class QuestGraphicsMod : MelonMod
	{
		private QuestGraphicsSettings settings;

		private SceneClutterCleaner cleaner;

		private SafeResolutionScaler scaler;

		private QuestRenderTuner? renderTuner;

		private ClutterHooks? hooks;

		private int mainThread;

		private float nextMenuPoll;

		private bool worldOpen = true;

		private bool live;

		private bool clutterFaultLogged;

		private bool sweepAfterLoad;

		internal bool Tracking
		{
			get
			{
				if (live && worldOpen)
				{
					return Environment.CurrentManagedThreadId == mainThread;
				}
				return false;
			}
		}

		public override void OnInitializeMelon()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Invalid comparison between Unknown and I4
			mainThread = Environment.CurrentManagedThreadId;
			settings = new QuestGraphicsSettings();
			cleaner = new SceneClutterCleaner(settings);
			scaler = new SafeResolutionScaler(((MelonBase)this).LoggerInstance);
			if ((int)Application.platform == 11)
			{
				renderTuner = new QuestRenderTuner(((MelonBase)this).LoggerInstance);
			}
			live = settings.Enabled;
			Hooking.OnLevelLoading += LevelLoading;
			Hooking.OnLevelLoaded += LevelLoaded;
			Hooking.OnLevelUnloaded += LevelUnloaded;
			Hooking.OnSwitchAvatarPostfix += AvatarChanged;
			try
			{
				hooks = new ClutterHooks(((MelonBase)this).HarmonyInstance);
				hooks.Install(this);
				((MelonBase)this).LoggerInstance.Msg("Installed Patch 6 decal, spent cartridge, fragment and Poolee callbacks.");
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Clutter callbacks unavailable. " + ex.GetBaseException().Message);
			}
			Type[] array = new Type[6]
			{
				typeof(QuestGraphicsMod),
				typeof(MelonMod),
				typeof(Hooking),
				typeof(Poolee),
				typeof(XRDisplaySubsystem),
				typeof(Harmony)
			};
			for (int i = 0; i < array.Length; i++)
			{
				Assembly assembly = array[i].Assembly;
				((MelonBase)this).LoggerInstance.Msg($"{assembly.FullName} MVID={assembly.ManifestModule.ModuleVersionId:D}");
			}
		}

		public override void OnUpdate()
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= nextMenuPoll)
			{
				nextMenuPoll = unscaledTime + 0.5f;
				settings.TryInstall(renderTuner != null, EnabledChanged, SweepRequested);
				if (live != settings.Enabled)
				{
					EnabledChanged();
				}
			}
			if (!live || !worldOpen)
			{
				return;
			}
			scaler.Tick(unscaledTime, Time.unscaledDeltaTime, settings.Target, settings.Guard);
			renderTuner?.Tick(unscaledTime, settings.ClampShadows, scaler.UnderLoad, settings.QuestMsaa);
			try
			{
				cleaner.Tick(unscaledTime);
			}
			catch (Exception ex)
			{
				ReportClutterFault(ex);
			}
		}

		private void EnabledChanged()
		{
			live = settings.Enabled;
			if (!live)
			{
				StopFeatures();
			}
			else
			{
				scaler.Resume();
			}
		}

		private void SweepRequested()
		{
			if (live)
			{
				if (worldOpen)
				{
					cleaner.RequestSweep();
				}
				else
				{
					sweepAfterLoad = true;
				}
			}
		}

		private void LevelLoading(LevelInfo level)
		{
			LevelUnloaded();
		}

		private void LevelLoaded(LevelInfo level)
		{
			worldOpen = true;
			cleaner.ForgetHead();
			scaler.Suspend();
			if (sweepAfterLoad)
			{
				cleaner.RequestSweep();
			}
			sweepAfterLoad = false;
		}

		private void LevelUnloaded()
		{
			if (worldOpen)
			{
				worldOpen = false;
				sweepAfterLoad = false;
				cleaner.Clear();
				scaler.Suspend();
			}
		}

		private void AvatarChanged(Avatar avatar)
		{
			cleaner.ForgetHead();
		}

		private void StopFeatures()
		{
			sweepAfterLoad = false;
			cleaner.Clear();
			renderTuner?.Stop();
			scaler.Stop();
		}

		public override void OnDeinitializeMelon()
		{
			live = false;
			Hooking.OnLevelLoading -= LevelLoading;
			Hooking.OnLevelLoaded -= LevelLoaded;
			Hooking.OnLevelUnloaded -= LevelUnloaded;
			Hooking.OnSwitchAvatarPostfix -= AvatarChanged;
			StopFeatures();
			try
			{
				hooks?.Dispose();
			}
			finally
			{
				settings.Dispose();
			}
		}

		internal void DecalHit(DecalProjector decal, Collider collider)
		{
			if (!Tracking)
			{
				return;
			}
			try
			{
				cleaner.ObserveDecal(decal, collider);
			}
			catch (Exception ex)
			{
				ReportClutterFault(ex);
			}
		}

		internal void CartridgeEjected(FirearmCartridge cartridge, bool spent)
		{
			if (!Tracking)
			{
				return;
			}
			try
			{
				cleaner.ObserveCartridge(cartridge, spent);
			}
			catch (Exception ex)
			{
				ReportClutterFault(ex);
			}
		}

		internal void FragmentSpawned(SpawnFragment fragment)
		{
			if (!Tracking)
			{
				return;
			}
			try
			{
				cleaner.ObserveFragment(fragment);
			}
			catch (Exception ex)
			{
				ReportClutterFault(ex);
			}
		}

		internal void ForgetDecal(DecalProjector decal)
		{
			if (!Tracking)
			{
				return;
			}
			try
			{
				cleaner.ForgetSource((Component)(object)decal);
			}
			catch (Exception ex)
			{
				ReportClutterFault(ex);
			}
		}

		internal void ForgetPool(Poolee pool)
		{
			if (!Tracking)
			{
				return;
			}
			try
			{
				cleaner.ForgetPool(pool);
			}
			catch (Exception ex)
			{
				ReportClutterFault(ex);
			}
		}

		internal void ReportClutterFault(Exception ex)
		{
			if (!clutterFaultLogged && !NativeLife.Lost(ex))
			{
				clutterFaultLogged = true;
				((MelonBase)this).LoggerInstance.Warning("A clutter callback failed. " + ex.GetBaseException().Message);
			}
		}
	}
	internal sealed class QuestGraphicsSettings : IDisposable
	{
		private enum Preset
		{
			Crisp,
			Ultra,
			MaxFps,
			Custom
		}

		private enum Msaa
		{
			GameDefault = 0,
			X2 = 2,
			X4 = 4
		}

		private readonly MelonPreferences_Entry<bool> enabled;

		private readonly MelonPreferences_Entry<bool> guard;

		private readonly MelonPreferences_Entry<bool> decals;

		private readonly MelonPreferences_Entry<bool> casings;

		private readonly MelonPreferences_Entry<bool> shadows;

		private readonly MelonPreferences_Entry<int> preset;

		private readonly MelonPreferences_Entry<int> budget;

		private readonly MelonPreferences_Entry<int> msaa;

		private readonly MelonPreferences_Entry<float> scale;

		private readonly MelonPreferences_Entry<float> lifetime;

		private Page? page;

		private Page? questPage;

		private FunctionElement? presetPicker;

		private FloatElement? scalePicker;

		private Preset CurrentPreset => (Preset)Math.Clamp(preset.Value, 0, 3);

		internal bool Enabled => enabled.Value;

		internal bool Guard => guard.Value;

		internal bool CleanDecals => decals.Value;

		internal bool CleanCasings => casings.Value;

		internal bool ClampShadows => shadows.Value;

		internal int QuestMsaa
		{
			get
			{
				int value = msaa.Value;
				if ((value != 2 && value != 4) || 1 == 0)
				{
					return 0;
				}
				return msaa.Value;
			}
		}

		internal int DecalBudget => Math.Clamp(budget.Value, 16, 160);

		internal float Lifetime
		{
			get
			{
				if (!float.IsFinite(lifetime.Value))
				{
					return 18f;
				}
				return Math.Clamp(lifetime.Value, 5f, 60f);
			}
		}

		internal float Target => CurrentPreset switch
		{
			Preset.Crisp => 1.2f, 
			Preset.Ultra => 1.3f, 
			Preset.MaxFps => 1.05f, 
			_ => ClampScale(scale.Value), 
		};

		internal QuestGraphicsSettings()
		{
			MelonPreferences_Category val = MelonPreferences.CreateCategory("QuestGraphics");
			enabled = val.CreateEntry<bool>("Enabled", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			preset = val.CreateEntry<int>("GraphicsPreset", 0, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			scale = val.CreateEntry<float>("TargetResolutionScale", 1.2f, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			guard = val.CreateEntry<bool>("Dynamic90HzGuard", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			decals = val.CreateEntry<bool>("AutoCleanDecals", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			budget = val.CreateEntry<int>("MaxActiveDecals", 64, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			lifetime = val.CreateEntry<float>("DecalLifetimeSeconds", 18f, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			casings = val.CreateEntry<bool>("AutoCleanCasings", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			shadows = val.CreateEntry<bool>("QuestCombatShadowClamp", false, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			msaa = val.CreateEntry<int>("QuestMsaa", 0, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
		}

		internal void TryInstall(bool isQuest, Action enabledChanged, Action sweep)
		{
			//IL_0045: 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_0087: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			if (page != null || Page.Root == null)
			{
				return;
			}
			Color val = default(Color);
			((Color)(ref val))..ctor(0.2f, 0.95f, 0.82f);
			page = Page.Root.CreatePage("Quest Graphics", val, 0, true);
			page.CreateBool("Mod Enabled", Color.white, Enabled, (Action<bool>)delegate(bool value)
			{
				enabled.Value = value;
				enabledChanged();
				MelonPreferences.Save();
			});
			presetPicker = page.CreateFunction(PresetLabel(), val, (Action)CyclePreset);
			((Element)presetPicker).ElementTooltip = "Press to cycle the graphics preset.";
			scalePicker = page.CreateFloat("Target Resolution Scale", Color.white, Target, 0.05f, 0.9f, 1.4f, (Action<float>)delegate(float value)
			{
				scale.Value = ClampScale(value);
				preset.Value = 3;
				RefreshPreset();
				MelonPreferences.Save();
			});
			page.CreateBool("Dynamic 90Hz FPS Guard", Color.white, Guard, (Action<bool>)delegate(bool value)
			{
				Save(guard, value);
			});
			page.CreateBool("Auto-Clean Blood & Bullet Decals", Color.white, CleanDecals, (Action<bool>)delegate(bool value)
			{
				Save(decals, value);
			});
			page.CreateInt("Max Active Decals", Color.white, DecalBudget, 16, 16, 160, (Action<int>)delegate(int value)
			{
				Save(budget, value);
			});
			((Element)page.CreateFloat("Decal Lifetime (Seconds)", Color.white, Lifetime, 5f, 5f, 60f, (Action<float>)delegate(float value)
			{
				Save(lifetime, value);
			})).ElementTooltip = "Also applies to casings and settled debris.";
			page.CreateBool("Auto-Clean Spent Shell Casings", Color.white, CleanCasings, (Action<bool>)delegate(bool value)
			{
				Save(casings, value);
			});
			((Element)page.CreateFunction("Sweep Clutter Now", val, sweep)).ElementTooltip = "Starts a staggered pass through the clutter currently tracked.";
			if (!isQuest)
			{
				return;
			}
			questPage = page.CreatePage("Quest Rendering", val, 0, true);
			questPage.CreateBool("Combat Shadow Clamp", Color.white, ClampShadows, (Action<bool>)delegate(bool value)
			{
				Save(shadows, value);
			});
			questPage.CreateEnum("MSAA", Color.white, (Enum)(Msaa)QuestMsaa, (Action<Enum>)delegate(Enum value)
			{
				if (value is Msaa value2)
				{
					Save(msaa, (int)value2);
				}
			});
		}

		private static float ClampScale(float value)
		{
			if (!float.IsFinite(value))
			{
				return 1.2f;
			}
			return MathF.Round(Math.Clamp(value, 0.9f, 1.4f) * 20f) / 20f;
		}

		private void CyclePreset()
		{
			preset.Value = (int)(CurrentPreset + 1) % 4;
			if (scalePicker != null)
			{
				scalePicker.Value = Target;
			}
			RefreshPreset();
			MelonPreferences.Save();
		}

		private void RefreshPreset()
		{
			if (presetPicker != null)
			{
				((Element)presetPicker).ElementName = PresetLabel();
			}
		}

		private string PresetLabel()
		{
			return CurrentPreset switch
			{
				Preset.Crisp => "Graphics Preset · Crisp 90Hz (1.20x)", 
				Preset.Ultra => "Graphics Preset · Ultra Sharp (1.30x)", 
				Preset.MaxFps => "Graphics Preset · Max FPS (1.05x)", 
				_ => "Graphics Preset · Custom", 
			};
		}

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

		public void Dispose()
		{
			if (page == null)
			{
				return;
			}
			Page parent = page.Parent;
			Page currentPage = Menu.CurrentPage;
			if (currentPage == page || (questPage != null && currentPage == questPage) || (currentPage != null && currentPage.Parent == page))
			{
				Menu.OpenPage(parent);
			}
			Page? obj = questPage;
			if (obj != null)
			{
				obj.RemoveAll();
			}
			page.RemoveAll();
			parent.RemovePageLinks(page);
			foreach (Page indexPage in parent.IndexPages)
			{
				indexPage.RemovePageLinks(page);
			}
			page = (questPage = null);
			presetPicker = null;
			scalePicker = null;
		}
	}
	internal sealed class QuestRenderTuner
	{
		private const float CombatShadowDistance = 18f;

		private readonly Instance logger;

		private float nextCheck;

		private float originalShadow;

		private float lastShadow;

		private int originalMsaa;

		private int lastMsaa;

		private int configuredMsaa;

		private bool shadowClamped;

		private bool msaaOwned;

		private bool shadowOwned;

		private bool faulted;

		internal QuestRenderTuner(Instance logger)
		{
			this.logger = logger;
		}

		internal void Tick(float now, bool clampShadows, bool underLoad, int msaa)
		{
			if (faulted || now < nextCheck)
			{
				return;
			}
			nextCheck = now + 0.35f;
			try
			{
				bool flag = clampShadows && underLoad;
				if (flag != shadowClamped)
				{
					shadowClamped = flag;
					if (flag)
					{
						originalShadow = QualitySettings.shadowDistance;
						if (originalShadow > 18f)
						{
							lastShadow = 18f;
							shadowOwned = true;
							QualitySettings.shadowDistance = lastShadow;
						}
					}
					else
					{
						RestoreShadows();
					}
				}
				if (msaa == configuredMsaa)
				{
					return;
				}
				RestoreMsaa();
				configuredMsaa = msaa;
				if (msaa != 0)
				{
					originalMsaa = QualitySettings.antiAliasing;
					if (msaa != originalMsaa)
					{
						lastMsaa = msaa;
						msaaOwned = true;
						QualitySettings.antiAliasing = lastMsaa;
					}
				}
			}
			catch (Exception ex)
			{
				faulted = true;
				logger.Warning("Quest quality overrides stopped. " + ex.GetBaseException().Message);
				Stop();
			}
		}

		private void RestoreShadows()
		{
			if (shadowOwned)
			{
				if (MathF.Abs(QualitySettings.shadowDistance - lastShadow) < 0.01f)
				{
					QualitySettings.shadowDistance = originalShadow;
				}
				shadowOwned = false;
			}
		}

		private void RestoreMsaa()
		{
			if (msaaOwned)
			{
				if (QualitySettings.antiAliasing == lastMsaa)
				{
					QualitySettings.antiAliasing = originalMsaa;
				}
				msaaOwned = false;
			}
		}

		internal void Stop()
		{
			try
			{
				RestoreShadows();
			}
			catch (Exception ex)
			{
				logger.Warning("Could not restore shadow distance. " + ex.GetBaseException().Message);
			}
			try
			{
				RestoreMsaa();
			}
			catch (Exception ex2)
			{
				logger.Warning("Could not restore MSAA. " + ex2.GetBaseException().Message);
			}
			shadowClamped = false;
			configuredMsaa = 0;
			nextCheck = 0f;
		}
	}
	internal sealed class SafeResolutionScaler
	{
		private const float Unset = float.NaN;

		private List<XRDisplaySubsystem>? displays;

		private readonly FrameTimeGuard timing = new FrameTimeGuard();

		private readonly Instance logger;

		private XRDisplaySubsystem? display;

		private float originalBuffer;

		private float originalViewport;

		private float lastBufferWrite = float.NaN;

		private float lastViewportWrite = float.NaN;

		private float pendingTarget = float.NaN;

		private float appliedTarget = float.NaN;

		private float currentScale;

		private float nextDisplayPoll;

		private float applyAt;

		private float validateAt;

		private float nextEvaluation;

		private float refreshHz = 90f;

		private bool probing;

		private bool guardMode;

		private bool blocked;

		internal bool UnderLoad => timing.UnderLoad;

		internal SafeResolutionScaler(Instance logger)
		{
			this.logger = logger;
		}

		internal void Suspend()
		{
			timing.Reset();
		}

		internal void Resume()
		{
			blocked = false;
		}

		internal void Tick(float now, float delta, float target, bool guard)
		{
			if (blocked)
			{
				return;
			}
			try
			{
				Advance(now, delta, target, guard);
			}
			catch (Exception ex)
			{
				blocked = true;
				logger.Warning("XR scaling stopped. " + ex.GetBaseException().Message);
				Stop();
			}
		}

		private void Advance(float now, float delta, float target, bool guard)
		{
			if (now >= nextDisplayPoll)
			{
				nextDisplayPoll = now + 0.75f;
				if (display != null && (((Il2CppObjectBase)display).WasCollected || !((IntegratedSubsystem)display).running))
				{
					RetireDisplay();
				}
				float num = default(float);
				if (display == null)
				{
					BindDisplay();
				}
				else if (display.TryGetDisplayRefreshRate(ref num) && num >= 50f && num <= 200f)
				{
					refreshHz = num;
				}
			}
			if (display == null)
			{
				return;
			}
			timing.Sample(delta);
			if (!Close(target, pendingTarget) || guard != guardMode)
			{
				pendingTarget = target;
				guardMode = guard;
				applyAt = now + 0.65f;
				appliedTarget = float.NaN;
			}
			if (validateAt > 0f && now >= validateAt)
			{
				validateAt = 0f;
				if (!Close(display.scaleOfAllViewports, lastViewportWrite))
				{
					throw new InvalidOperationException("The XR provider did not retain the viewport scale.");
				}
				if (!float.IsNaN(lastBufferWrite) && !Close(display.scaleOfAllRenderTargets, lastBufferWrite))
				{
					throw new InvalidOperationException("The XR provider did not retain the eye-buffer scale.");
				}
			}
			if (now < applyAt || !timing.Warm || validateAt > 0f)
			{
				return;
			}
			if (!Close(target, appliedTarget))
			{
				if (guard && target > 1f && !probing && float.IsNaN(lastViewportWrite))
				{
					probing = true;
					SetViewport(Math.Clamp(originalViewport * 0.95f, 0.5f, 0.99f), now);
					return;
				}
				float num2 = (guard ? Math.Min(target, 1f) : target);
				if (!Close(display.scaleOfAllRenderTargets, target))
				{
					lastBufferWrite = target;
					display.scaleOfAllRenderTargets = target;
				}
				currentScale = num2;
				SetViewport(num2 / target, now);
				appliedTarget = target;
				nextEvaluation = now + 0.2f;
				timing.Reset();
			}
			else if (!(now < nextEvaluation))
			{
				nextEvaluation = now + 0.15f;
				float num3 = timing.Evaluate(now, refreshHz, currentScale, target, guard);
				if (!Close(num3, currentScale))
				{
					currentScale = num3;
					SetViewport(num3 / target, now);
				}
			}
		}

		private void BindDisplay()
		{
			List<XRDisplaySubsystem> val = displays ?? (displays = new List<XRDisplaySubsystem>(4));
			SubsystemManager.GetInstances<XRDisplaySubsystem>(val);
			float num = default(float);
			for (int i = 0; i < val.Count; i++)
			{
				XRDisplaySubsystem val2 = val[i];
				if (val2 != null && !((Il2CppObjectBase)val2).WasCollected && ((IntegratedSubsystem)val2).running)
				{
					float scaleOfAllRenderTargets = val2.scaleOfAllRenderTargets;
					float scaleOfAllViewports = val2.scaleOfAllViewports;
					if (scaleOfAllRenderTargets > 0f && float.IsFinite(scaleOfAllRenderTargets) && scaleOfAllViewports > 0f && scaleOfAllViewports <= 1f)
					{
						originalBuffer = scaleOfAllRenderTargets;
						originalViewport = scaleOfAllViewports;
						refreshHz = ((val2.TryGetDisplayRefreshRate(ref num) && num >= 50f && num <= 200f) ? num : 90f);
						display = val2;
						logger.Msg($"Bound XR display at {refreshHz:0.##} Hz with eye buffer {scaleOfAllRenderTargets:0.00}x and viewport {scaleOfAllViewports:0.00}x.");
						break;
					}
				}
			}
			val.Clear();
		}

		private void SetViewport(float value, float now)
		{
			if (!Close(display.scaleOfAllViewports, value))
			{
				display.scaleOfAllViewports = value;
			}
			lastViewportWrite = value;
			validateAt = now + 0.12f;
		}

		internal void Stop()
		{
			RetireDisplay();
			nextDisplayPoll = 0f;
		}

		private void RetireDisplay()
		{
			XRDisplaySubsystem val = display;
			display = null;
			bool flag = false;
			try
			{
				flag = val != null && !((Il2CppObjectBase)val).WasCollected && !float.IsNaN(lastViewportWrite) && Close(val.scaleOfAllViewports, lastViewportWrite);
			}
			catch (Exception ex)
			{
				logger.Warning("Could not read the XR viewport at shutdown. " + ex.GetBaseException().Message);
			}
			try
			{
				if (val != null && !((Il2CppObjectBase)val).WasCollected && !float.IsNaN(lastBufferWrite) && Close(val.scaleOfAllRenderTargets, lastBufferWrite))
				{
					val.scaleOfAllRenderTargets = originalBuffer;
				}
			}
			catch (Exception ex2)
			{
				logger.Warning("Could not restore the XR eye buffer. " + ex2.GetBaseException().Message);
			}
			try
			{
				if (flag)
				{
					val.scaleOfAllViewports = originalViewport;
				}
			}
			catch (Exception ex3)
			{
				logger.Warning("Could not restore the XR viewport. " + ex3.GetBaseException().Message);
			}
			lastBufferWrite = (lastViewportWrite = (pendingTarget = (appliedTarget = float.NaN)));
			probing = false;
			validateAt = 0f;
			timing.Reset();
		}

		private static bool Close(float a, float b)
		{
			return MathF.Abs(a - b) < 0.001f;
		}
	}
	internal sealed class SceneClutterCleaner
	{
		private enum Kind
		{
			Decal,
			Casing,
			Fragment
		}

		private struct Entry
		{
			internal int SourceId;

			internal int PoolId;

			internal int Next;

			internal int Previous;

			internal ulong PoolLease;

			internal ulong Sequence;

			internal Kind Kind;

			internal GameObject GameObject;

			internal Transform Transform;

			internal Poolee? Pool;

			internal Rigidbody? FragmentBody;

			internal float SpawnedAt;
		}

		private struct Queue
		{
			internal int Oldest;

			internal int Newest;

			internal int Cursor;

			internal int Manual;

			internal int Count;
		}

		private const float SweepPeriod = 0.1f;

		private const int Capacity = 768;

		private readonly Entry[] entries = new Entry[769];

		private readonly Queue[] queues = new Queue[3];

		private readonly int[] free = new int[768];

		private readonly Dictionary<int, int> bySource = new Dictionary<int, int>(768);

		private readonly Dictionary<int, int> byPool = new Dictionary<int, int>(768);

		private readonly QuestGraphicsSettings settings;

		private int freeCount;

		private int nextKind;

		private ulong sequence;

		private ulong manualThrough;

		private float nextSweep;

		private float nextHeadPoll;

		private Transform? head;

		internal SceneClutterCleaner(QuestGraphicsSettings settings)
		{
			this.settings = settings;
			Clear();
		}

		internal void Clear()
		{
			Array.Clear(entries, 0, entries.Length);
			Array.Clear(queues, 0, queues.Length);
			bySource.Clear();
			byPool.Clear();
			for (int i = 0; i < free.Length; i++)
			{
				free[i] = free.Length - i;
			}
			freeCount = free.Length;
			nextKind = 0;
			sequence = (manualThrough = 0uL);
			ForgetHead();
		}

		internal void ForgetHead()
		{
			head = null;
			nextHeadPoll = 0f;
		}

		internal void RequestSweep()
		{
			manualThrough = sequence;
			for (int i = 0; i < queues.Length; i++)
			{
				queues[i].Manual = queues[i].Oldest;
			}
		}

		internal void ObserveDecal(DecalProjector decal, Collider hit)
		{
			if (!NativeLife.Alive((Object?)(object)decal) || !NativeLife.Alive((Object?)(object)hit))
			{
				return;
			}
			GameObject gameObject = ((Component)decal).gameObject;
			Transform transform = ((Component)decal).transform;
			if (!NativeLife.Alive((Object?)(object)gameObject) || !NativeLife.Alive((Object?)(object)transform) || (Object)(object)gameObject == (Object)(object)((Component)hit).gameObject)
			{
				return;
			}
			Poolee val = ((SpawnEvents)decal)._poolee;
			if (!NativeLife.Alive((Object?)(object)val))
			{
				val = gameObject.GetComponent<Poolee>();
			}
			if (NativeLife.Alive((Object?)(object)val))
			{
				if ((Object)(object)((Component)val).gameObject != (Object)(object)gameObject)
				{
					return;
				}
			}
			else
			{
				if (NativeLife.Alive((Object?)(object)gameObject.GetComponentInParent<Poolee>(true)) || transform.childCount != 0 || NativeLife.Alive((Object?)(object)gameObject.GetComponent<Rigidbody>()) || NativeLife.Alive((Object?)(object)gameObject.GetComponent<Collider>()))
				{
					return;
				}
				MeshRenderer meshRenderer = decal.meshRenderer;
				MeshFilter meshFilter = decal.meshFilter;
				if (!NativeLife.Alive((Object?)(object)meshRenderer) || !NativeLife.Alive((Object?)(object)meshFilter) || (Object)(object)((Component)meshRenderer).gameObject != (Object)(object)gameObject || (Object)(object)((Component)meshFilter).gameObject != (Object)(object)gameObject)
				{
					return;
				}
				val = null;
			}
			Add(Kind.Decal, (Component)(object)decal, gameObject, transform, val, null);
		}

		internal void ObserveCartridge(FirearmCartridge cartridge, bool spentEjection)
		{
			if (!NativeLife.Alive((Object?)(object)cartridge))
			{
				return;
			}
			ForgetSource((Component)(object)cartridge);
			if (spentEjection)
			{
				Poolee poolee = cartridge._poolee;
				if (NativeLife.Alive((Object?)(object)poolee) && !((Object)(object)((Component)poolee).gameObject != (Object)(object)((Component)cartridge).gameObject))
				{
					Add(Kind.Casing, (Component)(object)cartridge, ((Component)cartridge).gameObject, ((Component)cartridge).transform, poolee, null);
				}
			}
		}

		internal void ObserveFragment(SpawnFragment fragment)
		{
			if (!NativeLife.Alive((Object?)(object)fragment))
			{
				return;
			}
			GameObject gameObject = ((Component)fragment).gameObject;
			if (NativeLife.Alive((Object?)(object)gameObject))
			{
				Poolee component = gameObject.GetComponent<Poolee>();
				Rigidbody component2 = gameObject.GetComponent<Rigidbody>();
				if (NativeLife.Alive((Object?)(object)component) && NativeLife.Alive((Object?)(object)component2))
				{
					Add(Kind.Fragment, (Component)(object)fragment, gameObject, ((Component)fragment).transform, component, component2);
				}
			}
		}

		private void Add(Kind kind, Component source, GameObject owner, Transform transform, Poolee? pool, Rigidbody? fragmentBody)
		{
			if (!NativeLife.Alive((Object?)(object)owner) || !NativeLife.Alive((Object?)(object)transform) || !owner.activeInHierarchy || (pool != null && pool.IsInPool))
			{
				return;
			}
			int instanceID = ((Object)source).GetInstanceID();
			int num = ((pool != null) ? ((Object)pool).GetInstanceID() : 0);
			if (bySource.TryGetValue(instanceID, out var value))
			{
				Remove(value);
			}
			if (num != 0 && byPool.TryGetValue(num, out value))
			{
				Remove(value);
			}
			if (freeCount != 0)
			{
				int num2 = free[--freeCount];
				ref Queue reference = ref queues[(int)kind];
				entries[num2] = new Entry
				{
					SourceId = instanceID,
					PoolId = num,
					Kind = kind,
					GameObject = owner,
					Transform = transform,
					Pool = pool,
					FragmentBody = fragmentBody,
					PoolLease = ((pool != null) ? pool.ID : 0),
					SpawnedAt = Time.unscaledTime,
					Sequence = ++sequence,
					Previous = reference.Newest
				};
				if (reference.Newest == 0)
				{
					reference.Oldest = num2;
				}
				else
				{
					entries[reference.Newest].Next = num2;
				}
				reference.Newest = num2;
				reference.Count++;
				bySource.Add(instanceID, num2);
				if (num != 0)
				{
					byPool.Add(num, num2);
				}
			}
		}

		internal void ForgetSource(Component source)
		{
			if (bySource.Count != 0 && NativeLife.Alive((Object?)(object)source) && bySource.TryGetValue(((Object)source).GetInstanceID(), out var value))
			{
				Remove(value);
			}
		}

		internal void ForgetPool(Poolee pool)
		{
			if (byPool.Count != 0 && NativeLife.Alive((Object?)(object)pool) && byPool.TryGetValue(((Object)pool).GetInstanceID(), out var value))
			{
				Remove(value);
			}
		}

		private void Remove(int index)
		{
			Entry entry = entries[index];
			ref Queue reference = ref queues[(int)entry.Kind];
			if (entry.Previous == 0)
			{
				reference.Oldest = entry.Next;
			}
			else
			{
				entries[entry.Previous].Next = entry.Next;
			}
			if (entry.Next == 0)
			{
				reference.Newest = entry.Previous;
			}
			else
			{
				entries[entry.Next].Previous = entry.Previous;
			}
			if (reference.Cursor == index)
			{
				reference.Cursor = entry.Next;
			}
			if (reference.Manual == index)
			{
				reference.Manual = entry.Next;
			}
			reference.Count--;
			bySource.Remove(entry.SourceId);
			if (entry.PoolId != 0)
			{
				byPool.Remove(entry.PoolId);
			}
			entries[index] = default(Entry);
			free[freeCount++] = index;
		}

		internal void Tick(float now)
		{
			if (bySource.Count != 0 && !(now < nextSweep))
			{
				nextSweep = now + 0.1f;
				if (TrySelect(out var index, out var force))
				{
					Sweep(index, force, now);
				}
			}
		}

		private bool TrySelect(out int index, out bool force)
		{
			for (int i = 0; i < queues.Length; i++)
			{
				int num = (nextKind + i) % queues.Length;
				ref Queue reference = ref queues[num];
				if (reference.Manual != 0 && entries[reference.Manual].Sequence > manualThrough)
				{
					reference.Manual = 0;
				}
				bool flag = num switch
				{
					0 => settings.CleanDecals, 
					1 => settings.CleanCasings, 
					_ => true, 
				};
				int num2 = num switch
				{
					0 => settings.DecalBudget, 
					1 => 48, 
					_ => 768, 
				};
				bool flag2 = reference.Manual != 0;
				bool flag3 = flag && reference.Count > num2;
				if (reference.Count != 0 && (flag2 || flag))
				{
					index = (flag2 ? reference.Manual : ((flag3 || reference.Cursor == 0) ? reference.Oldest : reference.Cursor));
					if (flag2)
					{
						reference.Manual = entries[index].Next;
					}
					reference.Cursor = entries[index].Next;
					nextKind = (num + 1) % queues.Length;
					force = flag2 || flag3;
					return true;
				}
			}
			index = 0;
			force = false;
			return false;
		}

		private void Sweep(int index, bool force, float now)
		{
			Entry entry = entries[index];
			try
			{
				if (!NativeLife.Alive((Object?)(object)entry.GameObject) || !entry.GameObject.activeInHierarchy || (entry.Pool != null && (!NativeLife.Alive((Object?)(object)entry.Pool) || entry.Pool.IsInPool || entry.Pool.ID != entry.PoolLease)))
				{
					Remove(index);
					return;
				}
				if (entry.Kind == Kind.Fragment)
				{
					Rigidbody fragmentBody = entry.FragmentBody;
					if (!NativeLife.Alive((Object?)(object)fragmentBody))
					{
						Remove(index);
						return;
					}
					if (fragmentBody.isKinematic || !fragmentBody.IsSleeping())
					{
						return;
					}
				}
				if (force || !(now - entry.SpawnedAt < settings.Lifetime) || BehindPlayer(entry.Transform, now))
				{
					Remove(index);
					if (entry.Pool != null)
					{
						entry.Pool.Despawn();
					}
					else
					{
						Object.Destroy((Object)(object)entry.GameObject);
					}
				}
			}
			catch (Exception ex) when (NativeLife.Lost(ex))
			{
				if (entries[index].Sequence == entry.Sequence)
				{
					Remove(index);
				}
			}
		}

		private bool BehindPlayer(Transform target, float now)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			if (now >= nextHeadPoll)
			{
				nextHeadPoll = now + 0.5f;
				OpenControllerRig controllerRig = Player.ControllerRig;
				head = (NativeLife.Alive((Object?)(object)controllerRig) ? controllerRig.headset : null);
			}
			if (!NativeLife.Alive((Object?)(object)head) || !NativeLife.Alive((Object?)(object)target))
			{
				return false;
			}
			Vector3 val = target.position - head.position;
			float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
			if (sqrMagnitude <= 144f)
			{
				return false;
			}
			return Vector3.Dot(val, head.forward) < -0.35f * MathF.Sqrt(sqrMagnitude);
		}
	}
}