Decompiled source of ForgeFrameGen v1.0.1

patchers/ForgeFrameGen.Preloader.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
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.Logging;
using BepInEx.Preloader.Core.Patching;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ForgeFrameGen.Preloader")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ForgeFrameGen.Preloader")]
[assembly: AssemblyTitle("ForgeFrameGen.Preloader")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.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 ForgeFrameGen
{
	[PatcherPluginInfo("NAinfini.ForgeFrameGen.Preloader", "Forge FrameGen preloader", "1.0.0")]
	public sealed class Preloader : BasePatcher
	{
		public unsafe override void Initialize()
		{
			ManualLogSource val = Logger.CreateLogSource("ForgeFrameGen.Preloader");
			try
			{
				List<string> list = Directory.EnumerateFiles(Paths.PluginPath, "ForgeFrameGen.Native.dll", SearchOption.AllDirectories).ToList();
				if (list.Count != 1)
				{
					val.LogError((object)(((list.Count == 0) ? "No " : "More than one ") + "ForgeFrameGen.Native.dll under " + Paths.PluginPath + "; graphics hooks not installed, frame generation is not available. Reinstall Forge FrameGen."));
					return;
				}
				IntPtr intPtr = NativeLibrary.Load(list[0]);
				((delegate* unmanaged<int, void>)(void*)NativeLibrary.GetExport(intPtr, "ForgeFrameGen_SetFrameGenerationPreference"))(PickedFrameGeneration(val));
				((delegate* unmanaged<int, int>)(void*)NativeLibrary.GetExport(intPtr, "ForgeFrameGen_InstallGraphicsHooks"))(1);
				WatchForPlugin(intPtr, val);
			}
			catch (Exception ex)
			{
				val.LogError((object)("Installing the graphics hooks failed; frame generation is not available: " + ex));
			}
		}

		private unsafe static void WatchForPlugin(IntPtr native, ManualLogSource log)
		{
			delegate* unmanaged<int> parked = (delegate* unmanaged<int>)(void*)NativeLibrary.GetExport(native, "ForgeFrameGen_Parked");
			delegate* unmanaged<byte*, int, int*, int> pop = (delegate* unmanaged<byte*, int, int*, int>)(void*)NativeLibrary.GetExport(native, "ForgeFrameGen_PopBridgeMessage");
			delegate* unmanaged<int> state = (delegate* unmanaged<int>)(void*)NativeLibrary.GetExport(native, "ForgeFrameGen_PresentState");
			delegate* unmanaged<int*, int*, int*, long*, void> counts = (delegate* unmanaged<int*, int*, int*, long*, void>)(void*)NativeLibrary.GetExport(native, "ForgeFrameGen_GraphicsCounts");
			delegate* unmanaged<int> stage = (delegate* unmanaged<int>)(void*)NativeLibrary.GetExport(native, "ForgeFrameGen_PresentStage");
			Thread thread = new Thread((ThreadStart)delegate
			{
				bool flag = false;
				bool flag2 = false;
				long num = -1L;
				int num2 = 0;
				long num4 = default(long);
				while (state() != -1)
				{
					Thread.Sleep(1000);
					int num3 = parked();
					if (num3 == 1 && !flag)
					{
						flag = true;
						log.LogWarning((object)("The Forge FrameGen plugin did not load (see the errors above): frame generation is off and the game's frames pass through unchanged (" + Flush() + " developer lines of the bridge not written)."));
					}
					if (!(num3 == 0 || flag2))
					{
						counts(null, null, null, &num4);
						if (num4 > 0)
						{
							num2 = ((num4 == num) ? (num2 + 1) : 0);
							num = num4;
							if (num2 >= 10)
							{
								flag2 = true;
								string text = stage() switch
								{
									1 => "waiting for the bridge's D3D12 queue to finish a frame", 
									2 => "handing frame generation its inputs", 
									3 => "inside the display swap chain's Present", 
									4 => "resizing the swap chain", 
									5 => "moving the display to another frame generation", 
									6 => "handing the window back to the game's own swap chain", 
									_ => "not in the bridge", 
								};
								Flush();
								log.LogWarning((object)("No frame has gone through the Forge FrameGen present bridge for 10 seconds (" + num4 + " frames so far, present bridge state " + state() + "; the game's render thread is " + text + "). If the game froze, send this log; removing Forge FrameGen gives the game its own rendering back."));
							}
						}
					}
				}
			});
			thread.IsBackground = true;
			thread.Name = "ForgeFrameGen.Preloader";
			thread.Start();
			unsafe int Flush()
			{
				byte* ptr = stackalloc byte[1024];
				int num = 0;
				int byteCount;
				int num2 = default(int);
				while ((byteCount = pop(ptr, 1024, &num2)) >= 0)
				{
					if (num2 == 0)
					{
						num++;
					}
					else
					{
						log.LogWarning((object)Encoding.UTF8.GetString(ptr, byteCount));
					}
				}
				return num;
			}
		}

		private static int PickedFrameGeneration(ManualLogSource log)
		{
			string text = Path.Combine(Paths.ConfigPath, "NAinfini.ForgeFrameGen.cfg");
			if (!File.Exists(text))
			{
				return 0;
			}
			string text2 = "";
			foreach (string item in File.ReadLines(text))
			{
				string text3 = item.Trim();
				if (text3.StartsWith('[') && text3.EndsWith(']'))
				{
					string text4 = text3;
					text2 = text4.Substring(1, text4.Length - 1 - 1).Trim();
				}
				else
				{
					if (!(text2 == "Frame Generation") || !text3.StartsWith("Method"))
					{
						continue;
					}
					int num = text3.IndexOf('=');
					if (num > 0 && text3.Substring(0, num).Trim() == "Method")
					{
						string text5 = text3.Substring(num + 1).Trim();
						bool flag;
						switch (text5)
						{
						case "FSR":
							return 2;
						case "DLSS":
							return 1;
						case "Auto":
						case "Off":
							flag = true;
							break;
						default:
							flag = false;
							break;
						}
						if (!flag)
						{
							log.LogWarning((object)("Method = " + text5 + " in " + text + " is not Off, Auto, DLSS or FSR; frame generation picks as for Auto."));
						}
						return 0;
					}
				}
			}
			return 0;
		}
	}
	internal static class PackageFiles
	{
		internal const string NativeFile = "ForgeFrameGen.Native.dll";

		internal const string PluginId = "NAinfini.ForgeFrameGen";
	}
}

plugins/ForgeFrameGen/ForgeFrameGen.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Agents;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using Enemies;
using ForgeCore;
using ForgeUI;
using ForgeVisual;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using Player;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ForgeFrameGen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ForgeFrameGen")]
[assembly: AssemblyTitle("ForgeFrameGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.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 ForgeFrameGen
{
	internal static class PackageFiles
	{
		internal const string NativeFile = "ForgeFrameGen.Native.dll";

		internal const string PluginId = "NAinfini.ForgeFrameGen";
	}
	[BepInPlugin("NAinfini.ForgeFrameGen", "Forge FrameGen", "1.0.1")]
	[BepInDependency("NAinfini.ForgeCore", ">=1.0.4")]
	internal sealed class Plugin : BasePlugin
	{
		internal const string Id = "NAinfini.ForgeFrameGen";

		internal const string DisplayName = "Forge FrameGen";

		internal const string Version = "1.0.1";

		internal const string NativeFile = "ForgeFrameGen.Native.dll";

		internal const string DlssLibrary = "nvngx_dlss.dll";

		internal const string FsrLoader = "amd_fidelityfx_loader_dx12.dll";

		private const string InSettings = " Also in the game's settings (Video, Advanced Graphics), where a change applies at once.";

		internal static readonly int[] FrameLimits = new int[11]
		{
			0, 30, 40, 50, 60, 72, 90, 120, 144, 165,
			240
		};

		internal static ConfigEntry<UpscalerMethod> Upscaler = null;

		internal static ConfigEntry<DlssMode> Mode = null;

		internal static ConfigEntry<DlssPreset> Preset = null;

		internal static ConfigEntry<DlssExposure> Exposure = null;

		internal static ConfigEntry<FrameGenerationMethod> FrameGeneration = null;

		internal static ConfigEntry<bool> HudInGeneratedFrames = null;

		internal static ConfigEntry<ReflexMode> Reflex = null;

		internal static ConfigEntry<int> FrameLimit = null;

		internal static ModLog Logger { get; private set; } = null;

		internal static ManualLogSource Info { get; private set; } = null;

		internal static bool UpscalerOn => Upscaler.Value != UpscalerMethod.Off;

		internal static bool FrameGenerationOn => FrameGeneration.Value != FrameGenerationMethod.Off;

		internal static string Folder { get; private set; } = "";

		public override void Load()
		{
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Expected O, but got Unknown
			Logger = Log.For("NAinfini.ForgeFrameGen");
			Info = ((BasePlugin)this).Log;
			Folder = Path.GetDirectoryName(typeof(Plugin).Assembly.Location) ?? "";
			bool num = StoredModeOff(((BasePlugin)this).Config.ConfigFilePath);
			Upscaler = ((BasePlugin)this).Config.Bind<UpscalerMethod>("DLSS", "Upscaler", UpscalerMethod.Auto, "Which upscaler runs the mode below. Auto: NVIDIA® DLSS on an NVIDIA RTX card, AMD FSR™ on every other card (FSR 4 on the AMD Radeon cards AMD lists for it, RX 7000 and 9000 series; FSR 3.1 elsewhere). DLSS or FSR: that one; when this card cannot run it, Auto is used and the settings row says so. Off: no upscaler and no frame generation; the game's own anti-aliasing runs. Frame generation has its own setting. Also in the game's settings (Video, Advanced Graphics), where a change applies at once. This mod is not an NVIDIA or AMD product.");
			Mode = ((BasePlugin)this).Config.Bind<DlssMode>("DLSS", "Mode", DlssMode.DLAA, "The upscaling mode. DLAA: anti-aliasing at your screen resolution (FSR's Native AA), in place of the game's own anti-aliasing. Quality, Balanced, Performance, UltraPerformance: the world renders at a lower resolution (about 67%, 58%, 50% and 33% of the screen's width and height) and the upscaler brings it up to the screen's; the HUD stays at full resolution. Not used while the upscaler is Off. Also in the game's settings (Video, Advanced Graphics), where a change applies at once. DLSS needs an NVIDIA RTX graphics card: RTX 40 and 50 series supported, RTX 20 and 30 series untested. FSR runs on any DirectX 12 card.");
			Preset = ((BasePlugin)this).Config.Bind<DlssPreset>("DLSS", "Model", DlssPreset.Auto, "The DLSS model. Auto: model M, and model L in the Ultra Performance mode. K, M, L: that model in every mode. K is the lightest on the graphics card. M and L give a sharper, steadier picture with less ghosting and cost more, L the most; they run best on RTX 40 and 50 series cards. Also in the game's settings (Video, Advanced Graphics), where a change applies at once.");
			Exposure = ((BasePlugin)this).Config.Bind<DlssExposure>("DLSS", "Exposure", DlssExposure.Auto, "How the upscaler learns how bright the picture is. Auto: it measures it. Fixed: it is told the picture is already exposed; try it if dark scenes ghost or flicker with Auto. By NVIDIA's guide only DLSS model K takes it; M and L measure the picture themselves. Also in the game's settings (Video, Advanced Graphics), where a change applies at once.");
			FrameGeneration = ((BasePlugin)this).Config.Bind<FrameGenerationMethod>("Frame Generation", "Method", FrameGenerationMethod.Off, "A generated frame between every two rendered frames. Off; Auto: NVIDIA® DLSS Frame Generation with NVIDIA® Reflex on an RTX 40 or 50 series card with Windows' hardware-accelerated GPU scheduling turned on, AMD FSR™ Frame Generation on every other DirectX 12 card; DLSS or FSR: that one, with either upscaler (when this PC cannot run it, Auto is used and the settings row says so). Changes apply at once, while the game runs. Runs while the upscaler is not Off (any mode, DLAA included), in windowed or borderless mode only, and pauses while the map or the menu is open or you use a terminal. Also in the game's settings (Video, Advanced Graphics), where a change applies at once.");
			HudInGeneratedFrames = ((BasePlugin)this).Config.Bind<bool>("Frame Generation", "HudInGeneratedFrames", true, "Keeps the HUD and crosshair out of the interpolation: DLSS Frame Generation gets the HUD as its own layer and composites it, AMD FSR Frame Generation gets the picture without the HUD. Turn it off if the HUD flickers or doubles while frame generation runs. Also in the game's settings (Video, Advanced Graphics), where a change applies at once.");
			Reflex = ((BasePlugin)this).Config.Bind<ReflexMode>("Frame Generation", "Reflex", ReflexMode.On, "NVIDIA® Reflex low latency, which runs with DLSS Frame Generation (not with AMD FSR Frame Generation). On, or Boost (On + Boost: keeps the graphics card's clock up for a little less delay at more power). Also in the game's settings (Video, Advanced Graphics), where a change applies at once.");
			FrameLimit = ((BasePlugin)this).Config.Bind<int>("Frame Generation", "FrameLimit", 0, new ConfigDescription("Reflex frame rate limit, in frames a second; 0 is no limit. Runs with DLSS Frame Generation. Also in the game's settings (Video, Advanced Graphics), where a change applies at once.", (AcceptableValueBase)(object)new AcceptableValueList<int>(FrameLimits), Array.Empty<object>()));
			if (num)
			{
				Upscaler.Value = UpscalerMethod.Off;
				((BasePlugin)this).Log.LogWarning((object)"The config's DLSS Mode was Off; the upscaler is now Off instead (Off moved from Mode to Upscaler).");
			}
			DlssBridge.Load();
			WorldPass.Load();
			UpscaleMenu.Load();
		}

		private static bool StoredModeOff(string path)
		{
			if (!File.Exists(path))
			{
				return false;
			}
			string text = "";
			foreach (string item in File.ReadLines(path))
			{
				string text2 = item.Trim();
				if (text2.StartsWith("[") && text2.EndsWith("]"))
				{
					string text3 = text2;
					text = text3.Substring(1, text3.Length - 1 - 1).Trim();
				}
				else if (text == "DLSS" && text2.StartsWith("Mode") && text2.Substring(4).TrimStart().StartsWith("="))
				{
					return text2.Substring(text2.IndexOf('=') + 1).Trim() == "Off";
				}
			}
			return false;
		}

		public override bool Unload()
		{
			return false;
		}
	}
	internal enum UpscalerMethod
	{
		Auto,
		DLSS,
		FSR,
		Off
	}
	internal enum FrameGenerationMethod
	{
		Off,
		Auto,
		DLSS,
		FSR
	}
	internal enum DlssMode
	{
		DLAA,
		Quality,
		Balanced,
		Performance,
		UltraPerformance
	}
	internal enum DlssPreset
	{
		Auto,
		K,
		M,
		L
	}
	internal enum DlssExposure
	{
		Auto,
		Fixed
	}
	internal enum ReflexMode
	{
		On,
		Boost
	}
	internal static class DlssBridge
	{
		internal enum State
		{
			Idle,
			Ready,
			Running,
			Unavailable,
			Failed,
			ForeignLibrary
		}

		[StructLayout(LayoutKind.Sequential, Pack = 8)]
		private struct InitParams
		{
			public uint Size;

			public uint Version;

			public IntPtr AnyTexture;

			public IntPtr LibraryFolder;

			public IntPtr DataFolder;

			public int Method;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 8)]
		internal struct FrameParams
		{
			public uint Size;

			public uint Version;

			public IntPtr Color;

			public IntPtr Depth;

			public IntPtr Motion;

			public IntPtr Output;

			public uint RenderWidth;

			public uint RenderHeight;

			public uint OutputWidth;

			public uint OutputHeight;

			public float JitterX;

			public float JitterY;

			public float MotionScaleX;

			public float MotionScaleY;

			public int Reset;

			public int Hdr;

			public int DepthInverted;

			public int Quality;

			public int Exposure;

			public int Preset;

			public float CameraNear;

			public float CameraFar;

			public float CameraFov;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 8)]
		internal struct FrameGenerationParams
		{
			public uint Size;

			public uint Version;

			public int Frame;

			public int Enabled;

			public IntPtr Depth;

			public IntPtr Motion;

			public IntPtr Hudless;

			public IntPtr HudOnBlack;

			public IntPtr HudOnWhite;

			public uint RenderWidth;

			public uint RenderHeight;

			public uint OutputWidth;

			public uint OutputHeight;

			public Matrix4x4 ViewToClip;

			public Matrix4x4 ClipToView;

			public Matrix4x4 ClipToPrevClip;

			public Matrix4x4 PrevClipToClip;

			public float JitterX;

			public float JitterY;

			public float MotionScaleX;

			public float MotionScaleY;

			public Vector3 CameraPosition;

			public Vector3 CameraUp;

			public Vector3 CameraRight;

			public Vector3 CameraForward;

			public float CameraNear;

			public float CameraFar;

			public float CameraFov;

			public float CameraAspect;

			public int Reset;

			public int DepthInverted;

			public int FlipRows;

			public int EncodeSrgb;
		}

		internal enum Missing
		{
			Runs,
			NotNvidia,
			Driver,
			Gpu,
			Scheduling,
			Windows,
			Failed,
			OtherCard
		}

		internal const uint AbiVersion = 3u;

		internal const int EventInitialize = 1;

		internal const int EventEvaluate = 2;

		internal const int EventShutdown = 3;

		internal const int EventFrameGeneration = 4;

		internal const uint FrameGenerationVersion = 2u;

		private const int FrameGenerationSize = 424;

		private const int Slots = 4;

		private unsafe static FrameParams* _frames;

		private unsafe static FrameGenerationParams* _generationFrames;

		private static int _nextSlot;

		private static int _nextGenerationSlot;

		private unsafe static delegate* unmanaged<int> _status;

		private unsafe static delegate* unmanaged<long> _evaluations;

		private unsafe static delegate* unmanaged<byte*, int, int> _popMessage;

		private unsafe static delegate* unmanaged<uint, uint, int, uint*, uint*, int> _optimal;

		private unsafe static delegate* unmanaged<int> _presentState;

		private unsafe static delegate* unmanaged<int*, int*, int*, long*, void> _graphicsCounts;

		private unsafe static delegate* unmanaged<byte*, int, int*, int> _popBridgeMessage;

		private unsafe static delegate* unmanaged<byte*, int, long*, long*, int*, int> _generationState;

		private unsafe static delegate* unmanaged<int, int, void> _frameMarker;

		private unsafe static delegate* unmanaged<int, void> _setDeveloperLog;

		private unsafe static delegate* unmanaged<void> _releaseGeneration;

		private unsafe static delegate* unmanaged<byte*, int, int> _generationCounters;

		private unsafe static delegate* unmanaged<int, int, void> _setReflex;

		private unsafe static delegate* unmanaged<byte*, int, int*, int> _upscaler;

		private unsafe static delegate* unmanaged<int> _generationBackend;

		private unsafe static delegate* unmanaged<int, void> _setHud;

		private unsafe static delegate* unmanaged<int, void> _prefer;

		private unsafe static delegate* unmanaged<void> _pluginConnected;

		private unsafe static delegate* unmanaged<uint*, uint*, int> _dlssMissing;

		private unsafe static delegate* unmanaged<byte*, int, int> _generationDlssMissing;

		private static bool _initIssued;

		private static IntPtr _init;

		private static readonly byte[] MessageBuffer = new byte[1024];

		private static int _pickedAt;

		private static FrameGenerationMethod? _generationFallbackWarned;

		private static readonly byte[] MissingBuffer = new byte[512];

		private static readonly byte[] ReasonBuffer = new byte[512];

		private static bool _restarting;

		private static readonly byte[] ChoiceBuffer = new byte[1024];

		private static State _reported = State.Idle;

		private static bool _developer = true;

		private static string? _reportedChoice;

		private static bool _fallbackWarned;

		internal static IntPtr RenderEvent { get; private set; }

		internal static IntPtr RenderSubmitStartEvent { get; private set; }

		internal static bool Loaded { get; private set; }

		internal unsafe static State Status
		{
			get
			{
				if (!Loaded || _restarting)
				{
					return State.Idle;
				}
				return (State)_status();
			}
		}

		internal unsafe static long Evaluations
		{
			get
			{
				if (!Loaded)
				{
					return 0L;
				}
				return _evaluations();
			}
		}

		internal unsafe static int FrameGenerationBackend
		{
			get
			{
				if (!Loaded)
				{
					return 0;
				}
				return _generationBackend();
			}
		}

		internal static bool Bridged => PresentState == 2;

		internal unsafe static int PresentState
		{
			get
			{
				if (!Loaded)
				{
					return 0;
				}
				return _presentState();
			}
		}

		internal unsafe static bool Generating
		{
			get
			{
				if (Loaded)
				{
					return _generationState(null, 0, null, null, null) == 2;
				}
				return false;
			}
		}

		internal static int Quality(DlssMode mode)
		{
			return mode switch
			{
				DlssMode.Quality => 2, 
				DlssMode.Balanced => 1, 
				DlssMode.Performance => 0, 
				DlssMode.UltraPerformance => 3, 
				_ => 5, 
			};
		}

		internal static int Preset(DlssPreset preset)
		{
			return preset switch
			{
				DlssPreset.K => 11, 
				DlssPreset.M => 13, 
				DlssPreset.L => 12, 
				_ => 0, 
			};
		}

		internal unsafe static (int Width, int Height) RenderSize(int outputWidth, int outputHeight, DlssMode mode)
		{
			if (mode == DlssMode.DLAA)
			{
				return (Width: outputWidth, Height: outputHeight);
			}
			uint num = 0u;
			uint num2 = 0u;
			if (_optimal((uint)outputWidth, (uint)outputHeight, Quality(mode), &num, &num2) != 0 && num != 0 && num2 != 0)
			{
				return (Width: (int)num, Height: (int)num2);
			}
			Plugin.Logger.ErrorOnce("framegen-native-failed", "The upscaler gave no render size for " + mode.ToString() + " at " + outputWidth + "x" + outputHeight + "; rendering at the screen's resolution (DLAA).");
			return (Width: outputWidth, Height: outputHeight);
		}

		internal unsafe static void Load()
		{
			string text = Path.Combine(Plugin.Folder, "ForgeFrameGen.Native.dll");
			string text2 = Array.Find(new string[3]
			{
				text,
				Path.Combine(Plugin.Folder, "nvngx_dlss.dll"),
				Path.Combine(Plugin.Folder, "amd_fidelityfx_loader_dx12.dll")
			}, (string path) => !File.Exists(path));
			if (text2 != null)
			{
				Plugin.Logger.ErrorOnce("framegen-library-missing", "The package is incomplete (" + text2 + " is missing); the upscaler stays off and the game renders unchanged. Reinstall the package.");
				return;
			}
			try
			{
				IntPtr handle = NativeLibrary.Load(text);
				delegate* unmanaged<uint> delegate* = (delegate* unmanaged<uint>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_AbiVersion");
				if (delegate*() != 3)
				{
					Plugin.Logger.ErrorOnce("framegen-native-failed", "The native bridge " + text + " is from another build (layout " + delegate*() + ", plugin expects " + 3u + "); DLSS stays off.");
					return;
				}
				_status = (delegate* unmanaged<int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_Status");
				_popMessage = (delegate* unmanaged<byte*, int, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_PopMessage");
				_evaluations = (delegate* unmanaged<long>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_Evaluations");
				_optimal = (delegate* unmanaged<uint, uint, int, uint*, uint*, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_OptimalRenderSize");
				_presentState = (delegate* unmanaged<int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_PresentState");
				_graphicsCounts = (delegate* unmanaged<int*, int*, int*, long*, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_GraphicsCounts");
				_popBridgeMessage = (delegate* unmanaged<byte*, int, int*, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_PopBridgeMessage");
				_generationState = (delegate* unmanaged<byte*, int, long*, long*, int*, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_FrameGenerationState");
				_frameMarker = (delegate* unmanaged<int, int, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_FrameMarker");
				_setDeveloperLog = (delegate* unmanaged<int, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_SetDeveloperLog");
				_releaseGeneration = (delegate* unmanaged<void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_ReleaseFrameGeneration");
				_generationCounters = (delegate* unmanaged<byte*, int, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_FrameGenerationCounters");
				_setReflex = (delegate* unmanaged<int, int, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_SetReflex");
				_upscaler = (delegate* unmanaged<byte*, int, int*, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_Upscaler");
				_generationBackend = (delegate* unmanaged<int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_FrameGenerationBackend");
				_setHud = (delegate* unmanaged<int, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_SetHudInGeneratedFrames");
				_prefer = (delegate* unmanaged<int, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_SetFrameGenerationPreference");
				_pluginConnected = (delegate* unmanaged<void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_PluginConnected");
				_dlssMissing = (delegate* unmanaged<uint*, uint*, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_DlssMissing");
				_generationDlssMissing = (delegate* unmanaged<byte*, int, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_DlssFrameGenerationMissing");
				RenderEvent = ((delegate* unmanaged<IntPtr>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_RenderEventFunc"))();
				RenderSubmitStartEvent = ((delegate* unmanaged<IntPtr>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_RenderSubmitStartFunc"))();
			}
			catch (Exception ex)
			{
				Plugin.Logger.ErrorOnce("framegen-native-failed", "Loading the native bridge " + text + " failed; DLSS stays off: " + ex);
				return;
			}
			if (Unsafe.SizeOf<FrameGenerationParams>() != 424)
			{
				Plugin.Logger.ErrorOnce("framegen-native-failed", "The frame generation parameter layout is " + Unsafe.SizeOf<FrameGenerationParams>() + " bytes, not the native " + 424 + "; DLSS stays off.");
				return;
			}
			_frames = (FrameParams*)NativeMemory.AllocZeroed((nuint)(4 * sizeof(FrameParams)));
			_generationFrames = (FrameGenerationParams*)NativeMemory.AllocZeroed((nuint)(4 * Unsafe.SizeOf<FrameGenerationParams>()));
			Loaded = true;
			_pluginConnected();
			SendReflex();
			Plugin.Reflex.SettingChanged += delegate
			{
				SendReflex();
			};
			Plugin.FrameLimit.SettingChanged += delegate
			{
				SendReflex();
			};
			SendHud();
			Plugin.HudInGeneratedFrames.SettingChanged += delegate
			{
				SendHud();
			};
			SendPreference();
			Plugin.FrameGeneration.SettingChanged += delegate
			{
				SendPreference();
			};
			if (_presentState() == 2)
			{
				FrameMarkers.Load();
			}
			Frame.OnUpdate("NAinfini.ForgeFrameGen", (Action)DrainMessages);
		}

		private unsafe static void SendReflex()
		{
			_setReflex((Plugin.Reflex.Value == ReflexMode.Boost) ? 1 : 0, Plugin.FrameLimit.Value);
		}

		private unsafe static void SendHud()
		{
			_setHud(Plugin.HudInGeneratedFrames.Value ? 1 : 0);
		}

		private unsafe static void SendPreference()
		{
			if (Plugin.FrameGenerationOn)
			{
				_prefer((int)(Plugin.FrameGeneration.Value - 1));
			}
			_pickedAt = Frame.Count;
		}

		private static void ReportGenerationFallback()
		{
			FrameGenerationMethod? frameGenerationMethod = FrameGenerationFallback();
			if (frameGenerationMethod.HasValue)
			{
				FrameGenerationMethod valueOrDefault = frameGenerationMethod.GetValueOrDefault();
				if (Plugin.FrameGeneration.Value != _generationFallbackWarned)
				{
					_generationFallbackWarned = Plugin.FrameGeneration.Value;
					string text = ((valueOrDefault == FrameGenerationMethod.DLSS) ? FrameGenerationDlssMissing().Why : "see the bridge's error lines above");
					Plugin.Info.LogWarning((object)("framegen-frame-generation-fallback: " + ((Plugin.FrameGeneration.Value == FrameGenerationMethod.Auto) ? "Auto wanted " : "picked ") + valueOrDefault.ToString() + " frame generation, which cannot run on this PC (" + text + "); " + ((valueOrDefault == FrameGenerationMethod.DLSS) ? "AMD FSR" : "DLSS") + " frame generation runs instead."));
				}
			}
		}

		internal unsafe static FrameGenerationMethod? FrameGenerationFallback()
		{
			FrameGenerationMethod value = Plugin.FrameGeneration.Value;
			if (value == FrameGenerationMethod.Off || Frame.Count - _pickedAt < 10)
			{
				return null;
			}
			int frameGenerationBackend = FrameGenerationBackend;
			if (value == FrameGenerationMethod.Auto)
			{
				bool flag = frameGenerationBackend == 2;
				if (flag)
				{
					Missing missing = (Missing)_generationDlssMissing(null, 0);
					bool flag2 = (uint)missing <= 1u;
					flag = !flag2;
				}
				if (!flag)
				{
					return null;
				}
				return FrameGenerationMethod.DLSS;
			}
			if (frameGenerationBackend == 0 || frameGenerationBackend == (int)(value - 1))
			{
				return null;
			}
			return value;
		}

		internal unsafe static (Missing Code, uint Major, uint Minor) DlssMissing()
		{
			if (!Loaded)
			{
				return (Code: Missing.Failed, Major: 0u, Minor: 0u);
			}
			uint item = default(uint);
			uint item2 = default(uint);
			return (Code: (Missing)_dlssMissing(&item, &item2), Major: item, Minor: item2);
		}

		internal unsafe static (Missing Code, string Why) FrameGenerationDlssMissing()
		{
			if (!Loaded)
			{
				return (Code: Missing.Failed, Why: "native bridge not loaded");
			}
			fixed (byte* missingBuffer = MissingBuffer)
			{
				int item = _generationDlssMissing(missingBuffer, MissingBuffer.Length);
				int num = Array.IndexOf(MissingBuffer, (byte)0);
				return (Code: (Missing)item, Why: Encoding.UTF8.GetString(missingBuffer, (num >= 0) ? num : 0));
			}
		}

		internal unsafe static void Marker(int marker, int frame)
		{
			_frameMarker(marker, frame);
		}

		internal unsafe static void ReleaseFrameGeneration()
		{
			if (Bridged)
			{
				_releaseGeneration();
			}
		}

		internal unsafe static FrameGenerationParams* NextGenerationFrame()
		{
			FrameGenerationParams* num = _generationFrames + _nextGenerationSlot;
			_nextGenerationSlot = (_nextGenerationSlot + 1) % 4;
			num->Size = (uint)Unsafe.SizeOf<FrameGenerationParams>();
			num->Version = 2u;
			return num;
		}

		internal unsafe static string FrameGeneration()
		{
			if (!Loaded)
			{
				return "native bridge not loaded";
			}
			int num;
			long num2 = default(long);
			long num3 = default(long);
			int num4 = default(int);
			string text;
			fixed (byte* reasonBuffer = ReasonBuffer)
			{
				num = _generationState(reasonBuffer, ReasonBuffer.Length, &num2, &num3, &num4);
				int num5 = Array.IndexOf(ReasonBuffer, (byte)0);
				text = Encoding.UTF8.GetString(reasonBuffer, (num5 >= 0) ? num5 : 0);
			}
			return "frame generation state " + num + " (" + text + "), frames " + num2 + ", generated " + num3 + ", last present showed " + num4 + " (frame " + Time.frameCount + "); " + Counters();
		}

		internal unsafe static string ShownFrames(int start)
		{
			if (!Loaded)
			{
				return "native bridge not loaded";
			}
			IntPtr handle = NativeLibrary.Load(Path.Combine(Plugin.Folder, "ForgeFrameGen.Native.dll"));
			delegate* unmanaged<int, void> delegate* = (delegate* unmanaged<int, void>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_WatchShownFrames");
			if (start != 0)
			{
				delegate*(1);
				return "watching";
			}
			delegate* unmanaged<byte*, int, int*, uint*, int> delegate*2 = (delegate* unmanaged<byte*, int, int*, uint*, int>)(void*)NativeLibrary.GetExport(handle, "ForgeFrameGen_ShownFrames");
			byte[] rows = new byte[4194304];
			int[] array = new int[128];
			int num;
			uint num2 = default(uint);
			fixed (byte* ptr = rows)
			{
				fixed (int* ptr2 = array)
				{
					num = delegate*2(ptr, 128, ptr2, &num2);
				}
			}
			delegate*(0);
			int w = (int)num2;
			if (num == 0 || w == 0)
			{
				return "nothing watched (AMD FSR Frame Generation not on?)";
			}
			int num3 = 0;
			int num4 = 0;
			double val = 0.0;
			for (int i = 1; i + 1 < num; i++)
			{
				if (array[i] != 0 && array[i - 1] == 0 && array[i + 1] == 0)
				{
					num3++;
					double val2 = Difference(i, i - 1);
					double val3 = Difference(i, i + 1);
					double num5 = Difference(i - 1, i + 1);
					double num6 = Math.Abs(Mean(i) - (Mean(i - 1) + Mean(i + 1)) / 2.0);
					val = Math.Max(val, Math.Min(val2, val3) - num5);
					if (Math.Min(val2, val3) > num5 + 8.0 || num6 > 10.0)
					{
						num4++;
					}
				}
			}
			int num7 = 0;
			for (int j = 0; j < num; j++)
			{
				num7 += array[j];
			}
			return "shown " + num + ", generated " + num7 + ", judged " + num3 + ", flickering " + num4 + ", worst excess difference " + val.ToString("F1");
			double Difference(int num9, int num10)
			{
				double num8 = 0.0;
				for (int k = 0; k < w * 4; k++)
				{
					if ((k & 3) != 3)
					{
						num8 += (double)Math.Abs(rows[num9 * w * 4 + k] - rows[num10 * w * 4 + k]);
					}
				}
				return num8 / (3.0 * (double)w);
			}
			double Mean(int num9)
			{
				double num8 = 0.0;
				for (int k = 0; k < w; k++)
				{
					num8 += (double)(rows[(num9 * w + k) * 4] + rows[(num9 * w + k) * 4 + 1] + rows[(num9 * w + k) * 4 + 2]);
				}
				return num8 / (3.0 * (double)w);
			}
		}

		internal unsafe static string Counters()
		{
			if (!Loaded)
			{
				return "native bridge not loaded";
			}
			fixed (byte* reasonBuffer = ReasonBuffer)
			{
				return Encoding.UTF8.GetString(reasonBuffer, _generationCounters(reasonBuffer, ReasonBuffer.Length));
			}
		}

		internal unsafe static string PresentBridge()
		{
			if (!Loaded)
			{
				return "native bridge not loaded";
			}
			int num = default(int);
			int num2 = default(int);
			int num3 = default(int);
			long num4 = default(long);
			_graphicsCounts(&num, &num2, &num3, &num4);
			return "present bridge state " + _presentState() + ", hooks saw " + num + " devices, " + num2 + " factories, " + num3 + " swap chains; bridge presents " + num4 + " (frame " + Time.frameCount + ")";
		}

		internal unsafe static void Initialize(Texture anyTexture)
		{
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			if (Loaded && Plugin.UpscalerOn && !_initIssued && (!_restarting || _status() == 0))
			{
				_initIssued = true;
				_restarting = false;
				string text = Path.Combine(Paths.CachePath, "ForgeFrameGen");
				Directory.CreateDirectory(text);
				InitParams* ptr = (InitParams*)(void*)((_init != IntPtr.Zero) ? _init : ((IntPtr)NativeMemory.AllocZeroed((nuint)sizeof(InitParams))));
				if (_init == IntPtr.Zero)
				{
					ptr->LibraryFolder = Marshal.StringToHGlobalUni(Plugin.Folder);
					ptr->DataFolder = Marshal.StringToHGlobalUni(text);
					_init = (IntPtr)ptr;
				}
				ptr->Size = (uint)sizeof(InitParams);
				ptr->Version = 3u;
				ptr->AnyTexture = anyTexture.GetNativeTexturePtr();
				ptr->Method = (int)Plugin.Upscaler.Value;
				CommandBuffer val = new CommandBuffer
				{
					name = "ForgeFrameGen upscaler start"
				};
				val.IssuePluginEventAndData(RenderEvent, 1, _init);
				Graphics.ExecuteCommandBuffer(val);
				val.Release();
			}
		}

		internal static void Restart()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_004e: Expected O, but got Unknown
			if (Loaded && _initIssued)
			{
				_initIssued = false;
				_restarting = true;
				_reportedChoice = null;
				_fallbackWarned = false;
				CommandBuffer val = new CommandBuffer
				{
					name = "ForgeFrameGen upscaler stop"
				};
				val.IssuePluginEventAndData(RenderEvent, 3, IntPtr.Zero);
				Graphics.ExecuteCommandBuffer(val);
				val.Release();
			}
		}

		internal unsafe static (UpscalerMethod Running, string Why, bool FellBack) Upscaler()
		{
			if (!Loaded)
			{
				return (Running: UpscalerMethod.Auto, Why: "native bridge not loaded", FellBack: false);
			}
			fixed (byte* choiceBuffer = ChoiceBuffer)
			{
				int num = default(int);
				int item = _upscaler(choiceBuffer, ChoiceBuffer.Length, &num);
				int num2 = Array.IndexOf(ChoiceBuffer, (byte)0);
				return (Running: (UpscalerMethod)item, Why: Encoding.UTF8.GetString(choiceBuffer, (num2 >= 0) ? num2 : 0), FellBack: num != 0);
			}
		}

		internal unsafe static FrameParams* NextFrame()
		{
			FrameParams* num = _frames + _nextSlot;
			_nextSlot = (_nextSlot + 1) % 4;
			num->Size = (uint)sizeof(FrameParams);
			num->Version = 3u;
			return num;
		}

		private static void ReportChoice()
		{
			var (upscalerMethod, text, flag) = Upscaler();
			if (!(text == _reportedChoice))
			{
				_reportedChoice = text;
				if (flag && !_fallbackWarned)
				{
					Plugin.Info.LogWarning((object)("framegen-upscaler-fallback: " + text));
				}
				_fallbackWarned |= flag;
				if (Log.Developer)
				{
					Plugin.Info.LogInfo((object)("framegen-upscaler-selected: " + upscalerMethod.ToString() + "; " + text));
				}
			}
		}

		private unsafe static void DrainMessages()
		{
			if (_developer != Log.Developer)
			{
				_setDeveloperLog((_developer = Log.Developer) ? 1 : 0);
			}
			ReportGenerationFallback();
			State status = Status;
			if (status != _reported)
			{
				_reported = status;
				if (Log.Developer)
				{
					Plugin.Info.LogInfo((object)("Upscaler bridge: " + status));
				}
				if (status != State.Idle)
				{
					ReportChoice();
				}
			}
			fixed (byte* messageBuffer = MessageBuffer)
			{
				int byteCount;
				while ((byteCount = _popMessage(messageBuffer, MessageBuffer.Length)) >= 0)
				{
					string text = Encoding.UTF8.GetString(messageBuffer, byteCount);
					object obj = Status switch
					{
						State.Unavailable => "framegen-unavailable", 
						State.ForeignLibrary => "framegen-foreign-library", 
						_ => "framegen-native-failed", 
					};
					ModLog logger = Plugin.Logger;
					string text2 = (string)obj;
					State status2 = Status;
					bool flag = (uint)(status2 - 1) <= 1u;
					logger.ErrorOnce(text2, flag ? (text + ".") : (text + "; the game renders unchanged."));
				}
			}
			fixed (byte* messageBuffer2 = MessageBuffer)
			{
				int byteCount2;
				int num = default(int);
				while ((byteCount2 = _popBridgeMessage(messageBuffer2, MessageBuffer.Length, &num)) >= 0)
				{
					if (num == 0 && !_developer)
					{
						continue;
					}
					string text3 = Encoding.UTF8.GetString(messageBuffer2, byteCount2);
					switch (num)
					{
					case 1:
						Plugin.Logger.ErrorOnce("framegen-frame-bridge-failed", text3);
						continue;
					case 2:
						Plugin.Logger.ErrorOnce("framegen-frame-generation-skipped", text3);
						continue;
					case 3:
						Plugin.Logger.ErrorOnce("framegen-frame-generation-switch-failed", text3);
						continue;
					}
					if (Log.Developer)
					{
						Plugin.Info.LogInfo((object)text3);
					}
				}
			}
		}
	}
	internal static class FrameMarkers
	{
		private const int SimulationStart = 0;

		private const int SimulationEnd = 1;

		private static int _frame;

		internal static void Load()
		{
			Frame.OnUpdate("NAinfini.ForgeFrameGen", (Action)Start);
			Frame.OnLateUpdate("NAinfini.ForgeFrameGen", (Action)End);
		}

		private static void Start()
		{
			DlssBridge.Marker(0, _frame = Time.frameCount);
		}

		private static void End()
		{
			DlssBridge.Marker(1, _frame);
			GL.IssuePluginEvent(DlssBridge.RenderSubmitStartEvent, _frame);
		}
	}
	internal static class MipBias
	{
		private static Dictionary<IntPtr, (Texture2D Texture, float Original)> Biased = new Dictionary<IntPtr, (Texture2D, float)>();

		private static readonly HashSet<IntPtr> Interface = new HashSet<IntPtr>();

		private static float _bias;

		internal static int Count => Biased.Count;

		internal static void Apply(float bias)
		{
			if (bias == 0f)
			{
				Restore();
				return;
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			Interface.Clear();
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Sprite>()))
			{
				Sprite obj = ((Il2CppObjectBase)item).TryCast<Sprite>();
				Texture2D val = ((obj != null) ? obj.texture : null);
				if ((Object)(object)val != (Object)null)
				{
					Interface.Add(((Il2CppObjectBase)val).Pointer);
				}
			}
			Dictionary<IntPtr, (Texture2D, float)> dictionary = new Dictionary<IntPtr, (Texture2D, float)>(Biased.Count);
			foreach (Object item2 in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Texture2D>()))
			{
				Texture2D val2 = ((Il2CppObjectBase)item2).TryCast<Texture2D>();
				if ((Object)(object)val2 == (Object)null || ((Texture)val2).mipmapCount <= 1)
				{
					continue;
				}
				(Texture2D, float) value;
				bool flag = Biased.TryGetValue(((Il2CppObjectBase)val2).Pointer, out value) && !((Il2CppObjectBase)value.Item1).WasCollected;
				if (Interface.Contains(((Il2CppObjectBase)val2).Pointer))
				{
					if (flag && Math.Abs(((Texture)val2).mipMapBias - (value.Item2 + _bias)) < 0.0001f)
					{
						((Texture)val2).mipMapBias = value.Item2;
					}
					continue;
				}
				if (!flag)
				{
					value = (val2, ((Texture)val2).mipMapBias);
				}
				else if (Math.Abs(((Texture)val2).mipMapBias - (value.Item2 + _bias)) >= 0.0001f)
				{
					value = (val2, ((Texture)val2).mipMapBias);
				}
				dictionary[((Il2CppObjectBase)val2).Pointer] = value;
				((Texture)val2).mipMapBias = value.Item2 + bias;
			}
			Biased = dictionary;
			_bias = bias;
			if (Log.Developer)
			{
				Plugin.Info.LogInfo((object)("Mip bias " + bias.ToString("F3") + " on " + Biased.Count + " textures in " + stopwatch.ElapsedMilliseconds + " ms"));
			}
		}

		internal static void Restore()
		{
			foreach (var (val, num) in Biased.Values)
			{
				if (!((Il2CppObjectBase)val).WasCollected && (Object)(object)val != (Object)null && Math.Abs(((Texture)val).mipMapBias - (num + _bias)) < 0.0001f)
				{
					((Texture)val).mipMapBias = num;
				}
			}
			Biased.Clear();
			_bias = 0f;
		}
	}
	internal static class ScreenSpace
	{
		private static IntPtr _camera;

		private static float _x = 1f;

		private static float _y = 1f;

		private static int _renderWidth;

		private static int _renderHeight;

		private static bool _patched;

		private static bool _failed;

		private static bool _volume;

		private static MethodBase? _single;

		private static MethodBase? _eye;

		private static MethodBase? _collect;

		private static MethodBase? _width;

		private static MethodBase? _height;

		private static void Patch()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_014c: Expected O, but got Unknown
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Expected O, but got Unknown
			if (_patched || _failed)
			{
				return;
			}
			try
			{
				HookPart[] array = (HookPart[])(object)new HookPart[1]
				{
					new HookPart((HarmonyMethod)null, new HarmonyMethod(typeof(ScreenSpace), "Scale", (Type[])null), (HarmonyMethod)null)
				};
				_single = AccessTools.Method(typeof(Camera), "WorldToScreenPoint", new Type[1] { typeof(Vector3) }, (Type[])null);
				_eye = AccessTools.Method(typeof(Camera), "WorldToScreenPoint", new Type[2]
				{
					typeof(Vector3),
					typeof(MonoOrStereoscopicEye)
				}, (Type[])null);
				_collect = AccessTools.Method(typeof(PreLitVolume), "CollectCommands", (Type[])null, (Type[])null);
				_width = AccessTools.PropertyGetter(typeof(Screen), "width");
				_height = AccessTools.PropertyGetter(typeof(Screen), "height");
				Hooks.Own("NAinfini.ForgeFrameGen", _single, (IReadOnlyList<HookPart>)array);
				Hooks.Own("NAinfini.ForgeFrameGen", _eye, (IReadOnlyList<HookPart>)array);
				Hooks.Own("NAinfini.ForgeFrameGen", _collect, (IReadOnlyList<HookPart>)(object)new HookPart[1]
				{
					new HookPart(new HarmonyMethod(typeof(ScreenSpace), "EnterVolume", (Type[])null), new HarmonyMethod(typeof(ScreenSpace), "LeaveVolume", (Type[])null), (HarmonyMethod)null)
				});
				Hooks.Own("NAinfini.ForgeFrameGen", _width, (IReadOnlyList<HookPart>)(object)new HookPart[1]
				{
					new HookPart((HarmonyMethod)null, new HarmonyMethod(typeof(ScreenSpace), "Width", (Type[])null), (HarmonyMethod)null)
				});
				Hooks.Own("NAinfini.ForgeFrameGen", _height, (IReadOnlyList<HookPart>)(object)new HookPart[1]
				{
					new HookPart((HarmonyMethod)null, new HarmonyMethod(typeof(ScreenSpace), "Height", (Type[])null), (HarmonyMethod)null)
				});
				_patched = true;
			}
			catch (Exception ex)
			{
				_failed = true;
				Unpatch();
				Plugin.Logger.ErrorOnce("framegen-screen-points-unpatched", "Camera.WorldToScreenPoint, PreLitVolume.CollectCommands or Screen.width/height could not be patched; while DLSS renders below the screen's resolution HUD markers that follow world positions sit at the wrong place and distant surfaces lose their indirect light: " + ex);
			}
		}

		private static void Unpatch()
		{
			try
			{
				MethodBase[] array = new MethodBase[5] { _single, _eye, _collect, _width, _height };
				foreach (MethodBase methodBase in array)
				{
					if (methodBase != null)
					{
						Hooks.Disown("NAinfini.ForgeFrameGen", methodBase);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.ErrorOnce("framegen-screen-points-not-released", "Camera.WorldToScreenPoint, PreLitVolume.CollectCommands or Screen.width/height could not be taken off again: " + ex);
			}
			_patched = (_volume = false);
		}

		internal static void Route(Camera camera, int renderWidth, int renderHeight, int outputWidth, int outputHeight)
		{
			_camera = ((Il2CppObjectBase)camera).Pointer;
			_renderWidth = renderWidth;
			_renderHeight = renderHeight;
			_x = (float)outputWidth / (float)renderWidth;
			_y = (float)outputHeight / (float)renderHeight;
			if (_x != 1f || _y != 1f)
			{
				Patch();
			}
			else if (_patched)
			{
				Unpatch();
			}
		}

		internal static void Clear()
		{
			_camera = IntPtr.Zero;
			_x = (_y = 1f);
			if (_patched)
			{
				Unpatch();
			}
		}

		private static void EnterVolume()
		{
			_volume = true;
		}

		private static void LeaveVolume()
		{
			_volume = false;
		}

		private static void Width(ref int __result)
		{
			if (_volume)
			{
				__result = _renderWidth;
			}
		}

		private static void Height(ref int __result)
		{
			if (_volume)
			{
				__result = _renderHeight;
			}
		}

		private static void Scale(Camera __instance, ref Vector3 __result)
		{
			if (!(((Il2CppObjectBase)__instance).Pointer != _camera))
			{
				__result.x *= _x;
				__result.y *= _y;
			}
		}
	}
	internal static class UpscaleMenu
	{
		private const string Name = "Dlss";

		private static readonly DlssMode[] Modes = new DlssMode[5]
		{
			DlssMode.DLAA,
			DlssMode.Quality,
			DlssMode.Balanced,
			DlssMode.Performance,
			DlssMode.UltraPerformance
		};

		private static readonly UIText NoDlss = UIText.Key("mode.unavailable", Array.Empty<object>());

		private static readonly UIText NoGeneration = UIText.Key("generation.unavailable", Array.Empty<object>());

		private static readonly UIText DlssOnly = UIText.Key("model.dlssonly", Array.Empty<object>());

		private static readonly UIText UpscalerText = UIText.Key("upscaler.hint", Array.Empty<object>());

		private static readonly UIText UpscalerOff = UIText.Key("upscaler.offhint", Array.Empty<object>());

		private static readonly UIText[] ModelHints = Array.ConvertAll(Enum.GetValues<DlssPreset>(), (DlssPreset model) => UIText.Key("model.hint." + model, Array.Empty<object>()));

		internal static void Load()
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			//IL_0361: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Expected O, but got Unknown
			List<SettingsRow> list = new List<SettingsRow>
			{
				(SettingsRow)(object)Choice<UpscalerMethod>("upscaler.title", Plugin.Upscaler, () => DlssBridge.Loaded, UpscalerHint),
				(SettingsRow)new SettingsChoice(UIText.Key("mode.title", Array.Empty<object>()), (IReadOnlyList<UIText>)Array.ConvertAll(Modes, (DlssMode mode) => UIText.Key("mode." + mode, Array.Empty<object>())), (Func<int>)(() => Array.IndexOf(Modes, Plugin.Mode.Value)), (Action<int>)delegate(int index)
				{
					Plugin.Mode.Value = Modes[index];
				}, Upscaling(Available), Dlss("mode.hint")),
				(SettingsRow)(object)Choice<DlssPreset>("model.title", Plugin.Preset, Upscaling(DlssRuns), Off(() => Available() ? ((!DlssRuns()) ? DlssOnly : ModelHints[(int)Plugin.Preset.Value]) : NoDlss)),
				(SettingsRow)(object)Choice<DlssExposure>("exposure.title", Plugin.Exposure, Upscaling(Available), Dlss("exposure.hint")),
				(SettingsRow)(object)Choice<FrameGenerationMethod>("generation.title", Plugin.FrameGeneration, Upscaling(() => Plugin.FrameGenerationOn || Bridged()), Off(GenerationStatus)),
				(SettingsRow)new SettingsToggle(UIText.Key("hud.title", Array.Empty<object>()), (Func<bool>)(() => Plugin.HudInGeneratedFrames.Value), (Action<bool>)delegate(bool on)
				{
					Plugin.HudInGeneratedFrames.Value = on;
				}, Upscaling(Bridged), Bridge("hud.hint", "hud.hint.fsr")),
				(SettingsRow)(object)Choice<ReflexMode>("reflex.title", Plugin.Reflex, Upscaling(Reflex), Bridge("reflex.hint", "reflex.fsr")),
				(SettingsRow)new SettingsChoice(UIText.Key("limit.title", Array.Empty<object>()), (IReadOnlyList<UIText>)Array.ConvertAll(Plugin.FrameLimits, (int limit) => (limit != 0) ? UIText.Key("limit.fps", new object[1] { limit }) : UIText.Key("limit.off", Array.Empty<object>())), (Func<int>)(() => Array.IndexOf(Plugin.FrameLimits, Plugin.FrameLimit.Value)), (Action<int>)delegate(int index)
				{
					Plugin.FrameLimit.Value = Plugin.FrameLimits[index];
				}, Upscaling(Reflex), Bridge("limit.hint", "reflex.fsr"))
			};
			UIKit.Mod("NAinfini.ForgeFrameGen").AddSettings("Dlss", (SettingsBlock)0, (IReadOnlyList<SettingsRow>)list, (Action)Reset);
		}

		private static SettingsChoice Choice<T>(string title, ConfigEntry<T> setting, Func<bool> enabled, Func<UIText?> hint) where T : struct, Enum
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			T[] values = Enum.GetValues<T>();
			string prefix = title.Substring(0, title.IndexOf('.') + 1);
			return new SettingsChoice(UIText.Key(title, Array.Empty<object>()), (IReadOnlyList<UIText>)Array.ConvertAll(values, delegate(T value)
			{
				string text = prefix;
				T val = value;
				return UIText.Key(text + val, Array.Empty<object>());
			}), (Func<int>)(() => Array.IndexOf(values, setting.Value)), (Action<int>)delegate(int index)
			{
				setting.Value = values[index];
			}, enabled, hint);
		}

		private static Func<bool> Upscaling(Func<bool> enabled)
		{
			return () => Plugin.UpscalerOn && enabled();
		}

		private static Func<UIText?> Off(Func<UIText?> hint)
		{
			return () => (UIText?)((!Plugin.UpscalerOn) ? ((object)UpscalerOff) : ((object)hint()));
		}

		private static Func<UIText?> Dlss(string key)
		{
			UIText text = UIText.Key(key, Array.Empty<object>());
			return Off(() => (UIText?)((!Available()) ? ((object)NoDlss) : ((object)text)));
		}

		private static Func<UIText?> Bridge(string key, string fsr)
		{
			UIText text = UIText.Key(key, Array.Empty<object>());
			UIText fsrText = UIText.Key(fsr, Array.Empty<object>());
			return Off(() => (UIText?)(Bridged() ? ((object)((Backend() != 2) ? text : fsrText)) : ((object)NoGeneration)));
		}

		private static void Reset()
		{
			ConfigEntryBase[] array = (ConfigEntryBase[])(object)new ConfigEntryBase[8]
			{
				(ConfigEntryBase)Plugin.Upscaler,
				(ConfigEntryBase)Plugin.Mode,
				(ConfigEntryBase)Plugin.Preset,
				(ConfigEntryBase)Plugin.Exposure,
				(ConfigEntryBase)Plugin.FrameGeneration,
				(ConfigEntryBase)Plugin.HudInGeneratedFrames,
				(ConfigEntryBase)Plugin.Reflex,
				(ConfigEntryBase)Plugin.FrameLimit
			};
			foreach (ConfigEntryBase obj in array)
			{
				obj.BoxedValue = obj.DefaultValue;
			}
		}

		internal static string Rows()
		{
			return UIKit.Mod("NAinfini.ForgeFrameGen").SettingsReadback("Dlss");
		}

		internal static string Show(int window)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			if (window < 0)
			{
				FocusStateManager.ExitMenu(true);
				return "closed";
			}
			FocusStateManager.EnterMenu((eCM_MenuPage)10, true);
			MainMenuGuiLayer mainMenuLayer = GuiManager.MainMenuLayer;
			object obj;
			if (mainMenuLayer == null)
			{
				obj = null;
			}
			else
			{
				CM_PageBase page = mainMenuLayer.GetPage((eCM_MenuPage)10);
				obj = ((page != null) ? ((Il2CppObjectBase)page).TryCast<CM_PageSettings>() : null);
			}
			CM_PageSettings val = (CM_PageSettings)obj;
			if (val == null)
			{
				return "no settings page";
			}
			if (window >= val.m_allSettingsWindows.Count)
			{
				return "windows: " + val.m_allSettingsWindows.Count;
			}
			val.ShowSettingsWindow(val.m_allSettingsWindows[window]);
			return "page=" + ((object)val.m_currentSubMenuId/*cast due to .constrained prefix*/).ToString() + "\n" + Rows();
		}

		internal static string Choose(string row)
		{
			UpscalerMethod result;
			if (row.StartsWith("fg:"))
			{
				Plugin.FrameGeneration.Value = Enum.Parse<FrameGenerationMethod>(row.Substring(3));
			}
			else if (Enum.TryParse<UpscalerMethod>(row, out result))
			{
				Plugin.Upscaler.Value = result;
			}
			else
			{
				Plugin.Mode.Value = (DlssMode)Enum.Parse(typeof(DlssMode), row);
			}
			return "upscaler=" + Plugin.Upscaler.Value.ToString() + " running=" + DlssBridge.Upscaler().Running.ToString() + " mode=" + Plugin.Mode.Value.ToString() + " generation=" + Plugin.FrameGeneration.Value.ToString() + " backend=" + DlssBridge.FrameGenerationBackend + " bridge=" + DlssBridge.PresentState + " status=" + (object)GenerationStatus();
		}

		private static bool Available()
		{
			if (!DlssBridge.Loaded)
			{
				return false;
			}
			if (DlssBridge.Status == DlssBridge.State.Idle && Plugin.UpscalerOn)
			{
				DlssBridge.Initialize((Texture)(object)Texture2D.whiteTexture);
			}
			DlssBridge.State status = DlssBridge.Status;
			bool flag = (uint)(status - 3) <= 2u;
			return !flag;
		}

		private static bool Bridged()
		{
			return DlssBridge.Bridged;
		}

		private static int Backend()
		{
			return DlssBridge.FrameGenerationBackend;
		}

		private static bool Reflex()
		{
			if (Bridged())
			{
				return Backend() == 1;
			}
			return false;
		}

		private static bool DlssRuns()
		{
			if (Available())
			{
				return DlssBridge.Upscaler().Running == UpscalerMethod.DLSS;
			}
			return false;
		}

		private static UIText? UpscalerHint()
		{
			if (!Plugin.UpscalerOn)
			{
				return UpscalerOff;
			}
			if (!Available())
			{
				return NoDlss;
			}
			var (upscalerMethod, _, flag) = DlssBridge.Upscaler();
			if (upscalerMethod == UpscalerMethod.Auto)
			{
				return UpscalerText;
			}
			if (!flag)
			{
				return UIText.Key("upscaler.running", new object[1] { Brand(upscalerMethod) });
			}
			if (upscalerMethod == UpscalerMethod.DLSS)
			{
				return UIText.Key("upscaler.fallback", new object[3]
				{
					Brand(UpscalerMethod.FSR),
					Brand(upscalerMethod),
					Text("fsr.missing")
				});
			}
			(DlssBridge.Missing Code, uint Major, uint Minor) tuple2 = DlssBridge.DlssMissing();
			DlssBridge.Missing item = tuple2.Code;
			uint item2 = tuple2.Major;
			uint item3 = tuple2.Minor;
			string text = ((item == DlssBridge.Missing.Driver && item2 != 0) ? Text("dlss.missing.DriverVersion", item2, item3) : MissingText(item, generation: false));
			if (Plugin.Upscaler.Value != UpscalerMethod.Auto)
			{
				return UIText.Key("upscaler.fallback", new object[3]
				{
					Brand(UpscalerMethod.DLSS),
					Brand(upscalerMethod),
					text
				});
			}
			return UIText.Key("upscaler.auto.fallback", new object[1] { text });
		}

		private static string MissingText(DlssBridge.Missing missing, bool generation)
		{
			return Text((generation && missing == DlssBridge.Missing.Gpu) ? "dlssg.missing.Gpu" : ("dlss.missing." + missing));
		}

		private static string Text(string key, params object?[] args)
		{
			return UIKit.Mod("NAinfini.ForgeFrameGen").Text(key, args);
		}

		private static string Brand(UpscalerMethod method)
		{
			if (method != UpscalerMethod.FSR)
			{
				return "NVIDIA® DLSS";
			}
			return "AMD FSR™";
		}

		private static string GenerationBrand(int backend)
		{
			if (backend != 2)
			{
				return "NVIDIA® DLSS";
			}
			return "AMD FSR™";
		}

		private static UIText GenerationStatus()
		{
			if (!DlssBridge.Bridged || Backend() == 0)
			{
				return NoGeneration;
			}
			if (!Plugin.FrameGenerationOn)
			{
				return UIText.Key("generation.hint", Array.Empty<object>());
			}
			FrameGenerationMethod? frameGenerationMethod = DlssBridge.FrameGenerationFallback();
			if (frameGenerationMethod.HasValue)
			{
				FrameGenerationMethod valueOrDefault = frameGenerationMethod.GetValueOrDefault();
				if (valueOrDefault == FrameGenerationMethod.FSR)
				{
					return UIText.Key("generation.fallback.fsr", Array.Empty<object>());
				}
				string text = MissingText(DlssBridge.FrameGenerationDlssMissing().Code, generation: true);
				return UIText.Key((Plugin.FrameGeneration.Value == FrameGenerationMethod.Auto) ? "generation.auto.fallback" : "generation.fallback.dlss", new object[1] { text });
			}
			return UIText.Key(DlssBridge.Generating ? "generation.running" : "generation.waiting", new object[1] { GenerationBrand(Backend()) });
		}
	}
	internal static class WorldPass
	{
		private const CameraEvent EvaluateEvent = (CameraEvent)19;

		private const DepthTextureMode InputTextures = (DepthTextureMode)5;

		private static readonly int DepthTextureId = Shader.PropertyToID("_CameraDepthTexture");

		private static readonly int MotionTextureId = Shader.PropertyToID("_CameraMotionVectorsTexture");

		private static readonly RenderTargetIdentifier CameraTargetId = new RenderTargetIdentifier((BuiltinRenderTextureType)2);

		private static CommandBuffer? _evaluate;

		private static IntPtr _cameraPointer;

		private static IntPtr _presenterPointer;

		private static RenderTargetIdentifier _colorId;

		private static RenderTargetIdentifier _depthId;

		private static RenderTargetIdentifier _motionId;

		private static float _jitterScaleX;

		private static float _jitterScaleY;

		private static bool _jitterMeasured;

		private static bool _reversedDepth;

		private static bool _linearColour;

		private static IDisposable? _standIn;

		private static readonly Func<RenderTexture?> PresentedFrameStep = PresentedFrame;

		private static Camera? _camera;

		private static Camera? _presenter;

		private static PostProcessLayer? _layer;

		private static Antialiasing _layerMode;

		private static UI_Apply? _hud;

		private static UI_Apply? _presentHud;

		private static Material? _hudMaterial;

		private static RenderTexture? _world;

		private static RenderTexture? _color;

		private static RenderTexture? _depth;

		private static RenderTexture? _motion;

		private static RenderTexture? _output;

		private static RenderTexture? _hudOnBlack;

		private static RenderTexture? _hudOnWhite;

		private static IntPtr _colorPointer;

		private static IntPtr _depthPointer;

		private static IntPtr _motionPointer;

		private static IntPtr _outputPointer;

		private static IntPtr _hudOnBlackPointer;

		private static IntPtr _hudOnWhitePointer;

		private static DlssMode _mode;

		private static int _renderWidth;

		private static int _renderHeight;

		private static int _outputWidth;

		private static int _outputHeight;

		private static int _phases = 8;

		private static int _lastFrame = -1;

		private static int _jitterIndex;

		private static bool _active;

		private static bool _reset;

		private static bool _presenting;

		private static bool _measureHud;

		private static bool _jittered;

		private static IDisposable? _preCull;

		private static float _fovAtPreCull;

		private static int _fovFrames;

		private static int _fovLate;

		private static float _signJitterX = 1f;

		private static float _signJitterY = 1f;

		private static float _signMotionX = 1f;

		private static float _signMotionY = 1f;

		private static Matrix4x4 _previousViewToClip;

		private static Matrix4x4 _previousWorldToView;

		private static bool _hasPrevious;

		private static int _flipRows = 1;

		private static readonly Dictionary<string, (float Sum, int Frame)> ProbeLast = new Dictionary<string, (float, int)>();

		private static readonly Dictionary<(int, int, TextureFormat), Texture2D> ProbeReadback = new Dictionary<(int, int, TextureFormat), Texture2D>();

		private static CommandBuffer? _held;

		private static CameraEvent _heldAt;

		private static OutlineHandle? _outline;

		internal static void Load()
		{
			if (!DlssBridge.Loaded)
			{
				return;
			}
			Frame.OnLateUpdate("NAinfini.ForgeFrameGen", (Action)FollowWorldCamera);
			Plugin.Upscaler.SettingChanged += delegate
			{
				Stop();
				DlssBridge.Restart();
				SyncPreCull();
			};
			SyncPreCull();
			GameEvents.StateChanged += delegate
			{
				if (_active)
				{
					MipBias.Apply(Bias());
				}
				LogCounters();
			};
			Frame.OnQuit("NAinfini.ForgeFrameGen", (Action)LogCounters);
		}

		private static void LogCounters()
		{
			if (Log.Developer && DlssBridge.Bridged)
			{
				Plugin.Info.LogInfo((object)("Frame generation so far: " + DlssBridge.Counters()));
			}
		}

		private static void SyncPreCull()
		{
			bool flag = Plugin.UpscalerOn || _active;
			if (flag && _preCull == null)
			{
				_preCull = Frame.OnPreCull("NAinfini.ForgeFrameGen", (Action<Camera>)PreCull);
			}
			else if (!flag && _preCull != null)
			{
				_preCull.Dispose();
				_preCull = null;
			}
		}

		private static void RestoreProjection()
		{
			if (_jittered)
			{
				_jittered = false;
				if (!NativeObjects.Gone((Object)(object)_camera))
				{
					_camera.ResetProjectionMatrix();
				}
			}
		}

		private static void FollowWorldCamera()
		{
			if (!_active)
			{
				return;
			}
			if (NativeObjects.Gone((Object)(object)_camera))
			{
				Stop();
				return;
			}
			RestoreProjection();
			bool isActiveAndEnabled = ((Behaviour)_camera).isActiveAndEnabled;
			if (isActiveAndEnabled != _presenting && !((Object)(object)_presenter == (Object)null) && !((Il2CppObjectBase)_presenter).WasCollected)
			{
				((Behaviour)_presenter).enabled = (_presenting = isActiveAndEnabled);
			}
		}

		internal static string Readback()
		{
			//IL_0409: Unknown result type (might be due to invalid IL or missing references)
			//IL_040e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			Camera val = (((Object)(object)_camera != (Object)null && !((Il2CppObjectBase)_camera).WasCollected) ? _camera : null);
			ClusteredRendering current = ClusteredRendering.Current;
			return "status=" + DlssBridge.Status.ToString() + " upscaler=" + DlssBridge.Upscaler().Why + " evaluations=" + DlssBridge.Evaluations + " active=" + _active + " mode=" + Plugin.Mode.Value.ToString() + " render=" + _renderWidth + "x" + _renderHeight + " output=" + _outputWidth + "x" + _outputHeight + " phases=" + _phases + " target=" + (((Object)(object)((val != null) ? val.targetTexture : null) == (Object)null) ? "screen" : (((Texture)val.targetTexture).width + "x" + ((Texture)val.targetTexture).height)) + " pixels=" + (((Object)(object)val == (Object)null) ? "none" : (val.pixelWidth + "x" + val.pixelHeight)) + " clusters=" + (((Object)(object)current == (Object)null) ? "none" : (current.m_width + "x" + current.m_height)) + " hudApply=" + (((Object)(object)_hud == (Object)null || ((Il2CppObjectBase)_hud).WasCollected) ? "none" : (((Behaviour)_hud).enabled ? "on" : "off")) + " hudMaterial=" + ((Object)(object)_hudMaterial != (Object)null) + " presenting=" + ((Object)(object)_presentHud != (Object)null && !((Il2CppObjectBase)_presentHud).WasCollected && ((Behaviour)_presentHud).enabled && (Object)(object)_presenter != (Object)null && ((Behaviour)_presenter).enabled) + " mipTextures=" + MipBias.Count + " fovLate=" + _fovLate + "/" + _fovFrames + " hdr=" + ((Object)(object)val != (Object)null && val.allowHDR) + " stackAA=" + (((Object)(object)_layer == (Object)null || ((Il2CppObjectBase)_layer).WasCollected) ? "none" : ((object)_layer.antialiasingMode/*cast due to .constrained prefix*/).ToString()) + " playerAA=" + ((object)Unsafe.As<Antialiasing, Antialiasing>(ref _layerMode)/*cast due to .constrained prefix*/).ToString() + " model=" + Plugin.Preset.Value.ToString() + " exposure=" + Plugin.Exposure.Value.ToString() + " hudMeasured=" + _measureHud + " focus=" + ((object)Frame.Focus/*cast due to .constrained prefix*/).ToString();
		}

		internal static string SetMode(string mode)
		{
			Plugin.Mode.Value = (DlssMode)Enum.Parse(typeof(DlssMode), mode);
			return Readback();
		}

		internal static string Signs(float jitterX, float jitterY, float motionX, float motionY)
		{
			float signJitterX = jitterX;
			float signJitterY = jitterY;
			float signMotionX = motionX;
			float signMotionY = motionY;
			_signJitterX = signJitterX;
			_signJitterY = signJitterY;
			_signMotionX = signMotionX;
			_signMotionY = signMotionY;
			_reset = true;
			return "signs=" + jitterX + "," + jitterY + "," + motionX + "," + motionY;
		}

		private static Camera? WorldCamera()
		{
			PlayerAgent local = Players.Local;
			FPSCamera val = ((local != null) ? local.FPSCamera : null);
			if (!((Object)(object)val == (Object)null) && !((Il2CppObjectBase)val).WasCollected)
			{
				return ((CameraController)val).m_camera;
			}
			return null;
		}

		private unsafe static void PreCull(Camera camera)
		{
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Invalid comparison between Unknown and I4
			//IL_02f5: 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_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_036c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_051d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_0544: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_056d: Unknown result type (might be due to invalid IL or missing references)
			IntPtr pointer = ((Il2CppObjectBase)camera).Pointer;
			if (pointer == _presenterPointer)
			{
				RestoreProjection();
				if (Log.Developer)
				{
					CountLateFieldOfView();
				}
				return;
			}
			if (_active)
			{
				if (pointer != _cameraPointer)
				{
					return;
				}
			}
			else
			{
				if (!Plugin.UpscalerOn)
				{
					return;
				}
				Camera val = WorldCamera();
				if ((Object)(object)val == (Object)null || ((Il2CppObjectBase)val).Pointer != pointer)
				{
					return;
				}
				_camera = camera;
			}
			DlssMode value = Plugin.Mode.Value;
			DlssBridge.State status = DlssBridge.Status;
			bool flag = !Plugin.UpscalerOn;
			if (!flag)
			{
				bool flag2 = (uint)status <= 2u;
				flag = !flag2;
			}
			if (flag)
			{
				Stop();
				return;
			}
			if (status == DlssBridge.State.Idle)
			{
				DlssBridge.Initialize((Texture)(object)Texture2D.whiteTexture);
				return;
			}
			RenderTexture targetTexture = camera.targetTexture;
			if (targetTexture != null && (_world == null || ((Il2CppObjectBase)targetTexture).Pointer != ((Il2CppObjectBase)_world).Pointer))
			{
				Plugin.Logger.ErrorOnce("framegen-camera-target", "The world camera already renders into " + ((Object)targetTexture).name + " (not the screen); DLSS stays off while it does.");
				Stop();
				return;
			}
			if (!_active && (Object)(object)((Component)camera).GetComponent<UI_Apply>() == (Object)null)
			{
				Plugin.Logger.ErrorOnce("framegen-hud-missing", "The world camera has no UI_Apply, through which the DLSS image is presented; DLSS stays off.");
				return;
			}
			int screenWidth = Frame.ScreenWidth;
			int screenHeight = Frame.ScreenHeight;
			bool bridged = DlssBridge.Bridged;
			bool flag3 = bridged && Plugin.FrameGenerationOn && Plugin.HudInGeneratedFrames.Value && DlssBridge.FrameGenerationBackend == 1;
			bool flag4 = false;
			if (!_active || value != _mode || screenWidth != _outputWidth || screenHeight != _outputHeight || flag3 != _measureHud)
			{
				_measureHud = flag3;
				(int Width, int Height) tuple = DlssBridge.RenderSize(screenWidth, screenHeight, value);
				_renderWidth = tuple.Width;
				_renderHeight = tuple.Height;
				int outputWidth = screenWidth;
				int outputHeight = screenHeight;
				_mode = value;
				_outputWidth = outputWidth;
				_outputHeight = outputHeight;
				float num = (float)_outputWidth / (float)_renderWidth;
				_phases = Math.Max(8, (int)Math.Ceiling(8f * num * num - 0.0001f));
				EnsureTargets();
				if (_active)
				{
					MipBias.Apply(Bias());
				}
				flag4 = (_reset = true);
			}
			else if (!_world.IsCreated())
			{
				ReleaseTargets();
				EnsureTargets();
				flag4 = (_reset = true);
			}
			if (!_active)
			{
				Start(camera);
			}
			if (flag4 || targetTexture == null)
			{
				camera.targetTexture = _world;
			}
			ScreenSpace.Route(camera, _renderWidth, _renderHeight, _outputWidth, _outputHeight);
			ClusteredRendering current = ClusteredRendering.Current;
			if ((Object)(object)current != (Object)null && (current.m_width != _renderWidth || current.m_height != _renderHeight))
			{
				current.OnResolutionchange(_renderWidth, _renderHeight);
			}
			int frameCount = Time.frameCount;
			if (frameCount - _lastFrame > 1)
			{
				_reset = true;
			}
			_lastFrame = frameCount;
			KeepStackAntiAliasingOff();
			DepthTextureMode depthTextureMode = camera.depthTextureMode;
			if ((depthTextureMode & 5) != 5)
			{
				camera.depthTextureMode = (DepthTextureMode)(depthTextureMode | 5);
			}
			if (Log.Developer)
			{
				_fovAtPreCull = camera.fieldOfView;
			}
			_jitterIndex = _jitterIndex % _phases + 1;
			float num2 = (Halton(_jitterIndex, 2) - 0.5f) * _signJitterX;
			float num3 = (Halton(_jitterIndex, 3) - 0.5f) * _signJitterY;
			camera.ResetProjectionMatrix();
			Matrix4x4 val2 = (camera.nonJitteredProjectionMatrix = camera.projectionMatrix);
			Matrix4x4 projectionMatrix2 = val2;
			projectionMatrix2.m02 -= 2f * num2 / (float)_renderWidth;
			projectionMatrix2.m12 -= 2f * num3 / (float)_renderHeight;
			camera.projectionMatrix = projectionMatrix2;
			_jittered = true;
			if (!_jitterMeasured)
			{
				MeasureJitter(val2);
			}
			DlssBridge.FrameParams* ptr = DlssBridge.NextFrame();
			ptr->Color = _colorPointer;
			ptr->Depth = _depthPointer;
			ptr->Motion = _motionPointer;
			ptr->Output = _outputPointer;
			ptr->RenderWidth = (uint)_renderWidth;
			ptr->RenderHeight = (uint)_renderHeight;
			ptr->OutputWidth = (uint)_outputWidth;
			ptr->OutputHeight = (uint)_outputHeight;
			ptr->JitterX = num2 * _jitterScaleX;
			ptr->JitterY = num3 * _jitterScaleY;
			ptr->MotionScaleX = (float)(-_renderWidth) * _signMotionX;
			ptr->MotionScaleY = (float)(-_renderHeight) * _signMotionY;
			ptr->Reset = (_reset ? 1 : 0);
			ptr->Hdr = 1;
			ptr->DepthInverted = (_reversedDepth ? 1 : 0);
			ptr->Quality = DlssBridge.Quality(_mode);
			ptr->Exposure = (int)Plugin.Exposure.Value;
			ptr->Preset = DlssBridge.Preset(Plugin.Preset.Value);
			ref float reference = ref ptr->CameraNear;
			ref float reference2 = ref ptr->CameraFar;
			float* cameraFov = &ptr->CameraFov;
			(float, float, float) tuple2 = Planes(val2);
			reference = tuple2.Item1;
			reference2 = tuple2.Item2;
			*cameraFov = tuple2.Item3;
			_reset = false;
			CommandBuffer evaluate = _evaluate;
			evaluate.Clear();
			evaluate.Blit(CameraTargetId, _colorId);
			CopyGlobal(evaluate, DepthTextureId, _depthId);
			CopyGlobal(evaluate, MotionTextureId, _motionId);
			evaluate.IssuePluginEventAndData(DlssBridge.RenderEvent, 2, (IntPtr)ptr);
			if (bridged)
			{
				evaluate.IssuePluginEventAndData(DlssBridge.RenderEvent, 4, (IntPtr)GenerationFrame(camera, val2, ptr->JitterX, ptr->JitterY, ptr->Reset != 0, frameCount));
			}
		}

		private static void MeasureJitter(Matrix4x4 projection)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4 val = projection;
			val.m02 -= 2f / (float)_renderWidth;
			val.m12 -= 2f / (float)_renderHeight;
			Vector4 val2 = default(Vector4);
			((Vector4)(ref val2))..ctor(0f, 0f, -1f, 1f);
			Vector4 val3 = GL.GetGPUProjectionMatrix(projection, true) * val2;
			Vector4 val4 = GL.GetGPUProjectionMatrix(val, true) * val2;
			_jitterScaleX = (val4.x / val4.w - val3.x / val3.w) * (float)_renderWidth * 0.5f;
			_jitterScaleY = (0f - (val4.y / val4.w - val3.y / val3.w)) * (float)_renderHeight * 0.5f;
			_jitterMeasured = true;
		}

		private static void CopyGlobal(CommandBuffer command, int property, RenderTargetIdentifier target)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Texture globalTexture = Shader.GetGlobalTexture(property);
			if (globalTexture != null)
			{
				command.Blit(globalTexture, target);
			}
			else
			{
				Plugin.Logger.ErrorOnce("framegen-input-missing", "The camera's depth or motion texture is not set; DLSS runs without it this frame.");
			}
		}

		private static RenderTexture? PresentedFrame()
		{
			if (!_active || _lastFrame != Time.frameCount)
			{
				return null;
			}
			if (_measureHud)
			{
				MeasureHud();
			}
			return _output;
		}

		private static void MeasureHud()
		{
			RenderTexture active = RenderTexture.active;
			Graphics.Blit((Texture)(object)Texture2D.blackTexture, _hudOnBlack, _hudMaterial);
			Graphics.Blit((Texture)(object)Texture2D.whiteTexture, _hudOnWhite, _hudMaterial);
			RenderTexture.active = active;
		}

		private static void CountLateFieldOfView()
		{
			if (_active && _lastFrame == Time.frameCount && !NativeObjects.Gone((Object)(object)_camera))
			{
				_fovFrames++;
				if (_camera.fieldOfView != _fovAtPreCull)
				{
					_fovLate++;
				}
			}
		}

		private static void Start(Camera camera)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Invalid comparison between Unknown and I4
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			if (_evaluate == null)
			{
				_evaluate = new CommandBuffer
				{
					name = "ForgeFrameGen DLSS"
				};
			}
			camera.AddCommandBuffer((CameraEvent)19, _evaluate);
			if ((Object)(object)_presenter == (Object)null || ((Il2CppObjectBase)_presenter).WasCollected)
			{
				GameObject val = new GameObject("ForgeFrameGen presenter");
				Object.DontDestroyOnLoad((Object)val);
				_presenter = val.AddComponent<Camera>();
				_presenter.cullingMask = 0;
				_presenter.clearFlags = (CameraClearFlags)4;
				_presenter.allowHDR = false;
				_presenter.allowMSAA = false;
				_presenter.useOcclusionCulling = false;
				_presenter.renderingPath = (RenderingPath)1;
				_presenterPointer = ((Il2CppObjectBase)_presenter).Pointer;
			}
			_cameraPointer = ((Il2CppObjectBase)camera).Pointer;
			_reversedDepth = SystemInfo.usesReversedZBuffer;
			_linearColour = (int)QualitySettings.activeColorSpace == 1;
			_jitterMeasured = false;
			camera.useJitteredProjectionMatrixForTransparentRendering = true;
			_presenter.depth = camera.depth + 0.001f;
			((Behaviour)_presenter).enabled = (_presenting = true);
			PlayerAgent local = Players.Local;
			object obj;
			if (local == null)
			{
				obj = null;
			}
			else
			{
				FPSCamera fPSCamera = local.FPSCamera;
				obj = ((fPSCamera != null) ? fPSCamera.postProcessing : null);
			}
			PostProcessingAdapter val2 = (PostProcessingAdapter)obj;
			_layer = ((val2 == null || ((Il2CppObjectBase)val2).WasCollected) ? null : val2.m_ppLayer);
			if ((Object)(object)_layer == (Object)null || val2.m_useOldStack)
			{
				Plugin.Logger.ErrorOnce("framegen-postprocess-missing", "The world camera has no post-processing v2 layer to take TAA off; DLSS runs, but the game's own anti-aliasing may run on top of it.");
			}
			else
			{
				_layerMode = _layer.antialiasingMode;
			}
			_hud = ((Component)camera).GetComponent<UI_Apply>();
			_hudMaterial = _hud.GetUIBlitterInstance();
			((Behaviour)_hud).enabled = false;
			_presentHud = ((Component)_presenter).gameObject.AddComponent<UI_Apply>();
			_presentHud.m_UIBlitterMaterial = _hud.m_UIBlitterMaterial;
			_presentHud.m_UIBlitterMaterial_Instance = _hudMaterial;
			((Behaviour)_presentHud).enabled = true;
			_standIn = Frame.StandInForHud("NAinfini.ForgeFrameGen", _hud, _presentHud, PresentedFrameStep);
			MipBias.Apply(Bias());
			_active = true;
			_reset = true;
		}

		private static void Stop()
		{
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			if (!_active)
			{
				return;
			}
			_active = false;
			_cameraPointer = IntPtr.Zero;
			if ((Object)(object)_camera != (Object)null && !((Il2CppObjectBase)_camera).WasCollected)
			{
				if (_evaluate != null)
				{
					_camera.RemoveCommandBuffer((CameraEvent)19, _evaluate);
				}
				if ((Object)(object)_world != (Object)null && (Object)(object)_camera.targetTexture != (Object)null && ((Il2CppObjectBase)_camera.targetTexture).Pointer == ((Il2CppObjectBase)_world).Pointer)
				{
					_camera.targetTexture = null;
				}
				_camera.ResetProjectionMatrix();
				_jittered = false;
				_camera.useJitteredProjectionMatrixForTransparentRendering = false;
			}
			ClusteredRendering current = ClusteredRendering.Current;
			if ((Object)(object)current != (Object)null)
			{
				current.OnResolutionchange(Math.Max(16, Screen.width), Math.Max(16, Screen.height));
			}
			_standIn?.Dispose();
			_standIn = null;
			if ((Object)(object)_hud != (Object)null && !((Il2CppObjectBase)_hud).WasCollected)
			{
				((Behaviour)_hud).enabled = true;
			}
			_hud = null;
			if ((Object)(object)_presenter != (Object)null && !((Il2CppObjectBase)_presenter).WasCollected)
			{
				((Behaviour)_presenter).enabled = false;
			}
			_presenting = false;
			if ((Object)(object)_presentHud != (Object)null && !((Il2CppObjectBase)_presentHud).WasCollected)
			{
				((Behaviour)_presentHud).enabled = false;
				_presentHud.m_UIBlitterMaterial_Instance = null;
				Object.Destroy((Object)(object)_presentHud);
			}
			_presentHud = null;
			_hudMaterial = null;
			if ((Object)(object)_layer != (Object)null && !((Il2CppObjectBase)_layer).WasCollected)
			{
				_layer.antialiasingMode = _layerMode;
			}
			_layer = null;
			ScreenSpace.Clear();
			MipBias.Restore();
			ReleaseTargets();
			DlssBridge.ReleaseFrameGeneration();
			SyncPreCull();
		}

		private static float Bias()
		{
			if (_renderWidth < _outputWidth)
			{
				return Mathf.Log((float)_renderWidth / (float)_outputWidth, 2f) - 1f;
			}
			return 0f;
		}

		private static void KeepStackAntiAliasingOff()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (_layer != null)
			{
				Antialiasing antialiasingMode = _layer.antialiasingMode;
				if ((int)antialiasingMode != 0)
				{
					_layerMode = antialiasingMode;
					_layer.antialiasingMode = (Antialiasing)0;
				}
			}
		}

		private static void EnsureTargets()
		{
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_world == (Object)null || ((Texture)_world).width != _renderWidth || ((Texture)_world).height != _renderHeight)
			{
				if ((Object)(object)_world != (Object)null && (Object)(object)_camera != (Object)null && !((Il2CppObjectBase)_camera).WasCollected && (Object)(object)_camera.targetTexture != (Object)null && ((Il2CppObjectBase)_camera.targetTexture).Pointer == ((Il2CppObjectBase)_world).Pointer)
				{
					_camera.targetTexture = null;
				}
				Release(ref _world);
				Release(ref _color);
				Release(ref _depth);
				Release(ref _motion);
				_world = Target(_renderWidth, _renderHeight, 24, (RenderTextureFormat)2, unordered: false, "ForgeFrameGen world", (RenderTextureReadWrite)1);
				_color = Target(_renderWidth, _renderHeight, 0, (RenderTextureFormat)2, unordered: false, "ForgeFrameGen colour", (RenderTextureReadWrite)1);
				_depth = Target(_renderWidth, _renderHeight, 0, (RenderTextureFormat)14, unordered: false, "ForgeFrameGen depth", (RenderTextureReadWrite)1);
				_motion = Target(_renderWidth, _renderHeight, 0, (RenderTextureFormat)13, unordered: false, "ForgeFrameGen motion", (RenderTextureReadWrite)1);
				IntPtr nativeTexturePtr = ((Texture)_color).GetNativeTexturePtr();
				IntPtr nativeTexturePtr2 = ((Texture)_depth).GetNativeTexturePtr();
				IntPtr nativeTexturePtr3 = ((Texture)_motion).GetNativeTexturePtr();
				_colorPointer = nativeTexturePtr;
				_depthPointer = nativeTexturePtr2;
				_motionPointer = nativeTexturePtr3;
				RenderTargetIdentifier colorId = default(RenderTargetIdentifier);
				((RenderTargetIdentifier)(ref colorId))..ctor((Texture)(object)_color);
				RenderTargetIdentifier depthId = default(RenderTargetIdentifier);
				((RenderTargetIdentifier)(ref depthId))..ctor((Texture)(object)_depth);
				RenderTargetIdentifier motionId = new RenderTargetIdentifier((Texture)(object)_motion);
				_colorId = colorId;
				_depthId = depthId;
				_motionId = motionId;
			}
			if ((Object)(object)_output == (Object)null || ((Texture)_output).width != _outputWidth || ((Texture)_output).height != _outputHeight)
			{
				Release(ref _output);
				_output = Target(_outputWidth, _outputHeight, 0, (RenderTextureFormat)2, unordered: true, "ForgeFrameGen output", (RenderTextureReadWrite)1);
				_outputPointer = ((Texture)_output).GetNativeTexturePtr();
			}
			if (!_measureHud || ((Object)(object)_hudOnBlack != (Object)null && (((Texture)_hudOnBlack).width != _outputWidth || ((Texture)_hudOnBlack).height != _outputHeight)))
			{
				Release(ref _hudOnBlack);
				Release(ref _hudOnWhite);
				_hudOnBlackPointer = (_hudOnWhitePointer = IntPtr.Zero);
			}
			if (_measureHud && (Object)(object)_hudOnBlack == (Object)null)
			{
				_hudOnBlack = Target(_outputWidth, _outputHeight, 0, (RenderTextureFormat)0, unordered: false, "ForgeFrameGen HUD on black", (RenderTextureReadWrite)2);
				_hudOnWhite = Target(_outputWidth, _outputHeight, 0, (RenderTextureFormat)0, unordered: false, "ForgeFrameGen HUD on white", (RenderTextureReadWrite)2);
				IntPtr nativeTexturePtr2 = ((Texture)_hudOnBlack).GetNativeTexturePtr();
				IntPtr nativeTexturePtr4 = ((Texture)_hudOnWhite).GetNativeTexturePtr();
				_hudOnBlackPointer = nativeTexturePtr2;
				_hudOnWhitePointer = nativeTexturePtr4;
			}
		}

		private static void ReleaseTargets()
		{
			if ((Object)(object)_world != (Object)null && (Object)(object)_camera != (Object)null && !((Il2CppObjectBase)_camera).WasCollected && (Object)(object)_camera.targetTexture != (Object)null && ((Il2CppObjectBase)_camera.targetTexture).Pointer == ((Il2CppObjectBase)_world).Pointer)
			{
				_camera.targetTexture = null;
			}
			Release(ref _world);
			Release(ref _color);
			Release(ref _depth);
			Release(ref _motion);
			Release(ref _output);
			Release(ref _hudOnBlack);
			Release(ref _hudOnWhite);
			_colorPointer = (_depthPointer = (_motionPointer = (_outputPointer = (_hudOnBlackPointer = (_hudOnWhitePointer = IntPtr.Zero)))));
		}

		private static RenderTexture Target(int width, int height, int depth, RenderTextureFormat format, bool unordered, string name, RenderTextureReadWrite space = (RenderTextureReadWrite)1)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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)
			//IL_002f: Expected O, but got Unknown
			//IL_0030: Expected O, but got Unknown
			RenderTexture val = new RenderTexture(width, height, depth, format, space)
			{
				name = name,
				enableRandomWrite = unordered,
				useMipMap = false
			};
			val.Create();
			Object.DontDestroyOnLoad((Object)val);
			return val;
		}

		private static void Release(ref RenderTexture? texture)
		{
			if ((Object)(object)texture != (Object)null && !((Il2CppObjectBase)texture).WasCollected)
			{
				texture.Release();
				Object.Destroy((Object)(object)texture);
			}
			texture = null;
		}

		private static float Halton(int index, int radix)
		{
			float num = 0f;
			float num2 = 1f / (float)radix;
			while (index > 0)
			{
				num += (float)(index % radix) * num2;
				index /= radix;
				num2 /= (float)radix;
			}
			return num;
		}

		private unsafe static DlssBridge.FrameGenerationParams* GenerationFrame(Camera camera, Matrix4x4 projection, float jitterX, float jitterY, bool reset, int frameNumber)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_0027: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: 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_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: 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_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
			DlssBridge.FrameGenerationParams* ptr = DlssBridge.NextGenerationFrame();
			ptr->Frame = frameNumber;
			ref DlssBridge.FrameGenerationParams reference = ref *ptr;
			int enabled;
			if (!Plugin.FrameGenerationOn)
			{
				enabled = 0;
			}
			else
			{
				eFocusState focus = Frame.Focus;
				bool flag = (((int)focus == 2 || (int)focus == 8 || (int)focus == 13) ? true : false);
				enabled = ((!flag) ? 1 : 2);
			}
			reference.Enabled = enabled;
			ptr->Depth = _depthPointer;
			ptr->Motion = _motionPointer;
			ptr->Hudless = _outputPointer;
			ptr->HudOnBlack = _hudOnBlackPointer;
			ptr->HudOnWhite = _hudOnWhitePointer;
			ptr->RenderWidth = (uint)_renderWidth;
			ptr->RenderHeight = (uint)_renderHeight;
			ptr->OutputWidth = (uint)_outputWidth;
			ptr->OutputHeight = (uint)_outputHeight;
			Matrix4x4 gPUProjectionMatrix = GL.GetGPUProjectionMatrix(projection, _flipRows == 0);
			Matrix4x4 worldToCameraMatrix = camera.worldToCameraMatrix;
			float m = worldToCameraMatrix.m00;
			float m2 = worldToCameraMatrix.m01;
			float m3 = worldToCameraMatrix.m02;
			float m4 = worldToCameraMatrix.m10;
			float m5 = worldToCameraMatrix.m11;
			float m6 = worldToCameraMatrix.m12;
			float num = 0f - worldToCameraMatrix.m20;
			float num2 = 0f - worldToCameraMatrix.m21;
			float num3 = 0f - worldToCameraMatrix.m22;
			float num4 = 0f - worldToCameraMatrix.m03;
			float num5 = 0f - worldToCameraMatrix.m13;
			float m7 = worldToCameraMatrix.m23;
			float num6 = m * num4 + m4 * num5 + num * m7;
			float num7 = m2 * num4 + m5 * num5 + num2 * m7;
			float num8 = m3 * num4 + m6 * num5 + num3 * m7;
			Matrix4x4 b = default(Matrix4x4);
			b.m00 = (b.m11 = (b.m22 = (b.m33 = 1f)));
			ref float m8 = ref b.m03;
			ref float m9 = ref b.m13;
			ref float m10 = ref b.m23;
			float num9 = num6;
			float num10 = num7;
			float num11 = num8;
			m8 = num9;
			m9 = num10;
			m10 = num11;
			Matrix4x4 val = Product(gPUProjectionMatrix, Product(worldToCameraMatrix, b));
			Matrix4x4 previousWorldToView;
			if (!_hasPrevious || reset)
			{
				previousWorldToView = worldToCameraMatrix;
				_previousViewToClip = gPUProjectionMatrix;
				_previousWorldToView = previousWorldToView;
			}
			Matrix4x4 val2 = Product(_previousViewToClip, Product(_previousWorldToView, b));
			Unsafe.Write(&ptr->ViewToClip, gPUProjectionMatrix);
			Unsafe.Write(&ptr->ClipToView, Inverse(gPUProjectionMatrix));
			Unsafe.Write(&ptr->ClipToPrevClip, Product(val2, Inverse(val)));
			Unsafe.Write(&ptr->PrevClipToClip, Product(val, Inverse(val2)));
			previousWorldToView = worldToCameraMatrix;
			_previousViewToClip = gPUProjectionMatrix;
			_previousWorldToView = previousWorldToView;
			_hasPrevious = true;
			float num12 = ((_flipRows != 0) ? (-1f) : 1f);
			ptr->JitterX = jitterX;
			ptr->JitterY = jitterY * num12;
			ptr->MotionScaleX = -1f * _signMotionX;
			ptr->MotionScaleY = (0f - num12) * _signMotionY;
			m9 = ref ((Vector3)(&ptr->CameraPosition)).x;
			m8 = ref ((Vector3)(&ptr->CameraPosition)).y;
			float* z = &((Vector3)(&ptr->CameraPosition)).z;
			num11 = num6;
			num10 = num7;
			num9 = num8;
			m9 = num11;
			m8 = num10;
			*z = num9;
			m8 = ref ((Vector3)(&ptr->CameraUp)).x;
			m9 = ref ((Vector3)(&ptr->CameraUp)).y;
			float* z2 = &((Vector3)(&ptr->CameraUp)).z;
			num9 = m4;
			num10 = m5;
			num11 = m6;
			m8 = num9;
			m9 = num10;
			*z2 = num11;
			m9 = ref ((Vector3)(&ptr->CameraRight)).x;
			m8 = ref ((Vector3)(&ptr->CameraRight)).y;
			float* z3 = &((Vector3)(&ptr->CameraRight)).z;
			num11 = m;
			num10 = m2;
			num9 = m3;
			m9 = num11;
			m8 = num10;
			*z3 = num9;
			m8 = ref ((Vector3)(&ptr->CameraForward)).x;
			m9 = ref ((Vector3)(&ptr->CameraForward)).y;
			float* z4 = &((Vector3)(&ptr->CameraForward)).z;
			num9 = num;
			num10 = num2;
			num11 = num3;
			m8 = num9;
			m9 = num10;
			*z4 = num11;
			m9 = ref ptr->CameraNear;
			m8 = ref ptr->CameraFar;
			float* cameraFov = &ptr->CameraFov;
			(float, float, float) tuple = Planes(projection);
			m9 = tuple.Item1;
			m8 = tuple.Item2;
			*cameraFov = tuple.Item3;
			ptr->CameraAspect = projection.m11 / projection.m00;
			ptr->Reset = (reset ? 1 : 0);
			ptr->DepthInverted = (_reversedDepth ? 1 : 0);
			ptr->FlipRows = _flipRows;
			ptr->EncodeSrgb = (_linearColour ? 1 : 0);
			return ptr;
		}

		private static (float Near, float Far, float Fov) Planes(Matrix4x4 projection)
		{
			//IL_0000: 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)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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)
			return (Near: projection.m23 / (projection.m22 - 1f), Far: projection.m23 / (projection.m22 + 1f), Fov: 2f * MathF.Atan(1f / projection.m11));
		}

		private static Matrix4x4 Product(Matrix4x4 a, Matrix4x4 b)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4 matrix4x = Matrix4x4.Multiply((Matrix4x4)b, (Matrix4x4)a);
			return (Matrix4x4)matrix4x;
		}

		private static Matrix4x4 Inverse(Matrix4x4 matrix)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (!Matrix4x4.Invert((Matrix4x4)matrix, out var result))
			{
				return default(Matrix4x4);
			}
			return (Matrix4x4)result;
		}

		internal static string FlipRows(int flip)
		{
			_flipRows = flip;
			_reset = true;
			return "flipRows=" + flip + " " + DlssBridge.FrameGeneration();
		}

		internal static string CommandBuffers()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			Camera val = WorldCamera();
			if ((Object)(object)val == (Object)null)
			{
				return "no world camera";
			}
			StringBuilder stringBuilder = new StringBuilder("count=" + val.commandBufferCount);
			foreach (CameraEvent value in Enum.GetValues(typeof(CameraEvent)))
			{
				Il2CppReferenceArray<CommandBuffer> commandBuffers = val.GetCommandBuffers(value);
				if (commandBuffers == null || ((Il2CppArrayBase<CommandBuffer>)(object)commandBuffers).Length == 0)
				{
					continue;
				}
				stringBuilder.Append(" | ").Append(((object)value/*cast due to .constrained prefix*/).ToString()).Append(':');
				foreach (CommandBuffer item in (Il2CppArrayBase<CommandBuffer>)(object)commandBuffers)
				{
					stringBuilder.Append(" [").Append(item.name).Append(' ')
						.Append(item.sizeInBytes.ToString())
						.Append("B]");
				}
			}
			return stringBuilder.ToString();
		}

		internal static string HoldBuffer(string name)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_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_00b2: Unknown result type (might be due to invalid IL or missing references)
			Camera val = WorldCamera();
			if ((Object)(object)val == (Object)null)
			{
				return "no world camera";
			}
			if (_held != null)
			{
				val.AddCommandBuffer(_heldAt, _held);
				_held = null;
			}
			if (name.Length == 0)
			{
				return "put back; " + CommandBuffers();
			}
			foreach (CameraEvent value in Enum.GetValues(typeof(CameraEvent)))
			{
				Il2CppReferenceArray<CommandBuffer> commandBuffers = val.GetCommandBuffers(value);
				if (commandBuffers == null)
				{
					continue;
				}
				foreach (CommandBuffer item in (Il2CppArrayBase<CommandBuffer>)(object)commandBuffers)
				{
					if (!(item.name != name))
					{
						val.RemoveCommandBuffer(value, item);
						CameraEvent heldAt = value;
						_held = item;
						_heldAt = heldAt;
						return "taken " + name + " from " + ((object)value/*cast due to .constrained prefix*/).ToString();
					}
				}
			}
			return "no buffer named " + name;
		}

		internal static string OutlineNearestEnemy()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknow