Decompiled source of Steam Frame Foveation v0.6.5

Mods/FrameFoveation.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using BlobHandles;
using BoneLib.BoneMenu;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Bonelab.SaveData;
using Il2CppSLZ.Graphics2.VRS;
using Il2CppSLZ.Marrow.SaveData;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.NativeUtils;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using OscCore;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: MelonInfo(typeof(FrameFoveation), "Steam Frame Foveation", "0.6.5", "BONELAB Modding", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: MelonAdditionalDependencies(new string[] { "EyeTracking", "BoneLib" })]
[assembly: SecurityPermission((SecurityAction)8, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : System.Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class RefSafetyRulesAttribute : System.Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public sealed class FrameFoveation : MelonMod
{
	[HarmonyPatch(typeof(CommandBuffer), "SetGlobalVector", new System.Type[]
	{
		typeof(int),
		typeof(Vector4)
	})]
	private static class ShaderCenterPatch
	{
		private static void Prefix(int __0, ref Vector4 __1)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if (enabled && Object.op_Implicit((Object)(object)centerCamera) && (!Object.op_Implicit((Object)(object)renderingCamera) || !((Object)(object)renderingCamera != (Object)(object)centerCamera)) && Environment.TickCount64 - lastCenters <= 100 && __0 == VRSRenderFeature.EyeCenterProp)
			{
				__1 = projected;
				submitted = Environment.TickCount64;
			}
		}
	}

	private static class RenderPatch
	{
		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate void AddPasses(System.IntPtr feature, System.IntPtr renderer, System.IntPtr renderingData, System.IntPtr method);

		private static readonly AddPasses Callback = AfterSetup;

		private static NativeHook<AddPasses> hook;

		private static int cameraOffset;

		private static int xrOffset;

		internal static bool Failed;

		internal static long LastFeature = -2000L;

		internal static long LastXR = -2000L;

		internal static long LastInit = -2000L;

		private static bool modifiedTexture;

		private static long retrySetupAt;

		private static int ValueField<T>(string field)
		{
			//IL_000a: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
			System.IntPtr intPtr = IL2CPP.il2cpp_class_get_field_from_name(Il2CppClassPointerStore<T>.NativeClassPtr, field);
			if (intPtr == System.IntPtr.Zero)
			{
				throw new MissingFieldException(((MemberInfo)typeof(T)).Name, field);
			}
			int num = checked((int)IL2CPP.il2cpp_field_get_offset(intPtr) - 2 * System.IntPtr.Size);
			if (num < 0)
			{
				throw new InvalidOperationException("Invalid field offset: " + field);
			}
			return num;
		}

		internal static void Install()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int num = ValueField<RenderingData>("cameraData");
				cameraOffset = num + ValueField<CameraData>("camera");
				xrOffset = num + ValueField<CameraData>("xr");
				System.Type typeFromHandle = typeof(VRSRenderFeature);
				RuntimeHelpers.RunClassConstructor(typeFromHandle.TypeHandle);
				FieldInfo field = typeFromHandle.GetField("NativeMethodInfoPtr_AddRenderPasses_Public_Virtual_Void_ScriptableRenderer_byref_RenderingData_0", (BindingFlags)56);
				if (field == (FieldInfo)null)
				{
					throw new MissingMethodException(((MemberInfo)typeFromHandle).Name, "AddRenderPasses");
				}
				System.IntPtr intPtr = (System.IntPtr)field.GetValue((object)null);
				if (intPtr == System.IntPtr.Zero || Marshal.ReadIntPtr(intPtr) == System.IntPtr.Zero)
				{
					throw new InvalidOperationException("Missing native VRS method.");
				}
				hook = new NativeHook<AddPasses>(Marshal.ReadIntPtr(intPtr), Marshal.GetFunctionPointerForDelegate<AddPasses>(Callback));
				hook.Attach();
				if (nvidiaHardware)
				{
					try
					{
						PeripheralMap.Install();
						return;
					}
					catch (System.Exception ex)
					{
						MelonLogger.Warning("Hardware VRS unavailable. RDM remains available. " + ex.Message);
						return;
					}
				}
			}
			catch (System.Exception ex2)
			{
				Failed = true;
				MelonLogger.Error(((object)ex2).ToString());
			}
		}

		internal static void Uninstall()
		{
			NativeHook<AddPasses> obj = hook;
			if (obj != null && obj.IsHooked)
			{
				hook.Detach();
			}
		}

		private static void AfterSetup(System.IntPtr instance, System.IntPtr renderer, System.IntPtr data, System.IntPtr method)
		{
			//IL_0006: 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_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Expected O, but got Unknown
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: 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_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_033a: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			VRSRenderFeature val = null;
			CameraVRSOverride val2 = null;
			VRSRadii radii = default(VRSRadii);
			VRSRadii radii2 = default(VRSRadii);
			bool flag = false;
			bool flag2 = false;
			try
			{
				if (!Failed && enabled && Environment.TickCount64 >= retrySetupAt && UsingRdm && data != System.IntPtr.Zero)
				{
					System.IntPtr intPtr = Marshal.ReadIntPtr(data, xrOffset);
					System.IntPtr intPtr2 = Marshal.ReadIntPtr(data, cameraOffset);
					if (intPtr != System.IntPtr.Zero && intPtr2 != System.IntPtr.Zero)
					{
						XRPass val3 = new XRPass(intPtr);
						if (val3.enabled && val3.xrSdkEnabled && val3.viewCount >= 1 && val3.viewCount <= 2)
						{
							val = new VRSRenderFeature(instance);
							radii = val.radii;
							val.radii = WindowRadii(radii);
							flag = true;
							VRSOverrideSettingsCache perCameraOverride = VRSRenderFeature.PerCameraOverride;
							OverrideSettings val4 = ((perCameraOverride != null) ? perCameraOverride.GetVRSSettings(new Camera(intPtr2)) : null);
							if (val4 != null && val4.hasOverride && Object.op_Implicit((Object)(object)val4.overrideSettings))
							{
								val2 = val4.overrideSettings;
								radii2 = val2.radii;
								val2.radii = WindowRadii(radii2);
								flag2 = true;
							}
						}
					}
				}
			}
			catch (System.Exception ex)
			{
				if (Environment.TickCount64 >= retrySetupAt)
				{
					MelonLogger.Warning(ex.Message);
				}
				retrySetupAt = Environment.TickCount64 + 1000;
			}
			try
			{
				hook.Trampoline(instance, renderer, data, method);
			}
			finally
			{
				if (flag2 && Object.op_Implicit((Object)(object)val2))
				{
					val2.radii = radii2;
				}
				if (flag && Object.op_Implicit((Object)(object)val))
				{
					val.radii = radii;
				}
			}
			if (Failed || Environment.TickCount64 < retrySetupAt)
			{
				return;
			}
			try
			{
				LastFeature = Environment.TickCount64;
				if (data == System.IntPtr.Zero || renderer == System.IntPtr.Zero)
				{
					return;
				}
				System.IntPtr intPtr3 = Marshal.ReadIntPtr(data, cameraOffset);
				if (intPtr3 == System.IntPtr.Zero)
				{
					return;
				}
				Camera val5 = new Camera(intPtr3);
				System.IntPtr intPtr4 = Marshal.ReadIntPtr(data, xrOffset);
				if (intPtr4 == System.IntPtr.Zero)
				{
					return;
				}
				XRPass val6 = new XRPass(intPtr4);
				if (!val6.enabled || !val6.xrSdkEnabled || val6.viewCount < 1 || val6.viewCount > 2)
				{
					return;
				}
				centerCamera = null;
				LastXR = LastFeature;
				VRSRenderFeature val7 = new VRSRenderFeature(instance);
				List<ScriptableRenderPass> activeRenderPassQueue = new ScriptableRenderer(renderer).activeRenderPassQueue;
				VRSInitialize initPass = val7.initPass;
				VRSSetGlobals setGlobalsPass = val7.setGlobalsPass;
				VRSFakeMask fakeMaskPass = val7.fakeMaskPass;
				VRSFakeReconstruct fakeReconstructPass = val7.fakeReconstructPass;
				bool flag3 = fakeMaskPass != null && fakeReconstructPass != null && activeRenderPassQueue.Contains((ScriptableRenderPass)(object)fakeMaskPass) && activeRenderPassQueue.Contains((ScriptableRenderPass)(object)fakeReconstructPass);
				bool flag4 = setGlobalsPass != null && activeRenderPassQueue.Contains((ScriptableRenderPass)(object)setGlobalsPass);
				bool flag5 = initPass != null && activeRenderPassQueue.Contains((ScriptableRenderPass)(object)initPass);
				VRSReEnable enableAfterBlitPass = val7.enableAfterBlitPass;
				bool flag6 = enableAfterBlitPass != null && activeRenderPassQueue.Contains((ScriptableRenderPass)(object)enableAfterBlitPass);
				if (!flag5 && !flag6 && !flag4 && !flag3)
				{
					return;
				}
				Vector4 gaze;
				bool flag7 = ProjectGaze(val5, val6, out gaze);
				if (flag4 && flag7)
				{
					projected = gaze;
					setGlobalsPass.eyeCoords = gaze;
					centerCamera = val5;
					lastCenters = Environment.TickCount64;
				}
				if (flag3)
				{
					if (flag4 && flag7)
					{
						lastRdm = LastFeature;
					}
				}
				else
				{
					if (!nvidiaHardware)
					{
						return;
					}
					ShadingRateResource val8 = (flag5 ? initPass.SRR : null);
					ShadingRateResource val9 = (flag6 ? enableAfterBlitPass.SRR : null);
					bool flag8 = UpdateSurface(val8, gaze, flag7);
					if (val9 != null && (val8 == null || val9.SRRViewPtr != val8.SRRViewPtr))
					{
						flag8 |= UpdateSurface(val9, gaze, flag7);
					}
					if (flag8)
					{
						LastInit = (lastResource = LastFeature);
						if (flag5 && (flag7 || originals.Count != 0 || modifiedTexture))
						{
							initPass.regenSRR = true;
						}
						modifiedTexture = flag7;
						if (tracking != flag7)
						{
							MelonLogger.Msg(flag7 ? "Steam Frame gaze driving BONELAB VRS." : "Steam Frame gaze lost. Restoring BONELAB eye centers.");
						}
						tracking = flag7;
					}
				}
			}
			catch (System.Exception ex2)
			{
				retrySetupAt = Environment.TickCount64 + 1000;
				centerCamera = null;
				MelonLogger.Warning("Retrying headset pass after transient setup failure: " + ex2.Message);
			}
		}

		private static VRSRadii WindowRadii(VRSRadii radii)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)PeripheralMap.WindowPercent / 200f;
			float num2 = ((PeripheralMap.Requested == PeripheralRate.GameDefault) ? Math.Max(0.001f, radii.RDMOuterRadius - radii.RDMInnerRadius) : ((PeripheralMap.Requested == PeripheralRate.Performance) ? 0.06f : 0.12f));
			radii.RDMInnerRadius = num;
			radii.RDMOuterRadius = Math.Max(num + 0.001f, num + num2 * (1f - (float)peripheralReduction / 100f));
			return radii;
		}

		private static bool UpdateSurface(ShadingRateResource resource, Vector4 gaze, bool fresh)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (resource == null || resource.SRRViewPtr == System.IntPtr.Zero)
			{
				return false;
			}
			if (fresh)
			{
				PeripheralMap.Prepare(resource, gaze, peripheralReduction);
			}
			else
			{
				PeripheralMap.Invalidate(resource.SRRViewPtr);
			}
			return true;
		}

		private static bool ProjectGaze(Camera camera, XRPass xr, out Vector4 gaze)
		{
			//IL_0001: 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_004a: 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_006f: 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_007b: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: 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_0097: 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_009c: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: 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_00b7: 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)
			gaze = default(Vector4);
			Vector3 val;
			lock (SampleLock)
			{
				if (!enabled || !receivedAny || Environment.TickCount64 - received > SampleLifetime)
				{
					return false;
				}
				val = (useVrc ? vrcAxes : target);
			}
			Vector3 val2 = (useVrc ? EyeDirection(val.x, val.y) : val);
			Vector3 val3 = (useVrc ? EyeDirection(val.z, val.y) : val);
			int num = xr.viewCount - 1;
			if (num == 0)
			{
				val2 = ((xr.multipassId == 1) ? val3 : val2);
				val3 = val2;
			}
			if (!TryCenter(camera, xr, 0, val2, out var center) || !TryCenter(camera, xr, num, val3, out var center2))
			{
				return false;
			}
			gaze = new Vector4(center.x, center.y, center2.x, center2.y);
			return true;
		}

		private static bool TryCenter(Camera camera, XRPass xr, int eye, Vector3 ray, out Vector2 center)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_0056: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00b3: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4 viewMatrix = xr.GetViewMatrix(eye);
			Vector3 val = (useVrc ? ((Matrix4x4)(ref viewMatrix)).MultiplyVector(((Component)camera).transform.TransformDirection(ray)) : ((Matrix4x4)(ref viewMatrix)).MultiplyPoint3x4(((Component)camera).transform.TransformPoint(ray)));
			center = default(Vector2);
			if (val.z >= -0.001f)
			{
				return false;
			}
			Vector4 val2 = xr.GetProjMatrix(eye) * new Vector4(val.x, val.y, val.z, 1f);
			if (val2.w <= 0.001f)
			{
				return false;
			}
			center = new Vector2(0.5f + 0.5f * val2.x / val2.w, 0.5f + 0.5f * val2.y / val2.w);
			center.x = Mathf.Clamp01(center.x);
			center.y = Mathf.Clamp01(center.y);
			if (float.IsFinite(center.x))
			{
				return float.IsFinite(center.y);
			}
			return false;
		}
	}

	[CompilerGenerated]
	private static class <>O
	{
		public static Action<OscMessageValues> <0>__Receive;

		public static Action<ScriptableRenderContext, Camera> <1>__BeginCamera;

		public static Action<ScriptableRenderContext, Camera> <2>__EndCamera;

		public static MonitorCallback <3>__ReceiveVrc;
	}

	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static Action<bool> <>9__50_0;

		public static Action <>9__50_1;

		public static Action<System.Enum> <>9__50_2;

		public static Action <>9__50_3;

		public static Action<int> <>9__50_5;

		internal void <CreateMenu>b__50_0(bool value)
		{
			enabled = value;
		}

		internal void <CreateMenu>b__50_1()
		{
			if (GraphicsManager.graphicsSettings != null && (!UsingRdm || nvidiaHardware))
			{
				GraphicsManager.SetFoveatedRenderingMode((FoveatedRenderingMode)(UsingRdm ? 1 : 0));
				ResetRenderState();
			}
		}

		internal void <CreateMenu>b__50_2(System.Enum value)
		{
			ResetRenderState((PeripheralRate)(object)value);
		}

		internal void <CreateMenu>b__50_3()
		{
			overlay = GraphicsManager.ToggleFoveatedVisualization();
		}

		internal void <CreateMenu>b__50_5(int value)
		{
			peripheralReduction = value;
			if (value != 0)
			{
				RefreshFeatures();
			}
		}
	}

	private const string Address = "/tracking/eye/CenterVecFull";

	private static readonly object SampleLock = new object();

	private static Vector3 target;

	private static Vector3 vrcAxes;

	private static int vrcMask;

	private static bool useVrc;

	private MelonPreferences_Entry<bool> sourcePreference;

	private static Vector4 projected;

	private static long submitted = -1000L;

	private FunctionElement centersStatus;

	private FunctionElement mapStatus;

	private FunctionElement summary;

	private MelonPreferences_Entry<int> windowSize;

	private IntElement windowControl;

	private FoveatedPresets? lastPreset;

	private static long received = -1000L;

	private static bool tracking;

	private Action<ScriptableRenderContext, Camera> beginCamera;

	private Action<ScriptableRenderContext, Camera> endCamera;

	private static Camera renderingCamera;

	private static bool receivedAny;

	private bool reportedInput;

	private Page page;

	private FunctionElement methodButton;

	private static bool nvidiaHardware;

	private static long lastRdm = -2000L;

	private FunctionElement gazeStatus;

	private FunctionElement renderStatus;

	private long nextStatus;

	private static long lastCenters = -1000L;

	private static long lastResource = -1000L;

	private static bool enabled = true;

	private static int peripheralReduction;

	private static VRSRenderFeature[] features = System.Array.Empty<VRSRenderFeature>();

	private static readonly Dictionary<VRSRenderFeature, VRSRadii> originals = new Dictionary<VRSRenderFeature, VRSRadii>();

	private static bool overlay;

	private OscServer server;

	private static Camera centerCamera;

	private static bool UsingRdm
	{
		get
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			GraphicsSettings graphicsSettings = GraphicsManager.graphicsSettings;
			if (graphicsSettings == null)
			{
				return false;
			}
			return (int)graphicsSettings.FoveatedRenderingModeSetting == 0;
		}
	}

	private static int SampleLifetime
	{
		get
		{
			if (!useVrc)
			{
				return 200;
			}
			return 1000;
		}
	}

	public override void OnInitializeMelon()
	{
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Invalid comparison between Unknown and I4
		MelonPreferences_Category val = MelonPreferences.CreateCategory("FrameFoveation");
		sourcePreference = val.CreateEntry<bool>("UseVRCFaceTracking", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
		windowSize = val.CreateEntry<int>("SharpWindowPercent", 32, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
		PeripheralMap.WindowPercent = Math.Clamp(windowSize.Value, 10, 70);
		useVrc = sourcePreference.Value;
		if (!useVrc)
		{
			server = OscServer.GetOrCreate(9015);
			if (!server.TryAddMethod("/tracking/eye/CenterVecFull", (Action<OscMessageValues>)Receive))
			{
				throw new InvalidOperationException("Unable to register Steam Link eye-gaze listener.");
			}
		}
		beginCamera = Action<ScriptableRenderContext, Camera>.op_Implicit((Action<ScriptableRenderContext, Camera>)BeginCamera);
		endCamera = Action<ScriptableRenderContext, Camera>.op_Implicit((Action<ScriptableRenderContext, Camera>)EndCamera);
		RenderPipelineManager.beginCameraRendering += beginCamera;
		RenderPipelineManager.endCameraRendering += endCamera;
		nvidiaHardware = SystemInfo.graphicsDeviceVendorID == 4318 && (int)SystemInfo.graphicsDeviceType == 2;
		RenderPatch.Install();
		((MelonBase)this).LoggerInstance.Msg(useVrc ? "Waiting for VRCFaceTracking gaze on EyeTracking port 9000." : "Waiting for Steam Link gaze on port 9015.");
	}

	public override void OnDeinitializeMelon()
	{
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Expected O, but got Unknown
		RestoreRadii();
		RenderPatch.Uninstall();
		PeripheralMap.Dispose();
		if (overlay)
		{
			GraphicsManager.DisableFoveatedVisualization();
		}
		if (page != null)
		{
			Page.Root.RemovePage(page);
		}
		if ((Delegate)(object)beginCamera != (Delegate)null)
		{
			RenderPipelineManager.beginCameraRendering -= beginCamera;
		}
		if ((Delegate)(object)endCamera != (Delegate)null)
		{
			RenderPipelineManager.endCameraRendering -= endCamera;
		}
		if (useVrc)
		{
			OscServer obj = server;
			if (obj != null)
			{
				object obj2 = <>O.<3>__ReceiveVrc;
				if (obj2 == null)
				{
					MonitorCallback val = ReceiveVrc;
					<>O.<3>__ReceiveVrc = val;
					obj2 = (object)val;
				}
				obj.RemoveMonitorCallback((MonitorCallback)obj2);
			}
		}
		else
		{
			OscServer obj3 = server;
			if (obj3 != null)
			{
				obj3.RemoveMethod("/tracking/eye/CenterVecFull", (Action<OscMessageValues>)Receive);
			}
		}
		server = null;
	}

	private static void BeginCamera(ScriptableRenderContext context, Camera camera)
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: 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_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
		RestoreRadii();
		renderingCamera = camera;
		if (!enabled || peripheralReduction == 0 || !Object.op_Implicit((Object)(object)camera) || !camera.stereoEnabled)
		{
			return;
		}
		VRSRenderFeature[] array = features;
		foreach (VRSRenderFeature val in array)
		{
			if (Object.op_Implicit((Object)(object)val) && val.SupportsVRS)
			{
				VRSRadii radii = val.radii;
				originals[val] = radii;
				float fraction = 1f - (float)peripheralReduction / 100f;
				radii.VRSOuterElipseMajorRadius = Outer(radii.VRSInnerElipseMajorRadius, radii.VRSOuterElipseMajorRadius, fraction);
				radii.VRSOuterElipseMinorRadius = Outer(radii.VRSInnerElipseMinorRadius, radii.VRSOuterElipseMinorRadius, fraction);
				val.radii = radii;
			}
		}
	}

	private static float Outer(float inner, float outer, float fraction)
	{
		if (!(outer > inner))
		{
			return outer;
		}
		return inner + (outer - inner) * fraction;
	}

	private static void RestoreRadii()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		Enumerator<VRSRenderFeature, VRSRadii> enumerator = originals.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				KeyValuePair<VRSRenderFeature, VRSRadii> current = enumerator.Current;
				if (Object.op_Implicit((Object)(object)current.Key))
				{
					current.Key.radii = current.Value;
				}
			}
		}
		finally
		{
			((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		originals.Clear();
	}

	private static void EndCamera(ScriptableRenderContext context, Camera camera)
	{
		RestoreRadii();
		renderingCamera = null;
		centerCamera = null;
	}

	private static void RefreshFeatures()
	{
		features = Il2CppArrayBase<VRSRenderFeature>.op_Implicit(Resources.FindObjectsOfTypeAll<VRSRenderFeature>());
	}

	public override void OnSceneWasInitialized(int index, string name)
	{
		ResetRenderState();
		if (peripheralReduction != 0)
		{
			RefreshFeatures();
		}
	}

	private static void ResetRenderState(PeripheralRate? quality = null)
	{
		centerCamera = null;
		lastRdm = (lastCenters = (lastResource = (submitted = -2000L)));
		PeripheralMap.Reset(quality);
	}

	private void SetWindowSize(int value)
	{
		PeripheralMap.WindowPercent = value;
		if (windowControl != null && windowControl.Value != value)
		{
			windowControl.Value = value;
		}
		if (windowSize.Value != value)
		{
			windowSize.Value = value;
			((MelonPreferences_Entry)windowSize).Save();
		}
	}

	private void SyncGraphicsPreset()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: 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_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: 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_005e: Expected I4, but got Unknown
		GraphicsSettings graphicsSettings = GraphicsManager.graphicsSettings;
		if (graphicsSettings == null)
		{
			return;
		}
		if (!graphicsSettings.EnableFoveatedRenderingMenu)
		{
			graphicsSettings.EnableFoveatedRenderingMenu = true;
		}
		FoveatedPresets foveatedPresetSetting = graphicsSettings.FoveatedPresetSetting;
		if (lastPreset.HasValue && lastPreset != (FoveatedPresets?)foveatedPresetSetting)
		{
			switch (foveatedPresetSetting - 1)
			{
			case 2:
				SetWindowSize(20);
				break;
			case 1:
				SetWindowSize(32);
				break;
			case 0:
				SetWindowSize(50);
				break;
			}
		}
		lastPreset = foveatedPresetSetting;
	}

	private void CreateMenu()
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: 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_007e: 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_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Expected O, but got Unknown
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0185: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		//IL_0216: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Expected O, but got Unknown
		page = Page.Root.CreatePage("Steam Frame Foveation", Color.cyan, 0, true);
		summary = page.CreateFunction("Waiting for eye tracking", Color.white, (Action)null);
		page.CreateBool("Enable foveated rendering", Color.white, enabled, (Action<bool>)delegate(bool value)
		{
			enabled = value;
		});
		Page obj = page;
		Color white = Color.white;
		object obj2 = <>c.<>9__50_1;
		if (obj2 == null)
		{
			Action val = delegate
			{
				if (GraphicsManager.graphicsSettings != null && (!UsingRdm || nvidiaHardware))
				{
					GraphicsManager.SetFoveatedRenderingMode((FoveatedRenderingMode)(UsingRdm ? 1 : 0));
					ResetRenderState();
				}
			};
			<>c.<>9__50_1 = val;
			obj2 = (object)val;
		}
		methodButton = obj.CreateFunction("Rendering method", white, (Action)obj2);
		((Element)methodButton).ElementTooltip = "Select BONELAB's radial density mask for Radeon, or hardware VRS on supported NVIDIA PCs.";
		windowControl = page.CreateInt("Sharp window size (%)", Color.white, PeripheralMap.WindowPercent, 2, 10, 70, (Action<int>)SetWindowSize);
		((Element)windowControl).ElementTooltip = "Fine-tune the sharp width for each eye. Changing the BONELAB graphics preset selects a new starting size.";
		((Element)page.CreateEnum("Peripheral quality", Color.white, (System.Enum)PeripheralMap.Requested, (Action<System.Enum>)delegate(System.Enum value)
		{
			ResetRenderState((PeripheralRate)(object)value);
		})).ElementTooltip = "In RDM, Performance narrows the transition outside the sharp window. In hardware VRS, Balanced requests 2x2 shading and Performance requests 4x4. Window size comes from the graphics preset or the BoneMenu slider.";
		Page obj3 = page;
		Color white2 = Color.white;
		object obj4 = <>c.<>9__50_3;
		if (obj4 == null)
		{
			Action val2 = delegate
			{
				overlay = GraphicsManager.ToggleFoveatedVisualization();
			};
			<>c.<>9__50_3 = val2;
			obj4 = (object)val2;
		}
		obj3.CreateFunction("Show / hide shading overlay", white2, (Action)obj4);
		Page val3 = page.CreatePage("Tracking details", Color.white, 0, true);
		val3.CreateBool("Use VRCFaceTracking (restart required)", Color.white, useVrc, (Action<bool>)([CompilerGenerated] (bool value) =>
		{
			sourcePreference.Value = value;
			((MelonPreferences_Entry)sourcePreference).Save();
		}));
		gazeStatus = val3.CreateFunction("Waiting for eye input", Color.white, (Action)null);
		renderStatus = val3.CreateFunction("Waiting for rendering", Color.white, (Action)null);
		centersStatus = val3.CreateFunction("Waiting for shader coordinates", Color.white, (Action)null);
		mapStatus = val3.CreateFunction("Waiting for peripheral shading", Color.white, (Action)null);
		((Element)val3.CreateInt("Shorten edge transition (%)", Color.white, peripheralReduction, 25, 0, 100, (Action<int>)delegate(int value)
		{
			peripheralReduction = value;
			if (value != 0)
			{
				RefreshFeatures();
			}
		})).ElementTooltip = "Higher values start the coarsest shading closer to your gaze. The full-quality center keeps its size. Zero uses the game preset.";
	}

	public override void OnUpdate()
	{
		//IL_0048: 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_0053: Expected O, but got Unknown
		//IL_00a2: 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_00ad: Expected O, but got Unknown
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		//IL_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_028a: Unknown result type (might be due to invalid IL or missing references)
		OscServer val = default(OscServer);
		if (useVrc && OscServer.PortToServer.TryGetValue(9000, ref val) && val != server)
		{
			OscServer obj = server;
			if (obj != null)
			{
				object obj2 = <>O.<3>__ReceiveVrc;
				if (obj2 == null)
				{
					MonitorCallback val2 = ReceiveVrc;
					<>O.<3>__ReceiveVrc = val2;
					obj2 = (object)val2;
				}
				obj.RemoveMonitorCallback((MonitorCallback)obj2);
			}
			lock (SampleLock)
			{
				received = -2000L;
				vrcMask = 0;
				receivedAny = false;
			}
			OscServer obj3 = val;
			object obj4 = <>O.<3>__ReceiveVrc;
			if (obj4 == null)
			{
				MonitorCallback val3 = ReceiveVrc;
				<>O.<3>__ReceiveVrc = val3;
				obj4 = (object)val3;
			}
			obj3.AddMonitorCallback((MonitorCallback)obj4);
			server = val;
		}
		if (page == null && Page.Root != null)
		{
			CreateMenu();
		}
		long tickCount = Environment.TickCount64;
		if (page != null && tickCount >= nextStatus)
		{
			nextStatus = tickCount + 250;
			SyncGraphicsPreset();
			bool usingRdm = UsingRdm;
			string text = (usingRdm ? "Rendering method: radial density mask" : "Rendering method: hardware VRS");
			if (((Element)methodButton).ElementName != text)
			{
				((Element)methodButton).ElementName = text;
			}
			Vector3 val4;
			bool flag;
			bool flag2;
			lock (SampleLock)
			{
				val4 = (useVrc ? vrcAxes : target);
				flag = receivedAny;
				flag2 = flag && tickCount - received <= SampleLifetime;
			}
			if (!reportedInput && flag)
			{
				((MelonBase)this).LoggerInstance.Msg(useVrc ? "Received VRCFT eye parameters on port 9000." : "Received Steam Link gaze on port 9015.");
				reportedInput = true;
			}
			string text2 = (useVrc ? "VRCFT" : "Steam Link");
			string text3 = ((!flag2) ? (flag ? (text2 + ": stale") : $"{text2}: waiting on {(useVrc ? 9000 : 9015)}") : (useVrc ? $"VRCFT: Lx {val4.x:F2}  Rx {val4.z:F2}  Y {val4.y:F2}" : $"Steam: {val4.x:F2}, {val4.y:F2}, {val4.z:F2}"));
			string text4 = ((tickCount - submitted <= 500) ? $"Shader L {projected.x:F2},{projected.y:F2}  R {projected.z:F2},{projected.w:F2}" : "Shader: no recent center command");
			if (!usingRdm)
			{
				text4 = PeripheralMap.HardwareCenters(tickCount);
			}
			if (((Element)centersStatus).ElementName != text4)
			{
				((Element)centersStatus).ElementName = text4;
			}
			string text5 = ((!enabled) ? "Renderer: add-on off" : (RenderPatch.Failed ? "Renderer: hook unavailable (see log)" : ((tickCount - RenderPatch.LastFeature > 1000) ? "Renderer: no VRS feature call" : ((tickCount - RenderPatch.LastXR > 1000) ? "Renderer: no XR camera in VRS feature" : ((!usingRdm) ? ((!nvidiaHardware) ? "Renderer: select radial density mask" : ((tickCount - RenderPatch.LastInit > 1000) ? "Renderer: no queued hardware VRS pass" : ((tickCount - lastResource > 1000) ? "Renderer: shading resource unavailable" : ((!flag2) ? "Renderer: VRS ready, waiting for gaze" : ((tickCount - lastCenters > 500) ? "Renderer: waiting for gaze centers" : ((tickCount - submitted > 500) ? "Renderer: centers queued" : "Renderer: gaze sent to shader")))))) : ((tickCount - lastRdm <= 500) ? "Renderer: gaze applied to RDM" : "Renderer: waiting for RDM mask and reconstruction"))))));
			string text6 = (usingRdm ? "Peripheral shading: radial density mask" : ((enabled && flag2 && tickCount - PeripheralMap.LastAttempt <= 1000) ? PeripheralMap.Status : "Tile map: idle"));
			string text7 = ((!enabled) ? "Off" : ((!flag2) ? "Waiting for eye tracking" : ((!usingRdm) ? ((text6.StartsWith("Tile map: 2x2") || text6.StartsWith("Tile map: 4x4")) ? "On: following your eyes" : "Eye tracking ready; waiting for shading") : ((tickCount - lastRdm <= 500) ? "On: following your eyes" : "Waiting for radial density mask"))));
			if (((Element)summary).ElementName != text7)
			{
				((Element)summary).ElementName = text7;
			}
			if (((Element)mapStatus).ElementName != text6)
			{
				((Element)mapStatus).ElementName = text6;
				((MelonBase)this).LoggerInstance.Msg(text6);
			}
			if (((Element)gazeStatus).ElementName != text3)
			{
				((Element)gazeStatus).ElementName = text3;
			}
			if (((Element)renderStatus).ElementName != text5)
			{
				((Element)renderStatus).ElementName = text5;
				((MelonBase)this).LoggerInstance.Msg(text5);
			}
		}
	}

	private unsafe static void ReceiveVrc(BlobString address, OscMessageValues message)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		int length = address.Handle.Length;
		if (message.ElementCount != 1 || length < 26 || length > 32)
		{
			return;
		}
		string text = ((object)(*(BlobString*)(&address))/*cast due to .constrained prefix*/).ToString();
		int num = ((!(text == "/avatar/parameters/v2/EyeLeftX")) ? ((text == "/avatar/parameters/v2/EyeY") ? 1 : ((!(text == "/avatar/parameters/v2/EyeRightX")) ? (-1) : 2)) : 0);
		int num2 = num;
		if (num2 < 0)
		{
			return;
		}
		float num3 = message.ReadFloatElement(0);
		if (!float.IsFinite(num3) || Math.Abs(num3) > 1f)
		{
			return;
		}
		lock (SampleLock)
		{
			switch (num2)
			{
			case 0:
				vrcAxes.x = num3;
				break;
			case 1:
				vrcAxes.y = num3;
				break;
			default:
				vrcAxes.z = num3;
				break;
			}
			vrcMask |= 1 << num2;
			if (vrcMask == 7)
			{
				receivedAny = true;
				received = Environment.TickCount64;
			}
		}
	}

	private static Vector3 EyeDirection(float x, float y)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(x, y, MathF.Sqrt(MathF.Max(0.0001f, 1f - x * x - y * y)));
	}

	private static void Receive(OscMessageValues message)
	{
		//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)
		if (message.ElementCount != 3)
		{
			return;
		}
		float num = message.ReadFloatElement(0);
		float num2 = message.ReadFloatElement(1);
		float num3 = message.ReadFloatElement(2);
		lock (SampleLock)
		{
			if (!float.IsFinite(num) || !float.IsFinite(num2) || !float.IsFinite(num3) || num3 <= 0.001f)
			{
				received = -1000L;
				return;
			}
			receivedAny = true;
			target = new Vector3(num, num2, num3);
			received = Environment.TickCount64;
		}
	}
}
internal enum PeripheralRate
{
	GameDefault,
	Balanced,
	Performance
}
internal static class PeripheralMap
{
	[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
	private delegate void RenderEvent(int id, System.IntPtr data);

	private sealed class Surface
	{
		internal System.IntPtr view;

		internal long preparedAt = -2000L;

		private System.IntPtr texture;

		private int width;

		private int height;

		private int slices;

		private int mipCount;

		private int window;

		private int reduction;

		private Vector4 center;

		private byte[] pixels;

		private readonly int[] fallbackRates = new int[16];

		internal void Release()
		{
			SetTexture(System.IntPtr.Zero);
			if (view != System.IntPtr.Zero)
			{
				Marshal.Release(view);
			}
			view = System.IntPtr.Zero;
			preparedAt = -2000L;
		}

		private void SetTexture(System.IntPtr next)
		{
			if (!(next == texture))
			{
				if (next != System.IntPtr.Zero)
				{
					Marshal.AddRef(next);
				}
				if (texture != System.IntPtr.Zero)
				{
					Marshal.Release(texture);
				}
				texture = next;
			}
		}

		internal unsafe void Prepare(ShadingRateResource resource, Vector4 gaze, int transition)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Invalid comparison between Unknown and I4
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Invalid comparison between Unknown and I4
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: 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)
			RenderTexture shadingRateTexture = resource.shadingRateTexture;
			preparedAt = -2000L;
			if (!Object.op_Implicit((Object)(object)shadingRateTexture) || (int)SystemInfo.graphicsDeviceType != 2 || ((int)shadingRateTexture.graphicsFormat != 13 && (int)shadingRateTexture.graphicsFormat != 5) || ((int)((Texture)shadingRateTexture).dimension != 2 && ((int)((Texture)shadingRateTexture).dimension != 5 || shadingRateTexture.volumeDepth != 2)))
			{
				Status = "Tile map: unsupported headset texture";
				return;
			}
			System.IntPtr shadingRateTexturePtr = resource.shadingRateTexturePtr;
			if (shadingRateTexturePtr == System.IntPtr.Zero)
			{
				Status = "Tile map: missing D3D11 texture";
				return;
			}
			if (shadingRateTexturePtr != texture)
			{
				Guid texture2DId = Texture2DId;
				System.IntPtr intPtr = default(System.IntPtr);
				if (Marshal.QueryInterface(shadingRateTexturePtr, ref texture2DId, ref intPtr) != 0)
				{
					Status = "Tile map: native resource is not a D3D11 texture";
					return;
				}
				try
				{
					SetTexture(intPtr);
				}
				finally
				{
					Marshal.Release(intPtr);
				}
			}
			width = ((Texture)shadingRateTexture).width;
			height = ((Texture)shadingRateTexture).height;
			mipCount = ((Texture)shadingRateTexture).mipmapCount;
			slices = (((int)((Texture)shadingRateTexture).dimension != 5) ? 1 : 2);
			uint* ptr = stackalloc uint[11];
			((delegate* unmanaged[Stdcall]<System.IntPtr, uint*, void>)(void*)(*(System.IntPtr*)((nint)(*(System.IntPtr*)(void*)texture) + (nint)10 * (nint)sizeof(System.IntPtr))))(texture, ptr);
			if (*ptr != width || ptr[1] != height || ptr[2] != mipCount || ptr[3] != slices || (ptr[4] != 60 && ptr[4] != 61 && ptr[4] != 62) || ptr[5] != 1 || ptr[7] != 0)
			{
				Status = "Tile map: incompatible native texture";
				return;
			}
			if (!haveRates)
			{
				Il2CppStructArray<int> sRRTable = resource.SRRTable;
				if (sRRTable == null || ((Il2CppArrayBase<int>)(object)sRRTable).Length < rates.Length)
				{
					Status = "Tile map: no headset rate table";
					return;
				}
				for (int i = 0; i < rates.Length; i++)
				{
					fallbackRates[i] = ((Il2CppArrayBase<int>)(object)sRRTable)[i];
				}
			}
			center = gaze;
			window = WindowPercent;
			reduction = transition;
			preparedAt = LastAttempt;
			if (LastAttempt - lastWrite > 500)
			{
				Status = "Tile map: waiting for headset bind";
			}
		}

		internal unsafe void WriteAtBind()
		{
			//IL_00fc: 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_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			int[] array = (haveRates ? rates : fallbackRates);
			int num = System.Array.IndexOf<int>(array, 5);
			int num2 = System.Array.IndexOf<int>(array, 8);
			int num3 = ((Requested == PeripheralRate.Performance) ? System.Array.IndexOf<int>(array, 11) : (-1));
			if (num < 0 || (num2 < 0 && num3 < 0))
			{
				Status = "Tile map: outer rate unavailable";
				return;
			}
			int num4 = System.Array.IndexOf<int>(array, 6);
			int num5 = ((num3 >= 0) ? num3 : num2);
			int num6 = ((Requested == PeripheralRate.Performance) ? num5 : ((num4 >= 0) ? num4 : num));
			int num7 = checked(width * height);
			if (pixels == null || pixels.Length != num7)
			{
				pixels = new byte[num7];
			}
			System.IntPtr zero = System.IntPtr.Zero;
			System.IntPtr zero2 = System.IntPtr.Zero;
			try
			{
				((delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr*, void>)(void*)(*(System.IntPtr*)((nint)(*(System.IntPtr*)(void*)texture) + (nint)3 * (nint)sizeof(System.IntPtr))))(texture, &zero);
				if (zero == System.IntPtr.Zero)
				{
					throw new InvalidOperationException("No D3D11 device");
				}
				((delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr*, void>)(void*)(*(System.IntPtr*)((nint)(*(System.IntPtr*)(void*)zero) + (nint)40 * (nint)sizeof(System.IntPtr))))(zero, &zero2);
				if (zero2 == System.IntPtr.Zero)
				{
					throw new InvalidOperationException("No immediate context");
				}
				delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr, uint, System.IntPtr, byte*, uint, uint, void> delegate* = (delegate* unmanaged[Stdcall]<System.IntPtr, System.IntPtr, uint, System.IntPtr, byte*, uint, uint, void>)(void*)(*(System.IntPtr*)((nint)(*(System.IntPtr*)(void*)zero2) + (nint)48 * (nint)sizeof(System.IntPtr)));
				for (int i = 0; i < slices; i++)
				{
					float num8 = ((i == 1) ? center.z : center.x);
					float num9 = ((i == 1) ? center.w : center.y);
					float rx = ((slices == 2) ? num8 : center.z);
					float ry = ((slices == 2) ? num9 : center.w);
					Fill(pixels, width, height, num8, num9, rx, ry, window, reduction, (byte)num, (byte)num6, (byte)num5);
					fixed (byte* ptr = pixels)
					{
						delegate*(zero2, texture, (uint)(i * mipCount), System.IntPtr.Zero, ptr, (uint)width, (uint)num7);
					}
				}
				writtenCenter = center;
				lastWrite = Environment.TickCount64;
				Status = ((num3 >= 0) ? "Tile map: 4x4 at headset bind" : "Tile map: 2x2 at headset bind");
			}
			finally
			{
				if (zero2 != System.IntPtr.Zero)
				{
					Marshal.Release(zero2);
				}
				if (zero != System.IntPtr.Zero)
				{
					Marshal.Release(zero);
				}
			}
		}
	}

	internal static int WindowPercent = 32;

	internal static PeripheralRate Requested = PeripheralRate.Balanced;

	internal static long LastAttempt = -2000L;

	internal static volatile string Status = "Tile map: idle";

	private static readonly object Gate = new object();

	private static NativeHook<RenderEvent> hook;

	private static readonly RenderEvent Callback = OnRenderEvent;

	private static readonly Surface[] surfaces = new Surface[4]
	{
		new Surface(),
		new Surface(),
		new Surface(),
		new Surface()
	};

	private static readonly int[] rates = new int[16];

	private static bool haveRates;

	private static readonly Guid Texture2DId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c");

	private static long retryWriteAt;

	private static long lastWrite = -2000L;

	private static Vector4 writtenCenter;

	internal static void Install()
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		System.IntPtr renderEventWithDataFunc = VRSPlugin.GetRenderEventWithDataFunc();
		if (renderEventWithDataFunc == System.IntPtr.Zero)
		{
			throw new InvalidOperationException("Missing NVIDIA VRS render callback.");
		}
		hook = new NativeHook<RenderEvent>(renderEventWithDataFunc, Marshal.GetFunctionPointerForDelegate<RenderEvent>(Callback));
		hook.Attach();
	}

	internal static void Dispose()
	{
		NativeHook<RenderEvent> obj = hook;
		if (obj != null && obj.IsHooked)
		{
			hook.Detach();
		}
		Reset();
	}

	internal static void Reset(PeripheralRate? quality = null)
	{
		lock (Gate)
		{
			if (quality.HasValue)
			{
				Requested = quality.Value;
			}
			Surface[] array = surfaces;
			for (int i = 0; i < array.Length; i++)
			{
				array[i].Release();
			}
			haveRates = false;
			retryWriteAt = 0L;
			LastAttempt = (lastWrite = -2000L);
			Status = "Tile map: waiting for headset bind";
		}
	}

	internal static void Prepare(ShadingRateResource resource, Vector4 gaze, int transition)
	{
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		lock (Gate)
		{
			LastAttempt = Environment.TickCount64;
			System.IntPtr sRRViewPtr = resource.SRRViewPtr;
			if (sRRViewPtr == System.IntPtr.Zero)
			{
				return;
			}
			Surface surface = surfaces[0];
			Surface[] array = surfaces;
			foreach (Surface surface2 in array)
			{
				if (surface2.view == sRRViewPtr)
				{
					surface = surface2;
					break;
				}
				if (surface2.preparedAt < surface.preparedAt)
				{
					surface = surface2;
				}
			}
			if (surface.view != sRRViewPtr)
			{
				surface.Release();
				Marshal.AddRef(sRRViewPtr);
				surface.view = sRRViewPtr;
			}
			surface.Prepare(resource, gaze, transition);
		}
	}

	internal static void Invalidate(System.IntPtr view)
	{
		lock (Gate)
		{
			Surface[] array = surfaces;
			foreach (Surface surface in array)
			{
				if (surface.view == view)
				{
					surface.preparedAt = -2000L;
				}
			}
		}
	}

	internal static string HardwareCenters(long now)
	{
		lock (Gate)
		{
			return (now - lastWrite < 500) ? $"Hardware L {writtenCenter.x:F2},{writtenCenter.y:F2}  R {writtenCenter.z:F2},{writtenCenter.w:F2}" : "Hardware: no recent headset write";
		}
	}

	private static void OnRenderEvent(int id, System.IntPtr data)
	{
		try
		{
			lock (Gate)
			{
				if (id == 0 && data != System.IntPtr.Zero)
				{
					Marshal.Copy(data, rates, 0, rates.Length);
					haveRates = true;
				}
				if (id == 1 && Environment.TickCount64 >= retryWriteAt)
				{
					PreparedSurface(data, Environment.TickCount64)?.WriteAtBind();
				}
			}
		}
		catch (System.Exception ex)
		{
			retryWriteAt = Environment.TickCount64 + 1000;
			Status = "Tile map: retrying hardware update (" + ex.Message + ")";
		}
		finally
		{
			hook.Trampoline(id, data);
		}
	}

	private static Surface PreparedSurface(System.IntPtr view, long now)
	{
		if (view == System.IntPtr.Zero)
		{
			return null;
		}
		Surface[] array = surfaces;
		foreach (Surface surface in array)
		{
			if (surface.view == view && now - surface.preparedAt <= 200)
			{
				return surface;
			}
		}
		return null;
	}

	internal static void Fill(byte[] map, int w, int h, float lx, float ly, float rx, float ry, int windowPercent, int reduction, byte full, byte medium, byte outer)
	{
		float num = (float)windowPercent / 200f;
		float num2 = num + 0.12f * (1f - (float)reduction / 100f);
		for (int i = 0; i < h; i++)
		{
			float num3 = ((float)i + 0.5f) / (float)h - ly;
			float num4 = ((float)i + 0.5f) / (float)h - ry;
			for (int j = 0; j < w; j++)
			{
				float num5 = ((float)j + 0.5f) / (float)w - lx;
				float num6 = ((float)j + 0.5f) / (float)w - rx;
				float num7 = Math.Min(num5 * num5 + num3 * num3, num6 * num6 + num4 * num4);
				map[i * w + j] = ((num7 <= num * num) ? full : ((num7 <= num2 * num2) ? medium : outer));
			}
		}
	}
}