Decompiled source of BigScale v1.0.0

BigScale.dll

Decompiled 6 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BigScale.Core;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.LowLevel;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.XR;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BigScale")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+b9c38b44352defe5f554e8a8132796582ed1db97")]
[assembly: AssemblyProduct("BigScale")]
[assembly: AssemblyTitle("BigScale")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BigScale
{
	internal sealed class BigVisualsCompatibility
	{
		internal const string AssemblyName = "Big_Visuals";

		private const string SettingsTypeName = "Big_Visuals.Settings";

		private static readonly ManualLogSource Log = Logger.CreateLogSource("BigScale.BigVisuals");

		internal static bool DeferScaleWrites;

		internal static Camera? OwnedCamera;

		private Harmony? _harmony;

		private bool _resolutionFailed;

		private int _attempts;

		private int _nextAttemptFrame;

		private const int ScanIntervalFrames = 30;

		private Type? _settingsType;

		private MethodInfo? _setResolutionScale;

		private MethodInfo? _setUpscaler;

		private MethodInfo? _applyPostProcessAa;

		private MethodInfo? _setAllCameraSettings;

		private string _status = "Big Visuals not detected";

		private static object? _instance;

		private static bool _instanceResolved;

		internal bool Installed { get; private set; }

		internal bool IsReady
		{
			get
			{
				if (!Installed)
				{
					return _resolutionFailed;
				}
				return true;
			}
		}

		internal bool Initialize(Harmony harmony)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Expected O, but got Unknown
			if (Installed)
			{
				return true;
			}
			if (_settingsType == null && Time.frameCount < _nextAttemptFrame)
			{
				return false;
			}
			_nextAttemptFrame = Time.frameCount + 30;
			if ((object)_settingsType == null)
			{
				_settingsType = ResolveSettingsType();
			}
			if (_settingsType == null)
			{
				if (++_attempts > 600)
				{
					_resolutionFailed = true;
					_status = "Big Visuals not detected";
				}
				return false;
			}
			_setResolutionScale = _settingsType.GetMethod("SetResolutionScale", BindingFlags.Instance | BindingFlags.Public);
			_setUpscaler = _settingsType.GetMethod("SetUpscaler", BindingFlags.Instance | BindingFlags.Public);
			_applyPostProcessAa = _settingsType.GetMethod("ApplyPostProcessAA", BindingFlags.Instance | BindingFlags.Public, null, new Type[2]
			{
				typeof(Camera),
				typeof(string)
			}, null);
			_setAllCameraSettings = _settingsType.GetMethod("SetAllCameraSettings", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(100, 3, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Big Visuals.Settings signatures: SetResolutionScale=");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe(_setResolutionScale));
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("SetUpscaler=");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe(_setUpscaler));
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ApplyPostProcessAA(Camera,string)=");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe(_applyPostProcessAa));
			}
			Log.LogInfo(val);
			int num = 0;
			try
			{
				_harmony = harmony;
				if (_setResolutionScale != null)
				{
					harmony.Patch((MethodBase)_setResolutionScale, new HarmonyMethod(typeof(BigVisualsCompatibility), "PrefixSetResolutionScale", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				if (_setUpscaler != null)
				{
					harmony.Patch((MethodBase)_setUpscaler, new HarmonyMethod(typeof(BigVisualsCompatibility), "PrefixSetUpscaler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				if (_applyPostProcessAa != null)
				{
					harmony.Patch((MethodBase)_applyPostProcessAa, new HarmonyMethod(typeof(BigVisualsCompatibility), "PrefixApplyPostProcessAa", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
			}
			catch (Exception ex)
			{
				_status = "Big Visuals compatibility interception unavailable: " + ex.Message;
				Log.LogWarning((object)_status);
				DeferScaleWrites = false;
				return false;
			}
			Installed = num > 0;
			_status = (Installed ? $"Big Visuals compatibility active ({num} method(s) intercepted); its shadows, LOD, anisotropy and FOV remain untouched." : "Big Visuals detected but its graphics setters differ in this build; BigScale keeps its own requests at the camera boundary.");
			Log.LogInfo((object)_status);
			return Installed;
		}

		internal void Reapply()
		{
			if (_settingsType == null)
			{
				return;
			}
			DeferScaleWrites = false;
			OwnedCamera = null;
			try
			{
				object instance = GetInstance();
				if (instance != null)
				{
					_setResolutionScale?.Invoke(instance, null);
					_setUpscaler?.Invoke(instance, null);
					_setAllCameraSettings?.Invoke(instance, null);
					Log.LogInfo((object)"Big Visuals values reapplied after BigScale released rendering.");
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not reapply Big Visuals values: " + ex.Message));
			}
		}

		private object? GetInstance()
		{
			if (_instanceResolved)
			{
				return _instance;
			}
			_instanceResolved = true;
			BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			Type[] types = _settingsType.Assembly.GetTypes();
			foreach (Type type in types)
			{
				FieldInfo[] fields = type.GetFields(bindingAttr);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (!(fieldInfo.FieldType != _settingsType))
					{
						_instance = fieldInfo.GetValue(null);
						if (_instance != null)
						{
							return _instance;
						}
					}
				}
				PropertyInfo[] properties = type.GetProperties(bindingAttr);
				foreach (PropertyInfo propertyInfo in properties)
				{
					if (!(propertyInfo.PropertyType != _settingsType) && propertyInfo.GetIndexParameters().Length == 0)
					{
						_instance = propertyInfo.GetValue(null);
						if (_instance != null)
						{
							return _instance;
						}
					}
				}
			}
			return _instance;
		}

		private static string Describe(MethodInfo? method)
		{
			if (!(method == null))
			{
				if (!method.IsStatic)
				{
					return "instance";
				}
				return "static";
			}
			return "missing";
		}

		private static Type? ResolveSettingsType()
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!(assembly.GetName().Name != "Big_Visuals"))
				{
					try
					{
						return assembly.GetType("Big_Visuals.Settings", throwOnError: false);
					}
					catch
					{
						return null;
					}
				}
			}
			return null;
		}

		private static bool PrefixSetResolutionScale()
		{
			return !DeferScaleWrites;
		}

		private static bool PrefixSetUpscaler()
		{
			return !DeferScaleWrites;
		}

		private static bool PrefixApplyPostProcessAa(Camera camera)
		{
			if ((Object)(object)camera == (Object)null || (Object)(object)OwnedCamera == (Object)null)
			{
				return true;
			}
			return ((Object)camera).GetInstanceID() != ((Object)OwnedCamera).GetInstanceID();
		}

		internal void Dispose()
		{
			try
			{
				if (_harmony == null)
				{
					return;
				}
				if (_setResolutionScale != null)
				{
					_harmony.Unpatch((MethodBase)_setResolutionScale, AccessTools.Method(typeof(BigVisualsCompatibility), "PrefixSetResolutionScale", (Type[])null, (Type[])null));
				}
				if (_setUpscaler != null)
				{
					_harmony.Unpatch((MethodBase)_setUpscaler, AccessTools.Method(typeof(BigVisualsCompatibility), "PrefixSetUpscaler", (Type[])null, (Type[])null));
				}
				if (_applyPostProcessAa != null)
				{
					_harmony.Unpatch((MethodBase)_applyPostProcessAa, AccessTools.Method(typeof(BigVisualsCompatibility), "PrefixApplyPostProcessAa", (Type[])null, (Type[])null));
				}
			}
			catch
			{
			}
			Installed = false;
			DeferScaleWrites = false;
			OwnedCamera = null;
		}
	}
	internal sealed class CharacterMaskPass
	{
		private sealed class Payload
		{
			internal int Token;

			internal CharacterMaskDraw[] Draws = Array.Empty<CharacterMaskDraw>();

			internal int CullingMask;

			internal Material? Material;

			internal Mesh? FillMesh;

			internal Matrix4x4 WorldToCamera;

			internal Matrix4x4 Projection;
		}

		private const string PassName = "BigScale.CharacterMask";

		private const string TextureName = "BigScale.CharacterMask";

		private const string DepthTextureName = "BigScale.CharacterMaskDepth";

		private const string ScratchTextureName = "BigScale.CharacterMaskScratch";

		private const int PayloadCount = 8;

		private readonly BaseRenderFunc<DoFGaussianPassData, UnsafeGraphContext> _callback;

		private readonly Payload[] _payloads = new Payload[8];

		private readonly Action<string>? _log;

		private bool _loggedMissingCamera;

		private bool _loggedRecordingFailure;

		private bool _loggedExecutionFailure;

		private int _cursor;

		private int _lastDrawn = -1;

		private int _lastCullingMask;

		private int _nextToken;

		internal CharacterMaskPass(Action<string>? log = null)
		{
			_log = log;
			for (int i = 0; i < _payloads.Length; i++)
			{
				_payloads[i] = new Payload();
			}
			_callback = BaseRenderFunc<DoFGaussianPassData, UnsafeGraphContext>.op_Implicit((Action<DoFGaussianPassData, UnsafeGraphContext>)Execute);
		}

		internal TextureHandle Record(RenderGraph graph, UniversalCameraData cameraData, CharacterMaskDraw[] draws, Material fillMaterial, Mesh fillMesh, int width, int height)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//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)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: 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_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			if (graph == null || draws == null || draws.Length == 0 || (Object)(object)fillMaterial == (Object)null || (Object)(object)fillMesh == (Object)null || width <= 0 || height <= 0)
			{
				return TextureHandle.nullHandle;
			}
			Camera val = ((cameraData != null) ? cameraData.camera : null);
			if ((Object)(object)val == (Object)null)
			{
				if (!_loggedMissingCamera)
				{
					_loggedMissingCamera = true;
					_log?.Invoke("the character mask was requested without a camera; masking is skipped.");
				}
				return TextureHandle.nullHandle;
			}
			try
			{
				TextureDesc val2 = new TextureDesc(width, height, false, false)
				{
					format = (GraphicsFormat)5,
					clearBuffer = true,
					name = "BigScale.CharacterMask",
					filterMode = (FilterMode)1,
					wrapMode = (TextureWrapMode)1,
					useMipMap = false,
					enableRandomWrite = false,
					depthBufferBits = (DepthBits)0
				};
				TextureHandle val3 = graph.CreateTexture(ref val2);
				TextureDesc val4 = new TextureDesc(width, height, false, false)
				{
					format = (GraphicsFormat)93,
					clearBuffer = false,
					name = "BigScale.CharacterMaskDepth",
					filterMode = (FilterMode)0,
					wrapMode = (TextureWrapMode)1,
					useMipMap = false,
					enableRandomWrite = false
				};
				TextureHandle depthTexture = graph.CreateTexture(ref val4);
				TextureDesc val5 = new TextureDesc(width, height, false, false)
				{
					format = (GraphicsFormat)5,
					clearBuffer = false,
					name = "BigScale.CharacterMaskScratch",
					filterMode = (FilterMode)1,
					wrapMode = (TextureWrapMode)1,
					useMipMap = false,
					enableRandomWrite = false,
					depthBufferBits = (DepthBits)0
				};
				TextureHandle pingTexture = graph.CreateTexture(ref val5);
				Payload payload = _payloads[_cursor];
				_cursor = (_cursor + 1) % _payloads.Length;
				payload.Token = ++_nextToken;
				payload.Draws = draws;
				payload.CullingMask = val.cullingMask;
				payload.Material = fillMaterial;
				payload.FillMesh = fillMesh;
				payload.WorldToCamera = val.worldToCameraMatrix;
				payload.Projection = val.projectionMatrix;
				DoFGaussianPassData val7 = default(DoFGaussianPassData);
				IUnsafeRenderGraphBuilder val6 = graph.AddUnsafePass<DoFGaussianPassData>("BigScale.CharacterMask", ref val7, "", 0);
				try
				{
					val7.sourceTexture = val3;
					val7.depthTexture = depthTexture;
					val7.halfCoCTexture = TextureHandle.nullHandle;
					val7.fullCoCTexture = TextureHandle.nullHandle;
					val7.pingTexture = pingTexture;
					val7.pongTexture = TextureHandle.nullHandle;
					val7.destination = TextureHandle.nullHandle;
					val7.material = fillMaterial;
					val7.materialCoC = null;
					val7.cocParams = Vector3.zero;
					val7.highQualitySamplingValue = false;
					val7.downsample = payload.Token;
					IBaseRenderGraphBuilder obj = ((Il2CppObjectBase)val6).Cast<IBaseRenderGraphBuilder>();
					obj.UseTexture(ref val3, (AccessFlags)2);
					obj.UseTexture(ref depthTexture, (AccessFlags)2);
					obj.UseTexture(ref pingTexture, (AccessFlags)2);
					obj.AllowPassCulling(false);
					obj.AllowGlobalStateModification(true);
					val6.SetRenderFunc<DoFGaussianPassData>(_callback);
					return val3;
				}
				finally
				{
					((Il2CppObjectBase)val6).Cast<IDisposable>().Dispose();
				}
			}
			catch (Exception ex)
			{
				if (!_loggedRecordingFailure)
				{
					_loggedRecordingFailure = true;
					_log?.Invoke("recording the character mask failed: " + ex);
				}
				return TextureHandle.nullHandle;
			}
		}

		private void Execute(DoFGaussianPassData data, UnsafeGraphContext context)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Invalid comparison between Unknown and I4
			try
			{
				Payload payload = null;
				for (int i = 0; i < _payloads.Length; i++)
				{
					if (_payloads[i].Token == data.downsample)
					{
						payload = _payloads[i];
						break;
					}
				}
				RenderTexture val = UpscalingPass.ResolveTexture(data.sourceTexture);
				RenderTexture val2 = UpscalingPass.ResolveTexture(data.depthTexture);
				RenderTexture val3 = UpscalingPass.ResolveTexture(data.pingTexture);
				if (payload == null || (Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null || (Object)(object)payload.Material == (Object)null || (Object)(object)payload.FillMesh == (Object)null)
				{
					if (!_loggedExecutionFailure)
					{
						_loggedExecutionFailure = true;
						_log?.Invoke("the character mask could not be resolved at execution; masking is skipped.");
					}
					return;
				}
				CommandBuffer nativeCommandBuffer = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
				RenderTargetIdentifier val4 = default(RenderTargetIdentifier);
				((RenderTargetIdentifier)(ref val4))..ctor((Texture)(object)val2);
				nativeCommandBuffer.SetRenderTarget(new RenderTargetIdentifier((Texture)(object)val3), val4);
				nativeCommandBuffer.ClearRenderTarget(true, true, Color.clear);
				nativeCommandBuffer.SetViewProjectionMatrices(payload.WorldToCamera, payload.Projection);
				CharacterMaskDraw[] draws = payload.Draws;
				int num = 0;
				for (int j = 0; j < draws.Length; j++)
				{
					CharacterMaskDraw characterMaskDraw = draws[j];
					Renderer renderer = characterMaskDraw.Renderer;
					GameObject owner = characterMaskDraw.Owner;
					if (!((Object)(object)renderer == (Object)null) && !((Object)(object)owner == (Object)null) && !((Object)(object)characterMaskDraw.Material == (Object)null) && CharacterMaskPolicy.IsDrawnByCamera(payload.CullingMask, owner.layer, renderer.enabled, owner.activeInHierarchy, renderer.forceRenderingOff, (int)renderer.shadowCastingMode == 3))
					{
						nativeCommandBuffer.DrawRenderer(renderer, characterMaskDraw.Material, characterMaskDraw.Submesh, characterMaskDraw.Pass);
						num++;
					}
				}
				nativeCommandBuffer.SetRenderTarget(new RenderTargetIdentifier((Texture)(object)val), val4);
				nativeCommandBuffer.ClearRenderTarget(false, true, Color.black);
				if (num > 0)
				{
					nativeCommandBuffer.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
					nativeCommandBuffer.DrawMesh(payload.FillMesh, Matrix4x4.identity, payload.Material, 0, 0);
					nativeCommandBuffer.SetViewProjectionMatrices(payload.WorldToCamera, payload.Projection);
				}
				if (num != _lastDrawn || payload.CullingMask != _lastCullingMask)
				{
					_lastDrawn = num;
					_lastCullingMask = payload.CullingMask;
					_log?.Invoke($"character mask: drawing {num}/{draws.Length} draw(s), camera culling mask 0x{payload.CullingMask:X8}");
				}
			}
			catch (Exception ex)
			{
				if (!_loggedExecutionFailure)
				{
					_loggedExecutionFailure = true;
					_log?.Invoke("drawing the character mask failed: " + ex);
				}
			}
		}
	}
	internal readonly struct CharacterMaskDraw
	{
		internal readonly Renderer Renderer;

		internal readonly GameObject Owner;

		internal readonly Material Material;

		internal readonly int Submesh;

		internal readonly int Pass;

		internal CharacterMaskDraw(Renderer renderer, GameObject owner, Material material, int submesh, int pass)
		{
			Renderer = renderer;
			Owner = owner;
			Material = material;
			Submesh = submesh;
			Pass = pass;
		}
	}
	internal sealed class CharacterMaskSource : IDisposable
	{
		private sealed class ShaderPasses
		{
			internal string?[] Modes = Array.Empty<string>();
		}

		private sealed class MaterialPass
		{
			internal bool[] Enabled = Array.Empty<bool>();
		}

		private const int RescanFrames = 120;

		private const string ColoredShaderName = "Hidden/Internal-Colored";

		private const string MaterialName = "BigScale.CharacterMask";

		private const string FillMeshName = "BigScale.CharacterMaskFill";

		private const double SlowScanMilliseconds = 2.0;

		private const int SlowScanReportFrames = 600;

		private readonly ModSettings _settings;

		private readonly Action<string> _log;

		private readonly List<CharacterMaskDraw> _drawsCollected = new List<CharacterMaskDraw>();

		private readonly List<Renderer> _localCollected = new List<Renderer>();

		private readonly List<string> _extras = new List<string>();

		private readonly Dictionary<int, MaterialPass> _materialPasses = new Dictionary<int, MaterialPass>();

		private readonly Dictionary<int, ShaderPasses> _shaderPasses = new Dictionary<int, ShaderPasses>();

		private readonly Stopwatch _scanWatch = new Stopwatch();

		private CharacterMaskDraw[] _draws = Array.Empty<CharacterMaskDraw>();

		private Material? _material;

		private Mesh? _fillMesh;

		private bool _materialReported;

		private bool _meshReported;

		private bool _scanReported;

		private bool _disposed;

		private bool _rescanRequested;

		private int _nextScanFrame;

		private int _renderersIncluded;

		private int _localIncluded;

		private int _noPassSubmeshes;

		private int _lastRenderers = -1;

		private int _lastDraws = -1;

		private int _lastLocal = -1;

		private int _lastNoPass = -1;

		private string? _lastCharacterListFailure;

		private int _lastSlowScanFrame = -600;

		internal CharacterMaskDraw[] Draws => _draws;

		internal Material? Material => _material;

		internal Mesh? FillMesh => _fillMesh;

		internal CharacterMaskSource(ModSettings settings, Action<string> log)
		{
			_settings = settings;
			_log = log;
		}

		internal void Tick(bool force = false)
		{
			if (_disposed || !EffectivelyEnabled() || (!force && !_rescanRequested && Time.frameCount < _nextScanFrame))
			{
				return;
			}
			_rescanRequested = false;
			_scanWatch.Restart();
			try
			{
				Rebuild();
			}
			catch (Exception ex)
			{
				if (!_scanReported)
				{
					_scanReported = true;
					_log("character mask: scan failed: " + ex.Message);
				}
			}
			finally
			{
				_scanWatch.Stop();
				_nextScanFrame = Time.frameCount + 120;
				ReportSlowScan();
			}
		}

		internal void Invalidate()
		{
			if (!_disposed)
			{
				_draws = Array.Empty<CharacterMaskDraw>();
				_nextScanFrame = 0;
				_rescanRequested = true;
			}
		}

		public void Dispose()
		{
			if (!_disposed)
			{
				_disposed = true;
				if ((Object)(object)_material != (Object)null)
				{
					Object.Destroy((Object)(object)_material);
					_material = null;
				}
				if ((Object)(object)_fillMesh != (Object)null)
				{
					Object.Destroy((Object)(object)_fillMesh);
					_fillMesh = null;
				}
				_draws = Array.Empty<CharacterMaskDraw>();
				_drawsCollected.Clear();
				_localCollected.Clear();
				_extras.Clear();
			}
		}

		private bool EffectivelyEnabled()
		{
			try
			{
				return _settings.DLSS5Enabled.Value && _settings.DLSS5MasterEnabled.Value && _settings.Upscaler.Value != UpscalerKind.Off && _settings.DLSS5CharacterMask.Value;
			}
			catch (Exception)
			{
				return false;
			}
		}

		private void Rebuild()
		{
			if (_materialPasses.Count > 256 || _shaderPasses.Count > 64)
			{
				_materialPasses.Clear();
				_shaderPasses.Clear();
			}
			ParseExtras();
			_drawsCollected.Clear();
			_localCollected.Clear();
			_renderersIncluded = 0;
			_localIncluded = 0;
			_noPassSubmeshes = 0;
			Transform localRoot = null;
			try
			{
				PlayerCharacter localPlayerCharacter = WorldManager.localPlayerCharacter;
				GameObject val = (((Object)(object)localPlayerCharacter != (Object)null) ? ((Component)localPlayerCharacter).gameObject : null);
				if ((Object)(object)val != (Object)null)
				{
					localRoot = val.transform;
				}
			}
			catch (Exception)
			{
			}
			List<PlayerCharacter> allPlayerCharacters;
			try
			{
				allPlayerCharacters = PlayerCharacter.allPlayerCharacters;
			}
			catch (Exception ex2)
			{
				ReportCharacterListUnavailable(ex2.Message);
				_nextScanFrame = Time.frameCount + 120;
				return;
			}
			if (allPlayerCharacters == null || allPlayerCharacters.Count == 0)
			{
				ReportCharacterListUnavailable("empty list");
				_nextScanFrame = Time.frameCount + 120;
				return;
			}
			for (int i = 0; i < allPlayerCharacters.Count; i++)
			{
				PlayerCharacter val2 = allPlayerCharacters[i];
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				try
				{
					GameObject gameObject = ((Component)val2).gameObject;
					if ((Object)(object)gameObject == (Object)null)
					{
						continue;
					}
					Il2CppArrayBase<Renderer> componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(true);
					if (componentsInChildren == null)
					{
						continue;
					}
					foreach (Renderer item in componentsInChildren)
					{
						if ((Object)(object)item != (Object)null)
						{
							ScanRenderer(item, localRoot);
						}
					}
				}
				catch (Exception)
				{
				}
			}
			_draws = _drawsCollected.ToArray();
			EnsureResources();
			Report();
		}

		private void ReportCharacterListUnavailable(string message)
		{
			if (!string.Equals(_lastCharacterListFailure, message, StringComparison.Ordinal))
			{
				_lastCharacterListFailure = message;
				_log("character mask: player character list unavailable: " + message);
			}
		}

		private void ScanRenderer(Renderer renderer, Transform? localRoot)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject;
			try
			{
				gameObject = ((Component)renderer).gameObject;
			}
			catch (Exception)
			{
				return;
			}
			if ((Object)(object)gameObject == (Object)null)
			{
				return;
			}
			bool flag;
			try
			{
				Scene scene = gameObject.scene;
				flag = ((Scene)(ref scene)).IsValid();
			}
			catch (Exception)
			{
				return;
			}
			int num;
			int num2;
			if (flag)
			{
				num = (IsMaskRenderer(renderer) ? 1 : 0);
				if (num != 0 && (Object)(object)localRoot != (Object)null)
				{
					num2 = (IsDescendant(((Component)renderer).transform, localRoot) ? 1 : 0);
					goto IL_0059;
				}
			}
			else
			{
				num = 0;
			}
			num2 = 0;
			goto IL_0059;
			IL_0059:
			bool flag2 = (byte)num2 != 0;
			bool flag3 = (byte)num != 0;
			if (flag3)
			{
				string name;
				try
				{
					Material sharedMaterial = renderer.sharedMaterial;
					Shader val = (((Object)(object)sharedMaterial != (Object)null) ? sharedMaterial.shader : null);
					name = (((Object)(object)val != (Object)null) ? ((Object)val).name : null);
				}
				catch (Exception)
				{
					name = null;
				}
				flag3 = CharacterMaskPolicy.IsCharacterShader(name, _extras);
			}
			if (!flag3 && flag2)
			{
				flag3 = true;
			}
			if (flag3)
			{
				Collect(renderer, gameObject, flag2);
			}
		}

		private void ReportSlowScan()
		{
			if (!(_scanWatch.Elapsed.TotalMilliseconds < 2.0) && Time.frameCount >= _lastSlowScanFrame + 600)
			{
				_lastSlowScanFrame = Time.frameCount;
				_log($"character mask: scan took {_scanWatch.Elapsed.TotalMilliseconds:F1} ms for {_renderersIncluded} renderer(s)");
			}
		}

		private void Collect(Renderer renderer, GameObject owner, bool local)
		{
			try
			{
				Il2CppReferenceArray<Material> sharedMaterials = renderer.sharedMaterials;
				int num = Math.Min(SubmeshCount(renderer), ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length);
				for (int i = 0; i < num; i++)
				{
					Material val = ((Il2CppArrayBase<Material>)(object)sharedMaterials)[i];
					if (!((Object)(object)val == (Object)null) && IsOpaqueMaskMaterial(val) && (!local || !IsLocalNose(val)))
					{
						int num2 = ForwardPass(val);
						if (num2 < 0)
						{
							_noPassSubmeshes++;
						}
						else
						{
							_drawsCollected.Add(new CharacterMaskDraw(renderer, owner, val, i, num2));
						}
					}
				}
			}
			catch (Exception)
			{
				return;
			}
			_renderersIncluded++;
			if (local)
			{
				_localIncluded++;
				_localCollected.Add(renderer);
			}
		}

		private void ParseExtras()
		{
			_extras.Clear();
			string value;
			try
			{
				value = _settings.DLSS5CharacterMaskShaders.Value;
			}
			catch (Exception)
			{
				return;
			}
			if (string.IsNullOrEmpty(value))
			{
				return;
			}
			string[] array = value.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					_extras.Add(text);
				}
			}
		}

		private static bool IsMaskRenderer(Renderer renderer)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			try
			{
				if ((Object)(object)renderer == (Object)null || !renderer.enabled || renderer.forceRenderingOff)
				{
					return false;
				}
				GameObject gameObject = ((Component)renderer).gameObject;
				if ((Object)(object)gameObject == (Object)null || !gameObject.activeInHierarchy)
				{
					return false;
				}
				if ((int)renderer.shadowCastingMode == 3)
				{
					return false;
				}
				if ((Object)(object)((Il2CppObjectBase)renderer).TryCast<MeshRenderer>() == (Object)null && (Object)(object)((Il2CppObjectBase)renderer).TryCast<SkinnedMeshRenderer>() == (Object)null)
				{
					return false;
				}
				return IsOpaqueMaskMaterial(renderer.sharedMaterial);
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static bool IsOpaqueMaskMaterial(Material? material)
		{
			if ((Object)(object)material == (Object)null)
			{
				return false;
			}
			if (material.renderQueue > 2500)
			{
				return false;
			}
			Shader shader = material.shader;
			string text = (((Object)(object)shader != (Object)null) ? ((Object)shader).name : string.Empty);
			if (text.IndexOf("shadow", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("blob", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("decal", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return text.IndexOf("projector", StringComparison.OrdinalIgnoreCase) < 0;
			}
			return false;
		}

		private static bool IsLocalNose(Material material)
		{
			Shader shader = material.shader;
			if ((Object)(object)shader != (Object)null)
			{
				return string.Equals(((Object)shader).name, "househouse/PlayerNose", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private int ForwardPass(Material material)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Shader shader = material.shader;
				if ((Object)(object)shader == (Object)null)
				{
					return -1;
				}
				ShaderTagId val = default(ShaderTagId);
				((ShaderTagId)(ref val))..ctor("LightMode");
				int passCount = shader.passCount;
				if (passCount <= 0)
				{
					return -1;
				}
				int instanceID = ((Object)shader).GetInstanceID();
				_shaderPasses.TryGetValue(instanceID, out ShaderPasses value);
				if (value == null || value.Modes.Length != passCount)
				{
					string[] array = new string[passCount];
					for (int i = 0; i < passCount; i++)
					{
						ShaderTagId val2 = shader.FindPassTagValue(i, val);
						string name = ((ShaderTagId)(ref val2)).name;
						array[i] = (string.IsNullOrEmpty(name) ? null : name);
					}
					value = new ShaderPasses
					{
						Modes = array
					};
					_shaderPasses[instanceID] = value;
				}
				int instanceID2 = ((Object)material).GetInstanceID();
				_materialPasses.TryGetValue(instanceID2, out MaterialPass value2);
				if (value2 == null)
				{
					value2 = new MaterialPass();
					_materialPasses[instanceID2] = value2;
				}
				bool[] array2 = value2.Enabled;
				if (array2.Length != passCount)
				{
					array2 = (value2.Enabled = new bool[passCount]);
				}
				string[] modes = value.Modes;
				for (int j = 0; j < passCount; j++)
				{
					string text = modes[j];
					bool flag = text == null;
					array2[j] = material.GetShaderPassEnabled(flag ? "SRPDefaultUnlit" : text);
				}
				return CharacterMaskPolicy.SelectForwardPass(modes, array2);
			}
			catch (Exception)
			{
				return -1;
			}
		}

		private static int SubmeshCount(Renderer renderer)
		{
			SkinnedMeshRenderer val = ((Il2CppObjectBase)renderer).TryCast<SkinnedMeshRenderer>();
			if ((Object)(object)val != (Object)null)
			{
				Mesh sharedMesh = val.sharedMesh;
				if (!((Object)(object)sharedMesh != (Object)null))
				{
					return 0;
				}
				return sharedMesh.subMeshCount;
			}
			MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>();
			Mesh val2 = (((Object)(object)component != (Object)null) ? component.sharedMesh : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return 0;
			}
			return val2.subMeshCount;
		}

		private static bool IsDescendant(Transform? transform, Transform root)
		{
			try
			{
				Transform val = transform;
				while ((Object)(object)val != (Object)null)
				{
					if ((Object)(object)val == (Object)(object)root)
					{
						return true;
					}
					val = val.parent;
				}
			}
			catch (Exception)
			{
			}
			return false;
		}

		private void EnsureResources()
		{
			EnsureMaterial();
			EnsureFillMesh();
		}

		private void EnsureMaterial()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_material != (Object)null || _materialReported)
			{
				return;
			}
			Material val = null;
			try
			{
				Shader val2 = Shader.Find("Hidden/Internal-Colored");
				if ((Object)(object)val2 != (Object)null)
				{
					val = new Material(val2)
					{
						name = "BigScale.CharacterMask",
						hideFlags = (HideFlags)61
					};
				}
				if ((Object)(object)val == (Object)null || !val.HasProperty("_ZTest"))
				{
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
					_materialReported = true;
					_log("character mask: Hidden/Internal-Colored is unavailable; character masking is unavailable");
				}
				else
				{
					val.SetColor("_Color", Color.white);
					val.SetFloat("_Cull", 0f);
					val.SetFloat("_ZWrite", 0f);
					val.SetFloat("_ZTest", 6f);
					val.SetFloat("_SrcBlend", 1f);
					val.SetFloat("_DstBlend", 0f);
					val.SetFloat("_ZBias", 0f);
					_material = val;
				}
			}
			catch (Exception ex)
			{
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				_materialReported = true;
				_log("character mask: material creation failed: " + ex.Message);
			}
		}

		private void EnsureFillMesh()
		{
			//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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//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_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_fillMesh != (Object)null || _meshReported)
			{
				return;
			}
			try
			{
				Mesh val = new Mesh
				{
					name = "BigScale.CharacterMaskFill",
					hideFlags = (HideFlags)61
				};
				val.vertices = new Il2CppStructArray<Vector3>((Vector3[])(object)new Vector3[3]
				{
					new Vector3(-1f, -1f, 1f),
					new Vector3(3f, -1f, 1f),
					new Vector3(-1f, 3f, 1f)
				});
				val.triangles = new Il2CppStructArray<int>(new int[3] { 0, 1, 2 });
				val.bounds = new Bounds(Vector3.zero, new Vector3(8f, 8f, 8f));
				_fillMesh = val;
			}
			catch (Exception ex)
			{
				_meshReported = true;
				_log("character mask: fill mesh creation failed: " + ex.Message);
			}
		}

		private void Report()
		{
			int num = _draws.Length;
			if (_renderersIncluded == _lastRenderers && num == _lastDraws && _localIncluded == _lastLocal && _noPassSubmeshes == _lastNoPass)
			{
				return;
			}
			_lastRenderers = _renderersIncluded;
			_lastDraws = num;
			_lastLocal = _localIncluded;
			_lastNoPass = _noPassSubmeshes;
			_log($"character mask: {_renderersIncluded} renderer(s), {num} draw(s), local player {_localIncluded}, {_noPassSubmeshes} submesh(es) without a forward pass");
			for (int i = 0; i < _localCollected.Count; i++)
			{
				try
				{
					_log(DescribeLocal(_localCollected[i]));
				}
				catch (Exception)
				{
					_log("character mask local renderer: unreadable");
				}
			}
		}

		private string DescribeLocal(Renderer renderer)
		{
			bool flag = (Object)(object)((Il2CppObjectBase)renderer).TryCast<SkinnedMeshRenderer>() != (Object)null;
			Il2CppReferenceArray<Material> sharedMaterials = renderer.sharedMaterials;
			int num = Math.Min(SubmeshCount(renderer), ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length);
			string[] array = new string[num];
			for (int i = 0; i < num; i++)
			{
				Material val = ((Il2CppArrayBase<Material>)(object)sharedMaterials)[i];
				if ((Object)(object)val == (Object)null)
				{
					array[i] = "null";
					continue;
				}
				Shader shader = val.shader;
				string text = (((Object)(object)shader != (Object)null) ? ((Object)shader).name : "<no shader>");
				array[i] = (IsLocalNose(val) ? (text + " excluded (local nose)") : $"{text} q{val.renderQueue} pass {ForwardPass(val)}");
			}
			return $"character mask local renderer: '{((Object)renderer).name}' {(flag ? "skinned" : "mesh")} layer {((Component)renderer).gameObject.layer}: {string.Join("; ", array)}";
		}
	}
	internal sealed class FrameGenerationCaptureHook
	{
		private readonly FrameGenerationCoordinator _coordinator;

		private readonly Action<string> _log;

		private Harmony? _harmony;

		private MethodInfo? _renderGraph;

		private MethodInfo? _inputs;

		private MethodInfo? _renderOverlay;

		internal bool Installed { get; private set; }

		internal string Status { get; private set; } = "not installed";

		internal FrameGenerationCaptureHook(FrameGenerationCoordinator coordinator, Action<string> log)
		{
			_coordinator = coordinator;
			_log = log;
		}

		internal bool Install(Harmony harmony)
		{
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: 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_01a3: Expected O, but got Unknown
			//IL_01a3: Expected O, but got Unknown
			//IL_01a3: Expected O, but got Unknown
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Expected O, but got Unknown
			if (Installed)
			{
				return true;
			}
			_renderGraph = AccessTools.Method(typeof(UniversalRenderer), "OnRecordRenderGraph", new Type[2]
			{
				typeof(RenderGraph),
				typeof(ScriptableRenderContext)
			}, (Type[])null);
			if (_renderGraph == null)
			{
				Status = "UniversalRenderer.OnRecordRenderGraph(RenderGraph, ScriptableRenderContext) is missing";
				_log(Status);
				return false;
			}
			_inputs = AccessTools.Method(typeof(UniversalRenderer), "GetRenderPassInputs", (Type[])null, (Type[])null);
			if (_inputs == null || _inputs.GetParameters().Length != 6)
			{
				Status = "UniversalRenderer.GetRenderPassInputs does not match the inspected build";
				_log(Status);
				return false;
			}
			Type type = typeof(TextureHandle).MakeByRefType();
			Type[] array = new Type[4]
			{
				typeof(RenderGraph),
				typeof(ContextContainer),
				type,
				type
			};
			MethodInfo methodInfo = AccessTools.Method(typeof(DrawScreenSpaceUIPass), "RenderOverlay", array, (Type[])null);
			string text = ValidateOverlay(methodInfo, array);
			if (text != null)
			{
				Status = "DrawScreenSpaceUIPass.RenderOverlay(RenderGraph, ContextContainer, ref TextureHandle, ref TextureHandle) is unusable: " + text;
				_log(Status);
				return false;
			}
			_renderOverlay = methodInfo;
			try
			{
				_harmony = harmony;
				harmony.Patch((MethodBase)_renderGraph, new HarmonyMethod(typeof(FrameGenerationCaptureHook), "RenderGraphPrefix", (Type[])null), new HarmonyMethod(typeof(FrameGenerationCaptureHook), "RenderGraphPostfix", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(FrameGenerationCaptureHook), "RenderGraphFinalizer", (Type[])null), (HarmonyMethod)null);
				harmony.Patch((MethodBase)_inputs, (HarmonyMethod)null, new HarmonyMethod(typeof(FrameGenerationCaptureHook), "InputsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FrameGenerationCaptureHook), "OverlayPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Installed = true;
				Status = "frame-generation capture hooks installed";
				_log("frame-generation capture hooks installed; overlay prefix on the " + (methodInfo.IsStatic ? "static" : "instance") + " overload " + Describe(methodInfo) + "; render-graph prefix on " + Describe(_renderGraph) + ".");
				return true;
			}
			catch (Exception ex)
			{
				Status = "could not patch the URP frame-generation entry points: " + ex.Message;
				_log(Status);
				return false;
			}
		}

		internal void Uninstall()
		{
			if (_harmony == null)
			{
				return;
			}
			try
			{
				if (_renderGraph != null)
				{
					_harmony.Unpatch((MethodBase)_renderGraph, AccessTools.Method(typeof(FrameGenerationCaptureHook), "RenderGraphPrefix", (Type[])null, (Type[])null));
					_harmony.Unpatch((MethodBase)_renderGraph, AccessTools.Method(typeof(FrameGenerationCaptureHook), "RenderGraphPostfix", (Type[])null, (Type[])null));
					_harmony.Unpatch((MethodBase)_renderGraph, AccessTools.Method(typeof(FrameGenerationCaptureHook), "RenderGraphFinalizer", (Type[])null, (Type[])null));
				}
				if (_inputs != null)
				{
					_harmony.Unpatch((MethodBase)_inputs, AccessTools.Method(typeof(FrameGenerationCaptureHook), "InputsPostfix", (Type[])null, (Type[])null));
				}
				if (_renderOverlay != null)
				{
					_harmony.Unpatch((MethodBase)_renderOverlay, AccessTools.Method(typeof(FrameGenerationCaptureHook), "OverlayPrefix", (Type[])null, (Type[])null));
				}
			}
			catch
			{
			}
			_harmony = null;
			Installed = false;
			Status = "uninstalled";
		}

		private static string? ValidateOverlay(MethodInfo? method, Type[] expected)
		{
			if (method == null)
			{
				return "the method does not exist in this build";
			}
			if (method.DeclaringType != typeof(DrawScreenSpaceUIPass))
			{
				return "it is declared by " + (method.DeclaringType?.FullName ?? "?");
			}
			if (method.ReturnType != typeof(void))
			{
				return "it returns " + method.ReturnType.Name;
			}
			ParameterInfo[] parameters = method.GetParameters();
			if (parameters.Length != expected.Length)
			{
				return $"it takes {parameters.Length} parameters, not {expected.Length}";
			}
			for (int i = 0; i < expected.Length; i++)
			{
				Type parameterType = parameters[i].ParameterType;
				if (parameterType != expected[i])
				{
					return $"parameter {i} is {parameterType.Name}, not {expected[i].Name}";
				}
				if (i >= 2 && !parameterType.IsByRef)
				{
					return $"parameter {i} is not passed by reference";
				}
			}
			return null;
		}

		private static string Describe(MethodInfo? method)
		{
			if (method == null)
			{
				return "<null>";
			}
			ParameterInfo[] parameters = method.GetParameters();
			string[] array = new string[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType.Name + " " + parameters[i].Name;
			}
			return (method.DeclaringType?.Name ?? "?") + "." + method.Name + "(" + string.Join(", ", array) + ")";
		}

		private static void RenderGraphPrefix(UniversalRenderer __instance, ref int __state)
		{
			RenderCoordinator renderCoordinator = Plugin.Instance?.Coordinator;
			if (renderCoordinator == null)
			{
				return;
			}
			try
			{
				__state = ((!renderCoordinator.BeginXrReconstructionInputs(__instance)) ? 1 : 2);
			}
			catch (Exception exception)
			{
				__state = 1;
				renderCoordinator.ReportXrInputFailure(exception);
			}
			FrameGenerationCoordinator frameGeneration = renderCoordinator.FrameGeneration;
			try
			{
				frameGeneration.CaptureBegin(__instance);
			}
			catch (Exception ex)
			{
				frameGeneration.CaptureAbort();
				frameGeneration.ReportCaptureFailure("frame-generation capture prefix failed: " + ex);
			}
		}

		private static void RenderGraphPostfix(UniversalRenderer __instance, RenderGraph renderGraph)
		{
			FrameGenerationCoordinator frameGenerationCoordinator = Plugin.Instance?.Coordinator?.FrameGeneration;
			if (frameGenerationCoordinator == null)
			{
				return;
			}
			try
			{
				frameGenerationCoordinator.CaptureEnd(__instance, renderGraph);
			}
			catch (Exception ex)
			{
				frameGenerationCoordinator.CaptureAbort();
				frameGenerationCoordinator.ReportCaptureFailure("frame-generation capture postfix failed: " + ex);
			}
		}

		private static void RenderGraphFinalizer(int __state)
		{
			RenderCoordinator renderCoordinator = Plugin.Instance?.Coordinator;
			if (renderCoordinator != null)
			{
				renderCoordinator.FrameGeneration.CaptureAbort();
				if (__state != 0)
				{
					renderCoordinator.EndXrReconstructionInputs(__state == 2);
				}
			}
		}

		private static void OverlayPrefix(RenderGraph renderGraph, ContextContainer frameData, ref TextureHandle colorBuffer)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			FrameGenerationCoordinator frameGenerationCoordinator = Plugin.Instance?.Coordinator?.FrameGeneration;
			if (frameGenerationCoordinator == null)
			{
				return;
			}
			try
			{
				frameGenerationCoordinator.CaptureBeforeUi(renderGraph, frameData, colorBuffer);
			}
			catch (Exception ex)
			{
				frameGenerationCoordinator.ReportCaptureFailure("pre-overlay frame-generation capture failed: " + ex);
			}
		}

		private static void InputsPostfix(ref RenderPassInputSummary __result)
		{
			RenderCoordinator renderCoordinator = Plugin.Instance?.Coordinator;
			if (renderCoordinator == null)
			{
				return;
			}
			try
			{
				renderCoordinator.RequestXrReconstructionInputs(ref __result);
			}
			catch (Exception exception)
			{
				renderCoordinator.ReportXrInputFailure(exception);
			}
			FrameGenerationCoordinator frameGeneration = renderCoordinator.FrameGeneration;
			try
			{
				frameGeneration.RequestCaptureInputs(ref __result);
			}
			catch (Exception ex)
			{
				frameGeneration.CaptureAbort();
				frameGeneration.ReportCaptureFailure("frame-generation input request failed: " + ex);
			}
		}
	}
	internal sealed class FrameGenerationCoordinator
	{
		private sealed class CaptureGeometry
		{
			internal int CameraId;

			internal int RenderWidth;

			internal int RenderHeight;

			internal int OutputWidth;

			internal int OutputHeight;

			internal int HistoryEpoch;

			internal bool ReversedDepth;

			internal bool RendersOverlay;

			internal uint Generation;

			internal bool SameExtent(CaptureGeometry other)
			{
				if (other != null && CameraId == other.CameraId && RenderWidth == other.RenderWidth && RenderHeight == other.RenderHeight && OutputWidth == other.OutputWidth && OutputHeight == other.OutputHeight)
				{
					return ReversedDepth == other.ReversedDepth;
				}
				return false;
			}
		}

		internal static class NativeFgState
		{
			internal const int Off = 0;

			internal const int WaitingSwapchain = 1;

			internal const int WaitingWindow = 2;

			internal const int Initializing = 3;

			internal const int WaitingFirstGenerated = 4;

			internal const int Active = 5;

			internal const int Suspended = 6;

			internal const int Draining = 7;

			internal const int Faulted = 8;

			internal const int Unsupported = 9;
		}

		private readonly FrameGenerationPass _pass;

		private readonly Action<string> _log;

		private readonly bool _xrProof;

		private IntPtr _renderEvent;

		private string? _unavailable;

		private string? _captureFailure;

		private bool _sceneSuspended;

		private string? _nativeFault;

		private bool _nativeFaultUnsupported;

		private int _provider = int.MinValue;

		private int _effectiveProvider = int.MinValue;

		private int _xr;

		private int _menu;

		private const string RestartReason = "restart the game to switch between ANR and other frame-generation providers";

		private bool _gameplayActive;

		private int _gameplayCameraId;

		private bool _gameplayReadFailed;

		private bool _captureKeyFailed;

		private int _rendererInventoryCameraId;

		private int _cameraId;

		private int _epoch;

		private uint _generation;

		private uint _configuredGeneration = uint.MaxValue;

		private uint _captureReady;

		private IntPtr _presenterParent;

		private IntPtr _presenterAttempt;

		private ulong _presentId;

		private string? _pendingFailure;

		private CaptureGeometry? _approvedGeometry;

		private CaptureGeometry? _pendingGeometry;

		private CaptureGeometry? _suspendedGeometry;

		private readonly HashSet<string> _cameraLog = new HashSet<string>();

		private int _loggedProvider = int.MinValue;

		private uint _loggedGeneration = uint.MaxValue;

		private int _loggedState = int.MinValue;

		private string _loggedReason = "";

		private float _diagnosticWindowStart;

		private bool _scope;

		private bool _scopeRecorded;

		private volatile bool _reconstructionActive = true;

		private bool _scopeNeedsHudless;

		private UniversalCameraData? _scopeCamera;

		private Matrix4x4 _scopeJitter;

		private CaptureGeometry? _scopeGeometry;

		private uint _scopeGeneration;

		private int _scopeEpoch;

		private bool _previousValid;

		private int _previousCameraId = -1;

		private int _previousEpoch = -1;

		private Matrix4x4 _previousView;

		private Matrix4x4 _previousProjection;

		private readonly FrameGenerationActivity _activity = new FrameGenerationActivity();

		private readonly HudTelemetry _presentedRate = new HudTelemetry();

		private bool _activityNeedsReset;

		private NativeFg.Status _lastStatus;

		private bool _hasStatus;

		private int _lastRequested;

		private FrameGenerationKind _lastRequestedKind;

		private readonly int[] _providerMaximum = new int[6] { 0, 0, 2, 0, 0, 0 };

		private int _effectiveMultiplier = 2;

		private int _configuredMultiplier = int.MinValue;

		internal string HudLine { get; private set; } = "FG: Off - 1x - Off";

		internal bool FpsDecorationActive
		{
			get
			{
				if (_lastRequestedKind != FrameGenerationKind.Off && _xr == 0)
				{
					return !VrState.Active;
				}
				return false;
			}
		}

		internal string CaptureHookStatus { get; set; } = "not installed";

		internal string? Unavailable => _unavailable;

		internal FrameGenerationCoordinator(Action<string> log, bool xrProof)
		{
			_log = log;
			_xrProof = xrProof;
			_pass = new FrameGenerationPass(log);
		}

		internal bool RestartRequiredFor(FrameGenerationKind requested)
		{
			if (_hasStatus && _xr == 0 && !VrState.Active)
			{
				return RestartFor(in _lastStatus, requested);
			}
			return false;
		}

		private static bool RestartFor(in NativeFg.Status status, FrameGenerationKind requested)
		{
			return FrameGenerationFamily.RestartRequired(status.ProcessFamily, requested);
		}

		internal int ReportedMaximumMultiplier(FrameGenerationKind provider)
		{
			if (provider != FrameGenerationKind.Off)
			{
				return _providerMaximum[(int)provider];
			}
			return 0;
		}

		internal bool TryGetStatus(out NativeFg.Status status)
		{
			status = _lastStatus;
			return _hasStatus;
		}

		internal void AttachNative(IntPtr renderEvent)
		{
			if (renderEvent == IntPtr.Zero)
			{
				SetUnavailable("the frame-generation render event is unavailable");
			}
			else
			{
				_renderEvent = renderEvent;
			}
		}

		internal void SetUnavailable(string reason)
		{
			_unavailable = (string.IsNullOrEmpty(reason) ? "frame generation could not be set up" : reason);
			_scope = false;
			_presentedRate.Reset();
		}

		internal void ReportCaptureFailure(string reason)
		{
			PublishFailure(string.IsNullOrEmpty(reason) ? "the frame-generation capture failed" : reason);
		}

		private void PublishFailure(string reason)
		{
			Interlocked.CompareExchange(ref _pendingFailure, reason, null);
		}

		private string? TakeFailure()
		{
			return Interlocked.Exchange(ref _pendingFailure, null);
		}

		internal void BeginFrame()
		{
			if (!(_renderEvent == IntPtr.Zero) && _nativeFault == null && _gameplayActive && _xr == 0 && !VrState.Active && _lastRequestedKind != FrameGenerationKind.Off)
			{
				_presentId++;
				NativeFg.BeginFrame(_presentId);
			}
		}

		internal void EndSimulation()
		{
			if (!(_renderEvent == IntPtr.Zero) && _gameplayActive && _xr == 0 && !VrState.Active && _lastRequestedKind != FrameGenerationKind.Off)
			{
				NativeFg.EndSimulation(_presentId);
			}
		}

		internal void Tick(ModSettings settings, bool xrActive, bool menuVisible)
		{
			_pass.AbandonStaleLeases(Time.frameCount);
			string text = _pass.TakeFailure();
			if (text != null)
			{
				ReportCaptureFailure(text);
			}
			string text2 = TakeFailure();
			if (text2 != null && _captureFailure == null)
			{
				_captureFailure = text2;
				_captureReady = 0u;
				_scope = false;
				_log("frame generation faulted: " + text2);
			}
			FrameGenerationKind frameGenerationKind = (settings.Enabled.Value ? UpscalingModes.Selectable(settings.FrameGeneration.Value) : FrameGenerationKind.Off);
			int num = (int)frameGenerationKind;
			if (_renderEvent == IntPtr.Zero)
			{
				_lastRequested = num;
				_lastRequestedKind = frameGenerationKind;
				HudLine = ComposeUnavailable(frameGenerationKind);
				return;
			}
			UpdateGameplayState();
			PollCaptureKey(settings);
			if (settings.Diagnostics.Value && _gameplayActive && _gameplayCameraId != _rendererInventoryCameraId)
			{
				LogPlayerRenderers();
				_rendererInventoryCameraId = _gameplayCameraId;
			}
			ApprovePendingGeometry();
			int num2 = (xrActive ? 1 : 0);
			int num3 = (menuVisible ? 1 : 0);
			if (num != _provider)
			{
				InvalidateGeneration();
				_presenterAttempt = IntPtr.Zero;
			}
			int num4 = ((!_sceneSuspended && _gameplayActive && _unavailable == null && _captureFailure == null && num2 == 0) ? num : 0);
			int num5 = settings.FrameMultiplier.Value;
			if (num5 < 2)
			{
				num5 = 2;
			}
			if (num5 > 6)
			{
				num5 = 6;
			}
			int num6 = ((frameGenerationKind != FrameGenerationKind.Off) ? _providerMaximum[(int)frameGenerationKind] : 0);
			if (num6 > UpscalingModes.ProviderMultiplierLimit(frameGenerationKind))
			{
				num6 = UpscalingModes.ProviderMultiplierLimit(frameGenerationKind);
			}
			int num7 = ((num6 > 0) ? Math.Min(num5, num6) : 2);
			if (num7 != _effectiveMultiplier)
			{
				_effectiveMultiplier = num7;
				InvalidateGeneration();
			}
			if (num != _provider || num2 != _xr || num3 != _menu || num4 != _effectiveProvider || _generation != _configuredGeneration || num7 != _configuredMultiplier)
			{
				_provider = num;
				_xr = num2;
				_menu = num3;
				_effectiveProvider = num4;
				_configuredGeneration = _generation;
				_configuredMultiplier = num7;
				NativeFg.Config config = new NativeFg.Config
				{
					Abi = 7u,
					Size = (uint)NativeFg.ConfigSize,
					Provider = num4,
					Generation = _generation,
					PrimaryCameraId = _cameraId,
					PrimaryHistoryEpoch = _epoch,
					CaptureReady = (int)_captureReady,
					XrActive = num2,
					MenuVisible = num3,
					Multiplier = (uint)num7
				};
				NativeFg.Configure(ref config);
				_activityNeedsReset = true;
			}
			if (num != 0 && _gameplayActive && _unavailable == null && _captureFailure == null && num2 == 0 && !VrState.Active)
			{
				CreatePresenterIfReady();
			}
			NativeFg.Status status = default(NativeFg.Status);
			if (NativeFg.GetStatus(ref status) == 0)
			{
				_hasStatus = false;
				_lastRequested = num;
				_lastRequestedKind = frameGenerationKind;
				HudLine = UpscalingStatus.FrameGeneration("Unsupported", frameGenerationKind, 1, "status unavailable");
				return;
			}
			_hasStatus = true;
			_lastStatus = status;
			_lastRequested = num;
			_lastRequestedKind = frameGenerationKind;
			if (frameGenerationKind != FrameGenerationKind.Off && num4 != 0 && status.RequestedProvider == num4 && status.Generation == _generation && status.MaxMultiplier != 0)
			{
				int val = (int)Math.Min(status.MaxMultiplier, 6u);
				val = Math.Min(val, UpscalingModes.ProviderMultiplierLimit(frameGenerationKind));
				if (val >= 2 && val != _providerMaximum[(int)frameGenerationKind])
				{
					_providerMaximum[(int)frameGenerationKind] = val;
				}
			}
			if (status.RetirementCount != 0)
			{
				NativeFg.AckCaptures(NewestRetirement(in status));
			}
			if (_activityNeedsReset && status.Generation == _generation)
			{
				_activity.Reset(_generation, frameGenerationKind, status.GeneratedPresents);
				_activityNeedsReset = false;
			}
			int state = status.State;
			bool flag = (uint)(state - 8) <= 1u;
			if (flag && _nativeFault == null)
			{
				_nativeFaultUnsupported = status.State == 9;
				_nativeFault = (string.IsNullOrEmpty(status.ReasonText()) ? "the frame-generation provider reported a terminal failure" : status.ReasonText());
				_captureReady = 0u;
				_scope = false;
				_log("frame generation faulted: " + _nativeFault);
			}
			_activity.Observe(status.Generation, (FrameGenerationKind)status.ActiveProvider, status.State == 5, status.GeneratedPresents);
			NativeFg.SetPresenterVisible((_unavailable == null && _captureFailure == null && _gameplayActive && status.State == 5 && status.GeneratedPresents != 0 && num2 == 0 && num3 == 0 && _activity.Confirmed(_generation, frameGenerationKind)) ? 1 : 0);
			HudLine = Compose(status, frameGenerationKind, num3 != 0);
			LogDiagnostics(settings, in status, num);
		}

		internal int? SamplePresentedFps(double nowSeconds)
		{
			if (_xr != 0 || VrState.Active || _menu != 0 || _effectiveProvider == 0 || _unavailable != null || _captureFailure != null || _nativeFault != null || _sceneSuspended || !_gameplayActive || !TryGetStatus(out var status))
			{
				_presentedRate.Reset();
				return null;
			}
			bool flag = status.Generation != _generation || RestartFor(in status, _lastRequestedKind);
			if (!flag)
			{
				int state = status.State;
				bool flag2 = ((state == 0 || (uint)(state - 6) <= 3u) ? true : false);
				flag = flag2;
			}
			if (flag)
			{
				_presentedRate.Reset();
				return null;
			}
			if (!_activity.Confirmed(_generation, _lastRequestedKind))
			{
				_presentedRate.Reset();
				return null;
			}
			FrameGenerationKind provider = ((status.ActiveProvider != 0) ? ((FrameGenerationKind)status.ActiveProvider) : _lastRequestedKind);
			int multiplier = ((status.ActiveMultiplier >= 2) ? ((int)status.ActiveMultiplier) : Math.Max(2, _effectiveMultiplier));
			if (!_presentedRate.Observe(nowSeconds, status.Generation, provider, multiplier, status.RenderedPresents, status.GeneratedPresents, out var totalFps))
			{
				return null;
			}
			return totalFps;
		}

		internal void RefreshStatusLine(bool settingsOpen)
		{
			if (settingsOpen)
			{
				NativeFg.SetPresenterVisible(0);
			}
			if (!_hasStatus)
			{
				HudLine = ComposeUnavailable(_lastRequestedKind);
			}
			else
			{
				HudLine = Compose(_lastStatus, _lastRequestedKind, settingsOpen);
			}
		}

		internal void SuspendForScene()
		{
			_sceneSuspended = true;
			_captureReady = 0u;
			_scope = false;
			_presentedRate.Reset();
			NativeFg.SetPresenterVisible(0);
		}

		internal void ResumeAfterScene()
		{
			_sceneSuspended = false;
		}

		private void InvalidateGeneration(bool clearFaults = true)
		{
			if (clearFaults)
			{
				_nativeFault = null;
				_nativeFaultUnsupported = false;
				_captureFailure = null;
				_suspendedGeometry = null;
			}
			else
			{
				_suspendedGeometry = _approvedGeometry ?? _suspendedGeometry;
			}
			_generation++;
			_presentedRate.Reset();
			_captureReady = 0u;
			_previousValid = false;
			_scope = false;
			_approvedGeometry = null;
			Interlocked.Exchange(ref _pendingGeometry, null);
			_activityNeedsReset = true;
		}

		private void ApprovePendingGeometry()
		{
			CaptureGeometry captureGeometry = Interlocked.Exchange(ref _pendingGeometry, null);
			if (captureGeometry != null && _gameplayActive && captureGeometry.CameraId == _gameplayCameraId)
			{
				CaptureGeometry captureGeometry2 = _approvedGeometry ?? _suspendedGeometry;
				if (captureGeometry2 == null || !captureGeometry.SameExtent(captureGeometry2))
				{
					_generation++;
					_epoch++;
					_cameraId = captureGeometry.CameraId;
					_captureFailure = null;
					_nativeFault = null;
					_nativeFaultUnsupported = false;
					_captureReady = 0u;
					_previousValid = false;
					_scope = false;
					_activityNeedsReset = true;
					_log($"frame generation camera accepted: id={captureGeometry.CameraId} render={captureGeometry.RenderWidth}x{captureGeometry.RenderHeight} output={captureGeometry.OutputWidth}x{captureGeometry.OutputHeight} reversedDepth={captureGeometry.ReversedDepth} overlay={captureGeometry.RendersOverlay} generation={_generation} hook=[{CaptureHookStatus}].");
				}
				captureGeometry.Generation = _generation;
				captureGeometry.HistoryEpoch = _epoch;
				_approvedGeometry = captureGeometry;
				_suspendedGeometry = null;
			}
		}

		private void PollCaptureKey(ModSettings settings)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!settings.Diagnostics.Value || _xrProof)
			{
				return;
			}
			bool keyDown;
			try
			{
				KeyCode value = settings.FrameCaptureKey.Value;
				if ((int)value == 0)
				{
					return;
				}
				keyDown = Input.GetKeyDown(value);
				_captureKeyFailed = false;
			}
			catch (Exception ex)
			{
				if (!_captureKeyFailed)
				{
					_captureKeyFailed = true;
					_log("frame-generation capture key could not be read: " + ex.Message);
				}
				return;
			}
			if (keyDown)
			{
				if (!_gameplayActive)
				{
					_log("frame-generation capture ignored: not in gameplay.");
				}
				else
				{
					_log((NativeFg.RequestCapture(5u) == 1) ? "frame-generation capture armed: next 5 pairs." : "frame-generation capture refused: one is already in progress.");
				}
			}
		}

		private void LogPlayerRenderers()
		{
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				WorldManager instance = WorldManager.instance;
				PlayerCharacter localPlayerCharacter = WorldManager.localPlayerCharacter;
				if ((Object)(object)instance == (Object)null || (Object)(object)localPlayerCharacter == (Object)null || (Object)(object)((Component)localPlayerCharacter).gameObject == (Object)null)
				{
					return;
				}
				PlayerCameraReferences playerCameraReferences = instance.playerCameraReferences;
				Camera val = (((Object)(object)playerCameraReferences != (Object)null) ? playerCameraReferences.playerCamera : null);
				Camera val2 = (((Object)(object)playerCameraReferences != (Object)null) ? playerCameraReferences.playerUICamera : null);
				int num = (((Object)(object)val != (Object)null) ? val.cullingMask : 0);
				int num2 = (((Object)(object)val2 != (Object)null && ((Behaviour)val2).enabled) ? val2.cullingMask : 0);
				_log($"player cameras: main mask=0x{num:X8} ui={((num2 != 0) ? ("0x" + num2.ToString("X8")) : "none")}");
				Il2CppArrayBase<Renderer> componentsInChildren = ((Component)localPlayerCharacter).gameObject.GetComponentsInChildren<Renderer>(true);
				int num3 = 0;
				foreach (Renderer item in componentsInChildren)
				{
					if (num3 < 64)
					{
						num3++;
						GameObject gameObject = ((Component)item).gameObject;
						SkinnedMeshRenderer val3 = ((Il2CppObjectBase)item).TryCast<SkinnedMeshRenderer>();
						Material sharedMaterial = item.sharedMaterial;
						string value = (((Object)(object)sharedMaterial != (Object)null && (Object)(object)sharedMaterial.shader != (Object)null) ? ((Object)sharedMaterial.shader).name : "none");
						bool value2 = (Object)(object)sharedMaterial != (Object)null && sharedMaterial.FindPass("MotionVectors") >= 0;
						int layer = gameObject.layer;
						_log($"player renderer: path={RendererPath(((Component)item).transform, ((Component)localPlayerCharacter).transform)} type={(((Object)(object)val3 != (Object)null) ? "SkinnedMeshRenderer" : ((object)item).GetType().Name)} mesh={(Object)(object)((Il2CppObjectBase)item).TryCast<MeshRenderer>() != (Object)null} active={item.enabled && gameObject.activeInHierarchy} layer={layer} mv={item.motionVectorGenerationMode} skinnedMv={(((Object)(object)val3 != (Object)null) ? val3.skinnedMotionVectors.ToString() : "n/a")} shader={value} mvPass={value2} main={((num >> layer) & 1) != 0} ui={((num2 >> layer) & 1) != 0}");
						continue;
					}
					break;
				}
			}
			catch (Exception ex)
			{
				_log("player renderer inventory failed: " + ex.Message);
			}
		}

		private static string RendererPath(Transform transform, Transform root)
		{
			List<string> list = new List<string>();
			Transform val = transform;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}

		private void UpdateGameplayState()
		{
			bool flag = false;
			int num = 0;
			try
			{
				WorldManager instance = WorldManager.instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)((Component)instance).gameObject != (Object)null && ((Component)instance).gameObject.activeInHierarchy && instance.hasStarted && instance.localPlayerFullyReady)
				{
					PlayerCharacter localPlayerCharacter = WorldManager.localPlayerCharacter;
					PlayerCameraReferences playerCameraReferences = instance.playerCameraReferences;
					if ((Object)(object)localPlayerCharacter != (Object)null && (Object)(object)((Component)localPlayerCharacter).gameObject != (Object)null && ((Behaviour)localPlayerCharacter).isActiveAndEnabled && (Object)(object)playerCameraReferences != (Object)null && (Object)(object)((Component)playerCameraReferences).gameObject != (Object)null)
					{
						Camera playerCamera = playerCameraReferences.playerCamera;
						if ((Object)(object)playerCamera != (Object)null && ((Behaviour)playerCamera).isActiveAndEnabled)
						{
							num = ((Object)playerCamera).GetInstanceID();
							flag = num != 0;
						}
					}
				}
			}
			catch (Exception ex)
			{
				flag = false;
				num = 0;
				if (!_gameplayReadFailed)
				{
					_gameplayReadFailed = true;
					_log("frame generation cannot read the game's gameplay state; generation stays suspended: " + ex.Message);
				}
			}
			if (flag)
			{
				_gameplayReadFailed = false;
			}
			if (flag != _gameplayActive || num != _gameplayCameraId)
			{
				_gameplayActive = flag;
				_gameplayCameraId = num;
				InvalidateGeneration(clearFaults: false);
				NativeFg.SetPresenterVisible(0);
				_log(flag ? $"frame generation gameplay camera adopted: id={num}; capture re-armed." : "frame generation suspended: waiting for gameplay.");
			}
		}

		private void LogCamera(Camera camera, string message)
		{
			string item = ((Object)camera).GetInstanceID() + "|" + message;
			if (_cameraLog.Add(item))
			{
				_log($"frame generation camera {((Object)camera).GetInstanceID()}: {message} [hook: {CaptureHookStatus}].");
				if (_cameraLog.Count > 32)
				{
					_cameraLog.Clear();
				}
			}
		}

		private void LogDiagnostics(ModSettings settings, in NativeFg.Status status, int requested)
		{
			if (!settings.Diagnostics.Value)
			{
				_diagnosticWindowStart = 0f;
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (_diagnosticWindowStart <= 0f)
			{
				_diagnosticWindowStart = realtimeSinceStartup;
			}
			string text = status.ReasonText();
			if (requested != _loggedProvider || status.Generation != _loggedGeneration || status.State != _loggedState || !string.Equals(text, _loggedReason, StringComparison.Ordinal))
			{
				_loggedProvider = requested;
				_loggedGeneration = status.Generation;
				_loggedState = status.State;
				_loggedReason = text;
				_log($"FG status: requested={requested} active={status.ActiveProvider} generation={status.Generation} state={status.State} rendered={status.RenderedPresents} generated={status.GeneratedPresents} result=0x{status.LastResult:x8} reason={text}");
			}
			if (!(realtimeSinceStartup - _diagnosticWindowStart < 10f))
			{
				_diagnosticWindowStart = realtimeSinceStartup;
				_log($"FG summary: rendered={status.RenderedPresents} generated={status.GeneratedPresents} state={status.State} provider={requested} generation={status.Generation}.");
			}
		}

		private void CreatePresenterIfReady()
		{
			IntPtr gameWindow = NativeFg.GetGameWindow();
			if (!(gameWindow == IntPtr.Zero) && !(gameWindow == _presenterParent) && !(gameWindow == _presenterAttempt))
			{
				_presenterAttempt = gameWindow;
				if (NativeFg.CreatePresenterWindow(gameWindow) != 0)
				{
					_presenterParent = gameWindow;
					_log("frame-generation presenter window created on the game window's thread.");
				}
				else
				{
					ReportCaptureFailure("frame-generation presenter window could not be created");
				}
			}
		}

		internal void CaptureBegin(UniversalRenderer renderer)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			_scope = false;
			_scopeRecorded = false;
			_scopeGeometry = null;
			if (_renderEvent == IntPtr.Zero || _unavailable != null || _provider == int.MinValue || _provider == 0 || _xr != 0 || _menu != 0 || VrState.Active || !_gameplayActive)
			{
				return;
			}
			ContextContainer frameData = ((ScriptableRenderer)renderer).frameData;
			if (frameData == null)
			{
				return;
			}
			UniversalCameraData val;
			try
			{
				val = frameData.Get<UniversalCameraData>();
			}
			catch
			{
				return;
			}
			Camera camera = val.camera;
			if ((Object)(object)camera == (Object)null)
			{
				return;
			}
			if (!Eligible(val, out string reason))
			{
				LogCamera(camera, reason);
				return;
			}
			CaptureGeometry captureGeometry = Snapshot(val);
			if (captureGeometry == null)
			{
				LogCamera(camera, "the render or output extent is not positive");
				return;
			}
			CaptureGeometry approvedGeometry = _approvedGeometry;
			if (approvedGeometry == null || !captureGeometry.SameExtent(approvedGeometry))
			{
				Interlocked.Exchange(ref _pendingGeometry, captureGeometry);
			}
			else if (_captureFailure == null && _nativeFault == null)
			{
				_scopeCamera = val;
				_scopeJitter = val.m_JitterMatrix;
				_scopeGeometry = approvedGeometry;
				_scopeGeneration = approvedGeometry.Generation;
				_scopeEpoch = approvedGeometry.HistoryEpoch;
				FrameGenerationKind lastRequestedKind = _lastRequestedKind;
				bool scopeNeedsHudless = (((uint)(lastRequestedKind - 1) <= 1u || (uint)(lastRequestedKind - 4) <= 1u) ? true : false);
				_scopeNeedsHudless = scopeNeedsHudless;
				_scope = true;
			}
		}

		private bool Eligible(UniversalCameraData cameraData, out string reason)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Invalid comparison between Unknown and I4
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			reason = "";
			Camera camera = cameraData.camera;
			try
			{
				UniversalAdditionalCameraData component = ((Component)camera).GetComponent<UniversalAdditionalCameraData>();
				FrameGenerationCameraInput frameGenerationCameraInput = new FrameGenerationCameraInput
				{
					Live = ((Behaviour)camera).isActiveAndEnabled,
					GameCamera = ((int)cameraData.cameraType == 1),
					GameplayActive = (_gameplayActive && ((Object)camera).GetInstanceID() == _gameplayCameraId),
					Preview = cameraData.isPreviewCamera,
					SceneView = cameraData.isSceneViewCamera,
					BaseCamera = ((int)cameraData.renderType == 0),
					CameraStackCount = (((Object)(object)component != (Object)null) ? component.cameraStack.Count : 0),
					HasTargetTexture = ((Object)(object)cameraData.targetTexture != (Object)null),
					ResolveToScreen = cameraData.resolveToScreen,
					LastBaseCamera = cameraData.isLastBaseCamera,
					HdrDisplayOutput = cameraData.isHDROutputActive,
					XrEnabled = (cameraData.xr != null && cameraData.xr.enabled)
				};
				RenderTextureDescriptor cameraTargetDescriptor = cameraData.cameraTargetDescriptor;
				frameGenerationCameraInput.RenderWidth = ((RenderTextureDescriptor)(ref cameraTargetDescriptor)).width;
				cameraTargetDescriptor = cameraData.cameraTargetDescriptor;
				frameGenerationCameraInput.RenderHeight = ((RenderTextureDescriptor)(ref cameraTargetDescriptor)).height;
				frameGenerationCameraInput.OutputWidth = cameraData.pixelWidth;
				frameGenerationCameraInput.OutputHeight = cameraData.pixelHeight;
				FrameGenerationCameraInput camera2 = frameGenerationCameraInput;
				return FrameGenerationCameraPolicy.Accept(in camera2, out reason);
			}
			catch (Exception ex)
			{
				reason = "the camera data could not be read: " + ex.Message;
				return false;
			}
		}

		private CaptureGeometry? Snapshot(UniversalCameraData cameraData)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				RenderTextureDescriptor cameraTargetDescriptor = cameraData.cameraTargetDescriptor;
				int pixelWidth = cameraData.pixelWidth;
				int pixelHeight = cameraData.pixelHeight;
				if (((RenderTextureDescriptor)(ref cameraTargetDescriptor)).width <= 0 || ((RenderTextureDescriptor)(ref cameraTargetDescriptor)).height <= 0 || pixelWidth <= 0 || pixelHeight <= 0)
				{
					return null;
				}
				return new CaptureGeometry
				{
					CameraId = ((Object)cameraData.camera).GetInstanceID(),
					RenderWidth = ((RenderTextureDescriptor)(ref cameraTargetDescriptor)).width,
					RenderHeight = ((RenderTextureDescriptor)(ref cameraTargetDescriptor)).height,
					OutputWidth = pixelWidth,
					OutputHeight = pixelHeight,
					ReversedDepth = SystemInfo.usesReversedZBuffer,
					RendersOverlay = cameraData.rendersOverlayUI
				};
			}
			catch
			{
				return null;
			}
		}

		internal void RequestCaptureInputs(ref RenderPassInputSummary summary)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			//IL_001e: 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)
			if (_scope)
			{
				if (!summary.requiresDepthTexture)
				{
					summary.requiresDepthTexture = true;
					summary.requiresDepthTextureEarliestEvent = (RenderPassEvent)550;
				}
				else if ((int)summary.requiresDepthTextureEarliestEvent > 550)
				{
					summary.requiresDepthTextureEarliestEvent = (RenderPassEvent)550;
				}
				summary.requiresMotionVectors = true;
			}
		}

		internal void CaptureAbort()
		{
			_scope = false;
		}

		internal void SetReconstructionActive(bool active)
		{
			_reconstructionActive = active;
		}

		internal void CaptureBeforeUi(RenderGraph renderGraph, ContextContainer frameData, TextureHandle color)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!_scope || !_scopeNeedsHudless || _scopeRecorded)
			{
				return;
			}
			UniversalCameraData scopeCamera = _scopeCamera;
			if (scopeCamera == null || frameData == null || !((TextureHandle)(ref color)).IsValid() || !_pass.HasFreeLease)
			{
				return;
			}
			try
			{
				if (Record(renderGraph, frameData, scopeCamera, color, HudlessRequirement.Overlay))
				{
					_scopeRecorded = true;
				}
				else
				{
					LogCamera(scopeCamera.camera, "the pre-overlay capture was not recorded; the next eligible graph retries");
				}
			}
			catch (Exception ex)
			{
				LogCamera(scopeCamera.camera, "the pre-overlay capture failed (" + ex.Message + "); the next eligible graph retries");
			}
		}

		internal void CaptureAfterPostProcessing(RenderGraph renderGraph, ContextContainer frameData, int cameraId, TextureHandle color)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			if (!_scope || !_scopeNeedsHudless || _scopeRecorded)
			{
				return;
			}
			CaptureGeometry scopeGeometry = _scopeGeometry;
			if (scopeGeometry == null)
			{
				return;
			}
			if (scopeGeometry.CameraId != cameraId)
			{
				UniversalCameraData? scopeCamera = _scopeCamera;
				Camera val = ((scopeCamera != null) ? scopeCamera.camera : null);
				if ((Object)(object)val != (Object)null)
				{
					LogCamera(val, $"the reconstruction published camera {cameraId}, not this camera; " + "frame generation waits for its own camera's upscaled image");
				}
			}
			else if (((TextureHandle)(ref color)).IsValid() && _pass.HasFreeLease)
			{
				UniversalCameraData scopeCamera2 = _scopeCamera;
				if (scopeCamera2 != null && frameData != null && Record(renderGraph, frameData, scopeCamera2, color, HudlessRequirement.CameraColor))
				{
					_scopeRecorded = true;
				}
			}
		}

		internal void CaptureEnd(UniversalRenderer renderer, RenderGraph renderGraph)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if (!_scope)
			{
				return;
			}
			_scope = false;
			if (_renderEvent == IntPtr.Zero || _unavailable != null || _captureFailure != null)
			{
				return;
			}
			UniversalCameraData scopeCamera = _scopeCamera;
			CaptureGeometry scopeGeometry = _scopeGeometry;
			if (scopeCamera == null || scopeGeometry == null)
			{
				return;
			}
			ContextContainer frameData = ((ScriptableRenderer)renderer).frameData;
			if (frameData == null || _scopeRecorded)
			{
				return;
			}
			if (_scopeNeedsHudless)
			{
				if (_reconstructionActive)
				{
					LogCamera(scopeCamera.camera, "this graph recorded no pre-overlay capture; the next eligible graph retries");
				}
				else
				{
					ReportCaptureFailure("the frame-generation HUD-less image is unavailable; the upscaler must be producing frames");
				}
			}
			else if (_pass.HasFreeLease && !Record(renderGraph, frameData, scopeCamera, TextureHandle.nullHandle, HudlessRequirement.None))
			{
				LogCamera(scopeCamera.camera, "the capture was not recorded for this graph; the next graph retries");
			}
		}

		private unsafe bool Record(RenderGraph renderGraph, ContextContainer frameData, UniversalCameraData cameraData, TextureHandle color, HudlessRequirement hudless)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_030f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0376: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			CaptureGeometry scopeGeometry = _scopeGeometry;
			if (scopeGeometry == null)
			{
				return false;
			}
			UniversalResourceData val;
			try
			{
				val = frameData.Get<UniversalResourceData>();
			}
			catch
			{
				ReportCaptureFailure("the URP resource data is unavailable for frame generation");
				return false;
			}
			TextureHandle cameraDepthTexture = val.cameraDepthTexture;
			TextureHandle motionVectorColor = val.motionVectorColor;
			if (!((TextureHandle)(ref cameraDepthTexture)).IsValid() || !((TextureHandle)(ref motionVectorColor)).IsValid())
			{
				ReportCaptureFailure("frame generation needs URP depth and motion vectors; this camera did not provide them");
				return false;
			}
			TextureDesc descriptor = ((TextureHandle)(ref cameraDepthTexture)).GetDescriptor(renderGraph);
			TextureDesc descriptor2 = ((TextureHandle)(ref motionVectorColor)).GetDescriptor(renderGraph);
			if (descriptor.width < scopeGeometry.RenderWidth || descriptor.height < scopeGeometry.RenderHeight)
			{
				ReportCaptureFailure("the URP depth texture does not contain the active render extent");
				return false;
			}
			int cameraId = scopeGeometry.CameraId;
			int historyEpoch = scopeGeometry.HistoryEpoch;
			Matrix4x4 viewMatrix = cameraData.GetViewMatrix(0);
			Matrix4x4 gPUProjectionMatrix = GL.GetGPUProjectionMatrix(cameraData.GetProjectionMatrixNoJitter(0), false);
			bool flag = !_previousValid || _previousCameraId != cameraId || _previousEpoch != historyEpoch;
			NativeFg.Frame frame = new NativeFg.Frame
			{
				Abi = 7u,
				Size = (uint)NativeFg.FrameSize,
				Generation = _scopeGeneration,
				CameraId = cameraId,
				HistoryEpoch = historyEpoch,
				FrameIndex = Time.frameCount,
				RenderWidth = scopeGeometry.RenderWidth,
				RenderHeight = scopeGeometry.RenderHeight,
				OutputWidth = scopeGeometry.OutputWidth,
				OutputHeight = scopeGeometry.OutputHeight,
				MotionWidth = descriptor2.width,
				MotionHeight = descriptor2.height,
				PresentId = _presentId,
				Flags = ((scopeGeometry.ReversedDepth ? 1u : 0u) | (uint)(flag ? 2 : 0)),
				JitterX = _scopeJitter.m03 * (float)scopeGeometry.RenderWidth * 0.5f,
				JitterY = (0f - _scopeJitter.m13) * (float)scopeGeometry.RenderHeight * 0.5f,
				DeltaMilliseconds = Time.unscaledDeltaTime * 1000f,
				CameraNear = cameraData.camera.nearClipPlane,
				CameraFar = cameraData.camera.farClipPlane,
				VerticalFovRadians = VerticalFov(gPUProjectionMatrix),
				Aspect = cameraData.camera.aspect
			};
			Transform transform = ((Component)cameraData.camera).transform;
			WriteVector(frame.CameraPosition, transform.position);
			WriteVector(frame.CameraUp, transform.up);
			WriteVector(frame.CameraRight, transform.right);
			WriteVector(frame.CameraForward, transform.forward);
			WriteRowMajor(frame.CurrentView, viewMatrix);
			WriteRowMajor(frame.CurrentProjection, gPUProjectionMatrix);
			if (flag)
			{
				WriteRowMajor(frame.PreviousView, viewMatrix);
				WriteRowMajor(frame.PreviousProjection, gPUProjectionMatrix);
			}
			else
			{
				WriteRowMajor(frame.PreviousView, _previousView);
				WriteRowMajor(frame.PreviousProjection, _previousProjection);
			}
			bool boundHudless = hudless != HudlessRequirement.None && (((TextureHandle)(ref color)).IsBuiltin() || color == val.backBufferColor);
			if (!_pass.Record(renderGraph, color, cameraDepthTexture, motionVectorColor, frame, _renderEvent, hudless, boundHudless))
			{
				return false;
			}
			_previousView = viewMatrix;
			_previousProjection = gPUProjectionMatrix;
			_previousCameraId = cameraId;
			_previousEpoch = historyEpoch;
			_previousValid = true;
			_captureReady = 1u;
			return true;
		}

		private static float VerticalFov(Matrix4x4 projection)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Abs(projection.m11);
			if (!(num > 1E-06f))
			{
				return (float)Math.PI / 3f;
			}
			return 2f * Mathf.Atan(1f / num);
		}

		private unsafe static void WriteVector(float* destination, Vector3 value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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)
			*destination = value.x;
			destination[1] = value.y;
			destination[2] = value.z;
		}

		private unsafe static void WriteRowMajor(float* destination, Matrix4x4 matrix)
		{
			for (int i = 0; i < 4; i++)
			{
				for (int j = 0; j < 4; j++)
				{
					destination[i * 4 + j] = ((Matrix4x4)(ref matrix))[j, i];
				}
			}
		}

		private static uint NewestRetirement(in NativeFg.Status status)
		{
			uint num = 0u;
			if (status.Retirement0.Sequence > num)
			{
				num = status.Retirement0.Sequence;
			}
			if (status.Retirement1.Sequence > num)
			{
				num = status.Retirement1.Sequence;
			}
			if (status.Retirement2.Sequence > num)
			{
				num = status.Retirement2.Sequence;
			}
			if (status.Retirement3.Sequence > num)
			{
				num = status.Retirement3.Sequence;
			}
			if (status.Retirement4.Sequence > num)
			{
				num = status.Retirement4.Sequence;
			}
			if (status.Retirement5.Sequence > num)
			{
				num = status.Retirement5.Sequence;
			}
			if (status.Retirement6.Sequence > num)
			{
				num = status.Retirement6.Sequence;
			}
			if (status.Retirement7.Sequence > num)
			{
				num = status.Retirement7.Sequence;
			}
			return num;
		}

		private string ComposeUnavailable(FrameGenerationKind requested)
		{
			if (_xr != 0 || VrState.Active)
			{
				return UpscalingStatus.FrameGeneration("Disabled in VR", FrameGenerationKind.Off, 1, "");
			}
			if (requested == FrameGenerationKind.Off)
			{
				return UpscalingStatus.FrameGeneration("Off", FrameGenerationKind.Off, 1, "");
			}
			return UpscalingStatus.FrameGeneration("Unsupported", requested, Math.Max(2, _effectiveMultiplier), _unavailable ?? "the frame-generation transport is unavailable");
		}

		private string Compose(NativeFg.Status status, FrameGenerationKind requested, bool settingsOpen)
		{
			if (_xr != 0 || VrState.Active)
			{
				return UpscalingStatus.FrameGeneration("Disabled in VR", FrameGenerationKind.Off, 1, "");
			}
			if (requested == FrameGenerationKind.Off)
			{
				return UpscalingStatus.FrameGeneration("Off", FrameGenerationKind.Off, 1, "");
			}
			int num = Math.Max(2, _effectiveMultiplier);
			if (RestartFor(in status, requested))
			{
				return UpscalingStatus.FrameGeneration("Restart required", requested, num, "restart the game to switch between ANR and other frame-generation providers");
			}
			if (_sceneSuspended)
			{
				return UpscalingStatus.FrameGeneration("Suspended", requested, num, "waiting for a new camera");
			}
			if (_unavailable != null)
			{
				return UpscalingStatus.FrameGeneration("Unsupported", requested, num, _unavailable);
			}
			if (_captureFailure != null)
			{
				return UpscalingStatus.FrameGeneration("Faulted", requested, num, _captureFailure);
			}
			if (_nativeFault != null)
			{
				return UpscalingStatus.FrameGeneration(_nativeFaultUnsupported ? "Unsupported" : "Faulted", requested, num, _nativeFault);
			}
			if (!_gameplayActive)
			{
				return UpscalingStatus.FrameGeneration("Suspended", requested, num, "waiting for gameplay");
			}
			string text = status.ReasonText();
			bool flag = _activity.Confirmed(_generation, requested);
			FrameGenerationKind provider = (flag ? _activity.ConfirmedProvider : ((status.ActiveProvider != 0) ? ((FrameGenerationKind)status.ActiveProvider) : requested));
			int multiplier = ((status.ActiveMultiplier >= 1) ? ((int)status.ActiveMultiplier) : num);
			if (status.State == 8)
			{
				return UpscalingStatus.FrameGeneration("Faulted", provider, multiplier, text);
			}
			if (status.State == 9)
			{
				return UpscalingStatus.FrameGeneration("Unsupported", provider, multiplier, text);
			}
			if (settingsOpen)
			{
				return UpscalingStatus.FrameGeneration("Suspended", provider, multiplier, "settings open");
			}
			switch (status.State)
			{
			case 5:
				if (flag)
				{
					return UpscalingStatus.FrameGeneration("Active", provider, multiplier, "");
				}
				return UpscalingStatus.FrameGeneration("Waiting", requested, num, "waiting for a generated frame");
			case 6:
				return UpscalingStatus.FrameGeneration("Suspended", provider, multiplier, (text.Length > 0) ? text : "suspended");
			case 8:
				return UpscalingStatus.FrameGeneration("Faulted", provider, multiplier, text);
			case 9:
				return UpscalingStatus.FrameGeneration("Unsupported", provider, multiplier, text);
			case 0:
				return UpscalingStatus.FrameGeneration("Off", FrameGenerationKind.Off, 1, "");
			default:
				return UpscalingStatus.FrameGeneration("Waiting", provider, multiplier, text);
			}
		}
	}
	internal enum HudlessRequirement
	{
		None,
		Overlay,
		CameraColor
	}
	internal sealed class FrameGenerationPass
	{
		private sealed class Lease
		{
			internal readonly int Index;

			internal BaseRenderFunc<DoFGaussianPassData, UnsafeGraphContext>? Callback;

			internal NativeFg.Frame Frame;

			internal IntPtr RenderEvent;

			internal int Generation;

			internal int LeasedFrame;

			internal bool Busy;

			internal HudlessRequirement Hudless;

			internal bool BoundHudless;

			internal Action<string>? Failure;

			private readonly FrameGenerationPass _owner;

			internal Lease(FrameGenerationPass owner, int index)
			{
				_owner = owner;
				Index = index;
			}

			internal BaseRenderFunc<DoFGaussianPassData, UnsafeGraphContext> EnsureCallback()
			{
				return Callback ?? (Callback = BaseRenderFunc<DoFGaussianPassData, UnsafeGraphContext>.op_Implicit((Action<DoFGaussianPassData, UnsafeGraphContext>)Execute));
			}

			private void Execute(DoFGaussianPassData data, UnsafeGraphContext context)
			{
				//IL_0060: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
				NativeFg.Frame frame;
				IntPtr renderEvent;
				HudlessRequirement hudless;
				bool boundHudless;
				lock (_owner._gate)
				{
					if (!Busy || data.downsample != Generation)
					{
						return;
					}
					frame = Frame;
					renderEvent = RenderEvent;
					hudless = Hudless;
					boundHudless = BoundHudless;
				}
				try
				{
					IntPtr intPtr = Resolve(data.depthTexture);
					IntPtr intPtr2 = Resolve(data.halfCoCTexture);
					if (intPtr == IntPtr.Zero || intPtr2 == IntPtr.Zero)
					{
						Failure?.Invoke("frame generation needs URP depth and motion vectors; this camera did not provide them.");
						return;
					}
					if (hudless != HudlessRequirement.None)
					{
						frame.Hudless = (boundHudless ? IntPtr.Zero : Resolve(data.sourceTexture));
						if (boundHudless)
						{
							frame.Flags |= 4u;
						}
						else if (frame.Hudless == IntPtr.Zero)
						{
							Failure?.Invoke("pre-overlay colour was not captured");
							return;
						}
					}
					frame.Depth = intPtr;
					frame.Motion = intPtr2;
					CommandBuffer nativeCommandBuffer = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
					IntPtr intPtr3 = NativeFg.SubmitFrame(ref frame);
					if (intPtr3 == IntPtr.Zero)
					{
						NativeFg.Status status = default(NativeFg.Status);
						bool flag = NativeFg.GetStatus(ref status) != 0;
						if (flag)
						{
							int state = status.State;
							bool flag2 = (uint)(state - 8) <= 1u;
							flag = flag2;
						}
						if (flag)
						{
							Failure?.Invoke($"the native frame-generation bridge rejected camera {frame.CameraId}: " + status.ReasonText());
						}
					}
					else
					{
						if (boundHudless)
						{
							context.cmd.SetRenderTarget(TextureHandle.op_Implicit(data.sourceTexture), (RenderBufferLoadAction)0, (RenderBufferStoreAction)0);
						}
						nativeCommandBuffer.IssuePluginEventAndData(renderEvent, 2, intPtr3);
					}
				}
				catch (Exception ex)
				{
					Failure?.Invoke("frame-generation capture failed: " + ex.Message);
				}
				finally