Decompiled source of LethalGraphics v1.0.1

plugins/LethalGraphics.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalGraphics.Configuration;
using LethalGraphics.Core;
using LethalGraphics.Lighting;
using LethalGraphics.Lighting.Patches;
using LethalGraphics.Upscaling;
using LethalGraphics.Upscaling.FSR2;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.RenderGraphModule;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalGraphics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("LethalGraphics")]
[assembly: AssemblyTitle("LethalGraphics")]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalGraphics
{
	[BepInPlugin("okatodev.LethalGraphics", "LethalGraphics", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Init(((BaseUnityPlugin)this).Config);
			ExternalUpscalerManager.Initialize();
			_harmony = new Harmony("okato.lethallightning");
			_harmony.PatchAll();
			RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
			if (ModConfig.UpscalerDebug.Value)
			{
				Log.LogInfo((object)$"LethalLightning initialized. Render pipeline: {GraphicsSettings.renderPipelineAsset}");
			}
		}

		private void Update()
		{
			ExternalUpscalerManager.Update();
		}

		private static void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			if ((Object)(object)camera == (Object)null || (int)camera.cameraType != 1 || !CameraIdentity.IsPrimaryViewCamera(camera) || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				return;
			}
			HDAdditionalCameraData val = ((Component)camera).GetComponent<HDAdditionalCameraData>();
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)camera).gameObject.AddComponent<HDAdditionalCameraData>();
				if (ModConfig.Debug.Value)
				{
					Log.LogInfo((object)("Added missing HDAdditionalCameraData to camera '" + ((Object)camera).name + "'."));
				}
			}
			val.allowDynamicResolution = true;
			ResolutionManager.Apply(camera);
		}
	}
}
namespace LethalGraphics.Upscaling
{
	internal static class ExternalUpscalerManager
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static PerformDynamicRes <0>__GetDynamicResolutionScalePercentage;
		}

		private static bool _initialized;

		private static UpscalerMode _lastMode;

		private static UpscalerQuality _lastQuality;

		public static bool IsInitialized => _initialized;

		public static UpscalerMode Mode
		{
			get
			{
				if (ModConfig.Upscaler == null)
				{
					return UpscalerMode.Off;
				}
				return ModConfig.Upscaler.Value;
			}
		}

		public static UpscalerQuality Quality
		{
			get
			{
				if (ModConfig.UpscalerQuality == null)
				{
					return UpscalerQuality.Balanced;
				}
				return ModConfig.UpscalerQuality.Value;
			}
		}

		public static bool FSR2Requested => Mode == UpscalerMode.FSR2;

		private static bool DebugLogging
		{
			get
			{
				if (ModConfig.UpscalerDebug != null)
				{
					return ModConfig.UpscalerDebug.Value;
				}
				return false;
			}
		}

		public static void Initialize()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			if (!_initialized)
			{
				_initialized = true;
				_lastMode = Mode;
				_lastQuality = Quality;
				ConfigureDynamicResolution();
				object obj = <>O.<0>__GetDynamicResolutionScalePercentage;
				if (obj == null)
				{
					PerformDynamicRes val = GetDynamicResolutionScalePercentage;
					<>O.<0>__GetDynamicResolutionScalePercentage = val;
					obj = (object)val;
				}
				DynamicResolutionHandler.SetDynamicResScaler((PerformDynamicRes)obj, (DynamicResScalePolicyType)0);
				if (DebugLogging)
				{
					Plugin.Log.LogInfo((object)$"Upscaler manager initialized. Mode: {Mode}, Quality: {Quality}.");
				}
			}
		}

		private static void ConfigureDynamicResolution()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			RenderPipelineAsset renderPipeline = QualitySettings.renderPipeline;
			HDRenderPipelineAsset val = (HDRenderPipelineAsset)(object)((renderPipeline is HDRenderPipelineAsset) ? renderPipeline : null);
			if ((Object)(object)val == (Object)null)
			{
				RenderPipelineAsset renderPipelineAsset = GraphicsSettings.renderPipelineAsset;
				val = (HDRenderPipelineAsset)(object)((renderPipelineAsset is HDRenderPipelineAsset) ? renderPipelineAsset : null);
			}
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"FSR2 could not find the active HDRenderPipelineAsset to configure Dynamic Resolution.");
				return;
			}
			RenderPipelineSettings currentPlatformRenderPipelineSettings = val.currentPlatformRenderPipelineSettings;
			GlobalDynamicResolutionSettings dynamicResolutionSettings = currentPlatformRenderPipelineSettings.dynamicResolutionSettings;
			dynamicResolutionSettings.enabled = true;
			dynamicResolutionSettings.dynResType = (DynamicResolutionType)0;
			dynamicResolutionSettings.forceResolution = false;
			dynamicResolutionSettings.upsampleFilter = (DynamicResUpscaleFilter)4;
			dynamicResolutionSettings.minPercentage = Mathf.Min(dynamicResolutionSettings.minPercentage, 25f);
			dynamicResolutionSettings.maxPercentage = Mathf.Max(dynamicResolutionSettings.maxPercentage, 100f);
			currentPlatformRenderPipelineSettings.dynamicResolutionSettings = dynamicResolutionSettings;
			val.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings;
		}

		private static float GetDynamicResolutionScalePercentage()
		{
			if (Mode != UpscalerMode.FSR2)
			{
				return 100f;
			}
			return Quality switch
			{
				UpscalerQuality.NativeAA => 100f, 
				UpscalerQuality.Quality => 66.6f, 
				UpscalerQuality.Balanced => 58.8f, 
				UpscalerQuality.Performance => 50f, 
				UpscalerQuality.UltraPerformance => 33.3f, 
				_ => 100f, 
			};
		}

		public static void Update()
		{
			if (!_initialized)
			{
				return;
			}
			UpscalerMode mode = Mode;
			UpscalerQuality quality = Quality;
			if (mode != _lastMode || quality != _lastQuality)
			{
				_lastMode = mode;
				_lastQuality = quality;
				FSR2Runtime.Cleanup();
				if (DebugLogging)
				{
					Plugin.Log.LogInfo((object)$"Upscaler configuration changed. Mode: {mode}, Quality: {quality}.");
				}
			}
			DynamicResolutionHandler.instance.upsamplerSchedule = (UpsamplerScheduleType)((!FSR2Requested) ? 2 : 0);
		}

		public static void Cleanup()
		{
			if (_initialized)
			{
				FSR2Runtime.Cleanup();
				_initialized = false;
			}
		}
	}
	public static class ResolutionManager
	{
		private static readonly HashSet<int> _configuredCameras = new HashSet<int>();

		private static RenderTexture _scaledTarget;

		private static int _scaledWidth;

		private static int _scaledHeight;

		public static void Apply(Camera camera)
		{
			if (!((Object)(object)camera == (Object)null))
			{
				int instanceID = ((Object)camera).GetInstanceID();
				if (_configuredCameras.Add(instanceID))
				{
					ApplyAntiAliasing(camera);
				}
				else
				{
					RefreshAntiAliasingIfNeeded(camera);
				}
				ApplyResolutionScale(camera);
			}
		}

		private static void ApplyAntiAliasing(Camera camera)
		{
			HDAdditionalCameraData component = ((Component)camera).GetComponent<HDAdditionalCameraData>();
			if (!((Object)(object)component == (Object)null))
			{
				ApplyMode(component);
			}
		}

		private static void RefreshAntiAliasingIfNeeded(Camera camera)
		{
			HDAdditionalCameraData component = ((Component)camera).GetComponent<HDAdditionalCameraData>();
			if (!((Object)(object)component == (Object)null))
			{
				ApplyMode(component);
			}
		}

		private static void ApplyMode(HDAdditionalCameraData cameraData)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			if (ExternalUpscalerManager.FSR2Requested)
			{
				cameraData.antialiasing = (AntialiasingMode)0;
				return;
			}
			string value = ModConfig.AntiAliasingType.Value;
			if (string.Equals(value, "TAA", StringComparison.OrdinalIgnoreCase))
			{
				cameraData.antialiasing = (AntialiasingMode)2;
				cameraData.TAAQuality = (TAAQualityLevel)2;
				cameraData.taaSharpenStrength = ModConfig.TaaSharpening.Value;
				cameraData.taaHistorySharpening = ModConfig.TaaHistorySharpening.Value;
				cameraData.taaBaseBlendFactor = ModConfig.TaaMotionClamping.Value;
				cameraData.taaAntiFlicker = ModConfig.TaaAntiFlicker.Value;
			}
			else if (string.Equals(value, "SMAA", StringComparison.OrdinalIgnoreCase))
			{
				cameraData.antialiasing = (AntialiasingMode)3;
				cameraData.SMAAQuality = (SMAAQualityLevel)2;
			}
			else if (string.Equals(value, "FXAA", StringComparison.OrdinalIgnoreCase))
			{
				cameraData.antialiasing = (AntialiasingMode)1;
			}
			else
			{
				cameraData.antialiasing = (AntialiasingMode)0;
			}
		}

		private static void ApplyResolutionScale(Camera camera)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			if (ModConfig.UseNativeResolution.Value)
			{
				ReleaseScaledTarget();
				ApplyNativeResolutionOverride(camera);
				return;
			}
			RenderTexture targetTexture = camera.targetTexture;
			if ((Object)(object)targetTexture == (Object)null || ((Object)targetTexture).name == "LethalLightning_ScaledRT")
			{
				return;
			}
			float num = Mathf.Clamp(ModConfig.ResolutionScale.Value, 1f, 2f);
			if (Mathf.Approximately(num, 1f))
			{
				return;
			}
			int num2 = Mathf.Max(1, Mathf.RoundToInt((float)Screen.width * num));
			int num3 = Mathf.Max(1, Mathf.RoundToInt((float)Screen.height * num));
			if ((Object)(object)_scaledTarget != (Object)null && _scaledWidth == num2 && _scaledHeight == num3)
			{
				camera.targetTexture = _scaledTarget;
				AssignPlayerScreenTexture(_scaledTarget);
				return;
			}
			ReleaseScaledTarget();
			RenderTextureDescriptor descriptor = targetTexture.descriptor;
			((RenderTextureDescriptor)(ref descriptor)).width = num2;
			((RenderTextureDescriptor)(ref descriptor)).height = num3;
			((RenderTextureDescriptor)(ref descriptor)).msaaSamples = 1;
			_scaledTarget = new RenderTexture(descriptor)
			{
				filterMode = (FilterMode)1,
				name = "LethalLightning_ScaledRT"
			};
			_scaledTarget.Create();
			_scaledWidth = num2;
			_scaledHeight = num3;
			camera.targetTexture = _scaledTarget;
			AssignPlayerScreenTexture(_scaledTarget);
			if (ModConfig.Debug.Value)
			{
				Plugin.Log.LogInfo((object)$"Internal resolution scaled to {num2}x{num3}.");
			}
		}

		private static void ApplyNativeResolutionOverride(Camera camera)
		{
			RenderTexture targetTexture = camera.targetTexture;
			if ((Object)(object)targetTexture == (Object)null)
			{
				return;
			}
			int num = Mathf.Max(1, Screen.width);
			int num2 = Mathf.Max(1, Screen.height);
			if (((Texture)targetTexture).width == num && ((Texture)targetTexture).height == num2)
			{
				AssignPlayerScreenTexture(targetTexture);
				return;
			}
			if (ModConfig.Debug.Value)
			{
				Plugin.Log.LogInfo((object)$"Resizing camera render target in place from {((Texture)targetTexture).width}x{((Texture)targetTexture).height} to native {num}x{num2}.");
			}
			targetTexture.Release();
			((Texture)targetTexture).width = num;
			((Texture)targetTexture).height = num2;
			targetTexture.Create();
			camera.aspect = (float)num / (float)num2;
			AssignPlayerScreenTexture(targetTexture);
		}

		private static void AssignPlayerScreenTexture(RenderTexture texture)
		{
			if ((Object)(object)HUDManager.Instance != (Object)null && (Object)(object)HUDManager.Instance.playerScreenTexture != (Object)null)
			{
				HUDManager.Instance.playerScreenTexture.texture = (Texture)(object)texture;
			}
		}

		private static void ReleaseScaledTarget()
		{
			if (!((Object)(object)_scaledTarget == (Object)null))
			{
				_scaledTarget.Release();
				Object.Destroy((Object)(object)_scaledTarget);
				_scaledTarget = null;
				_scaledWidth = 0;
				_scaledHeight = 0;
			}
		}
	}
}
namespace LethalGraphics.Upscaling.FSR2
{
	internal static class FSR2PatchDebug
	{
		public static bool Enabled
		{
			get
			{
				if (ModConfig.UpscalerDebug != null)
				{
					return ModConfig.UpscalerDebug.Value;
				}
				return false;
			}
		}
	}
	[HarmonyPatch]
	internal static class FSR2ScheduleSyncPatch
	{
		private static MethodBase _targetMethod;

		public static MethodBase TargetMethod()
		{
			if (_targetMethod != null)
			{
				return _targetMethod;
			}
			MethodInfo[] methods = typeof(HDRenderPipeline).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (!(methodInfo.Name != "RenderPostProcess"))
				{
					ParameterInfo[] parameters = methodInfo.GetParameters();
					if (parameters.Length == 11 && !(parameters[0].ParameterType != typeof(RenderGraph)) && parameters[1].ParameterType.IsByRef && !(parameters[2].ParameterType != typeof(TextureHandle)) && !(parameters[7].ParameterType != typeof(CullingResults)) && !(parameters[8].ParameterType != typeof(HDCamera)))
					{
						_targetMethod = methodInfo;
						return _targetMethod;
					}
				}
			}
			Plugin.Log.LogError((object)"FSR2 could not find HDRenderPipeline.RenderPostProcess for schedule sync.");
			return null;
		}

		public static void Prefix(object[] __args)
		{
			if (__args != null && __args.Length >= 9)
			{
				object obj = __args[8];
				HDCamera val = (HDCamera)((obj is HDCamera) ? obj : null);
				if (val != null && !((Object)(object)val.camera == (Object)null) && CameraIdentity.IsPrimaryViewCamera(val.camera))
				{
					DynamicResolutionHandler.instance.upsamplerSchedule = (UpsamplerScheduleType)((!ExternalUpscalerManager.FSR2Requested) ? 2 : 0);
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class FSR2DLSSPassPatch
	{
		private static MethodBase _targetMethod;

		private static readonly HashSet<string> _loggedOtherCameras = new HashSet<string>();

		public static MethodBase TargetMethod()
		{
			if (_targetMethod != null)
			{
				return _targetMethod;
			}
			MethodInfo[] methods = typeof(HDRenderPipeline).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (!(methodInfo.Name != "DoDLSSPasses"))
				{
					ParameterInfo[] parameters = methodInfo.GetParameters();
					if (parameters.Length == 6 && !(parameters[0].ParameterType != typeof(RenderGraph)) && !(parameters[1].ParameterType != typeof(HDCamera)) && !(parameters[2].ParameterType != typeof(UpsamplerScheduleType)) && !(parameters[3].ParameterType != typeof(TextureHandle)) && !(parameters[4].ParameterType != typeof(TextureHandle)) && !(parameters[5].ParameterType != typeof(TextureHandle)))
					{
						_targetMethod = methodInfo;
						return _targetMethod;
					}
				}
			}
			Plugin.Log.LogError((object)"FSR2 could not find HDRenderPipeline.DoDLSSPasses.");
			return null;
		}

		public static bool Prefix(RenderGraph renderGraph, HDCamera hdCamera, UpsamplerScheduleType upsamplerSchedule, TextureHandle source, TextureHandle depthBuffer, TextureHandle motionVectors, ref TextureHandle __result)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if ((int)upsamplerSchedule != 0)
			{
				return true;
			}
			if (renderGraph == null || hdCamera == null || (Object)(object)hdCamera.camera == (Object)null)
			{
				return true;
			}
			if (!CameraIdentity.IsPrimaryViewCamera(hdCamera.camera))
			{
				if (ModConfig.Debug.Value && _loggedOtherCameras.Add(((Object)hdCamera.camera).name))
				{
					Plugin.Log.LogInfo((object)("FSR2 DoDLSSPasses(BeforePost) reached for a camera not in the primary-view allowlist '" + ((Object)hdCamera.camera).name + "'."));
				}
				return true;
			}
			if (!ExternalUpscalerManager.FSR2Requested)
			{
				return true;
			}
			if (!FSR2Runtime.Available)
			{
				return true;
			}
			__result = FSR2RenderBridge.Replace(renderGraph, hdCamera, source, depthBuffer, motionVectors);
			return false;
		}
	}
	[HarmonyPatch]
	internal static class FSR2TransparencyCapturePatch
	{
		private static MethodBase _targetMethod;

		public static MethodBase TargetMethod()
		{
			if (_targetMethod != null)
			{
				return _targetMethod;
			}
			MethodInfo[] methods = typeof(HDRenderPipeline).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (!(methodInfo.Name != "RenderTransparency"))
				{
					ParameterInfo[] parameters = methodInfo.GetParameters();
					if (parameters.Length == 16 && !(parameters[0].ParameterType != typeof(RenderGraph)) && !(parameters[1].ParameterType != typeof(HDCamera)) && !(parameters[2].ParameterType != typeof(TextureHandle)) && !(parameters[3].ParameterType != typeof(TextureHandle)) && !(parameters[8].ParameterType != typeof(Texture)))
					{
						_targetMethod = methodInfo;
						return _targetMethod;
					}
				}
			}
			Plugin.Log.LogError((object)"FSR2 could not find HDRenderPipeline.RenderTransparency.");
			return null;
		}

		public static void Prefix(object[] __args)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (__args != null && __args.Length >= 3)
			{
				object obj = __args[1];
				HDCamera val = (HDCamera)((obj is HDCamera) ? obj : null);
				if (val != null && !((Object)(object)val.camera == (Object)null) && CameraIdentity.IsPrimaryViewCamera(val.camera) && __args[2] is TextureHandle colorOpaqueOnly)
				{
					FSR2RenderBridge.CaptureColorOpaqueOnly(colorOpaqueOnly);
				}
			}
		}
	}
	[HarmonyPatch(typeof(HDCamera), "RequiresCameraJitter")]
	internal static class FSR2ForceCameraJitterPatch
	{
		public static void Postfix(HDCamera __instance, ref bool __result)
		{
			if (!__result && __instance != null && !((Object)(object)__instance.camera == (Object)null) && CameraIdentity.IsPrimaryViewCamera(__instance.camera) && ExternalUpscalerManager.FSR2Requested && FSR2Runtime.Available)
			{
				__result = true;
			}
		}
	}
	internal static class FSR2Native
	{
		internal struct InitializeParam
		{
			public uint Flags;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
			public uint[] DisplaySize;
		}

		internal struct GenReactiveParam
		{
			public IntPtr ColorOpaqueOnly;

			public IntPtr ColorPreUpscale;

			public IntPtr OutReactive;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
			public uint[] RenderSize;

			public float Scale;

			public float CutoffThreshold;

			public float BinaryValue;

			public uint Flags;
		}

		internal struct ExecuteParam
		{
			public IntPtr Color;

			public IntPtr Depth;

			public IntPtr MotionVectors;

			public IntPtr Reactive;

			public IntPtr TransparencyAndComposition;

			public IntPtr Output;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
			public float[] MotionVectorScale;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
			public uint[] RenderSize;

			[MarshalAs(UnmanagedType.I1)]
			public bool EnableSharpening;

			public float Sharpness;

			public float FrameTimeDeltaInSec;

			public float CameraNear;

			public float CameraFar;

			public float CameraFov;

			public float PreExposure;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
			public float[] JitterOffset;

			public byte Reset;
		}

		private const string LibraryName = "fsr2-unity-plugin";

		[DllImport("fsr2-unity-plugin", CallingConvention = CallingConvention.Cdecl)]
		internal static extern void FSR2Initialize(InitializeParam initParam);

		[DllImport("fsr2-unity-plugin", CallingConvention = CallingConvention.Cdecl)]
		internal static extern void FSR2GetProjectionMatrixJitterOffset(uint renderWidth, uint renderHeight, uint displayWidth, [Out] float[] jitterOffset);

		[DllImport("fsr2-unity-plugin", CallingConvention = CallingConvention.Cdecl)]
		internal static extern void FSR2GenReactiveMask(GenReactiveParam reactiveParam);

		[DllImport("fsr2-unity-plugin", CallingConvention = CallingConvention.Cdecl)]
		internal static extern void FSR2Execute(ExecuteParam executeParam);

		[DllImport("fsr2-unity-plugin", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr FSR2GetRenderEventFunc();
	}
	internal static class FSR2RenderBridge
	{
		private sealed class PassData
		{
			public TextureHandle Color;

			public TextureHandle Depth;

			public TextureHandle MotionVectors;

			public TextureHandle Output;

			public int RenderWidth;

			public int RenderHeight;

			public int DisplayWidth;

			public int DisplayHeight;

			public float CameraNear;

			public float CameraFar;

			public float CameraFov;

			public float JitterX;

			public float JitterY;

			public HDCamera HdCamera;

			public TextureHandle ColorOpaqueOnly;

			public bool HasReactiveMask;

			public TextureHandle Reactive;

			public float DeltaTime;

			public float PreExposure;
		}

		private static RenderTexture _privateColor;

		private static RenderTexture _privateDepth;

		private static RenderTexture _privateMotion;

		private static RenderTexture _privateColorOpaqueOnly;

		private static RenderTexture _privateReactive;

		private static RenderTexture _privateOutput;

		private static TextureHandle _capturedColorOpaqueOnly;

		private static bool _colorOpaqueOnlyCaptured;

		private static readonly ProfilingSampler ProfilingSampler = new ProfilingSampler("FSR2");

		private static MethodInfo _getPostprocessUpsampledOutputHandle;

		private static MethodInfo _setCurrentResolutionGroup;

		private static object _afterDynamicResUpscaleValue;

		private static bool _pipelineReflectionInitialized;

		private static FieldInfo _finalViewportField;

		private static bool _finalViewportFieldInitialized;

		private static FieldInfo _resetPostProcessingHistoryField;

		private static bool _resetFieldInitialized;

		private static bool _exposureReflectionInitialized;

		private static bool _exposureReflectionValid;

		private static float _cachedHdrpExposure = 1f;

		private static bool _exposureReadbackPending;

		private static int _drsEnabledCameraInstanceId = int.MinValue;

		private static bool DebugLogging
		{
			get
			{
				if (ModConfig.UpscalerDebug != null)
				{
					return ModConfig.UpscalerDebug.Value;
				}
				return false;
			}
		}

		private static RenderTexture GetOrCreatePrivate(ref RenderTexture cache, RenderTexture source, bool enableRandomWrite, string name)
		{
			//IL_0065: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			if ((Object)(object)cache != (Object)null && ((Texture)cache).width == ((Texture)source).width && ((Texture)cache).height == ((Texture)source).height && cache.graphicsFormat == source.graphicsFormat && cache.depthStencilFormat == source.depthStencilFormat && cache.enableRandomWrite == enableRandomWrite)
			{
				return cache;
			}
			ReleasePrivate(ref cache);
			RenderTextureDescriptor descriptor = source.descriptor;
			((RenderTextureDescriptor)(ref descriptor)).enableRandomWrite = enableRandomWrite;
			((RenderTextureDescriptor)(ref descriptor)).msaaSamples = 1;
			cache = new RenderTexture(descriptor)
			{
				name = name
			};
			cache.Create();
			return cache;
		}

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

		public static void CaptureColorOpaqueOnly(TextureHandle colorOpaqueOnly)
		{
			//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)
			_capturedColorOpaqueOnly = colorOpaqueOnly;
			_colorOpaqueOnlyCaptured = true;
		}

		private static bool EnsurePipelineReflection()
		{
			if (_pipelineReflectionInitialized)
			{
				if (_getPostprocessUpsampledOutputHandle != null)
				{
					return _setCurrentResolutionGroup != null;
				}
				return false;
			}
			_pipelineReflectionInitialized = true;
			_getPostprocessUpsampledOutputHandle = typeof(HDRenderPipeline).GetMethod("GetPostprocessUpsampledOutputHandle", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (_getPostprocessUpsampledOutputHandle == null)
			{
				Plugin.Log.LogError((object)"FSR2 could not find HDRenderPipeline.GetPostprocessUpsampledOutputHandle via reflection.");
				return false;
			}
			_setCurrentResolutionGroup = typeof(HDRenderPipeline).GetMethod("SetCurrentResolutionGroup", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (_setCurrentResolutionGroup == null)
			{
				Plugin.Log.LogError((object)"FSR2 could not find HDRenderPipeline.SetCurrentResolutionGroup via reflection.");
				return false;
			}
			ParameterInfo[] parameters = _setCurrentResolutionGroup.GetParameters();
			if (parameters.Length != 3)
			{
				Plugin.Log.LogError((object)$"FSR2 SetCurrentResolutionGroup has unexpected parameter count: {parameters.Length}.");
				_setCurrentResolutionGroup = null;
				return false;
			}
			Type parameterType = parameters[2].ParameterType;
			try
			{
				_afterDynamicResUpscaleValue = Enum.Parse(parameterType, "AfterDynamicResUpscale");
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 could not resolve ResolutionGroup.AfterDynamicResUpscale: {arg}");
				_setCurrentResolutionGroup = null;
				return false;
			}
			return true;
		}

		private static bool TryGetUpsampledOutputHandle(HDRenderPipeline pipeline, RenderGraph renderGraph, HDCamera hdCamera, out TextureHandle output)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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)
			output = TextureHandle.nullHandle;
			if (!EnsurePipelineReflection())
			{
				return false;
			}
			try
			{
				if (_getPostprocessUpsampledOutputHandle.Invoke(pipeline, new object[3] { hdCamera, renderGraph, "FSR2 Output" }) is TextureHandle val)
				{
					output = val;
					return ((TextureHandle)(ref output)).IsValid();
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 GetPostprocessUpsampledOutputHandle failed: {arg}");
			}
			return false;
		}

		private static void MarkAfterDynamicResUpscale(HDRenderPipeline pipeline, RenderGraph renderGraph, HDCamera hdCamera)
		{
			if (_setCurrentResolutionGroup == null)
			{
				return;
			}
			try
			{
				_setCurrentResolutionGroup.Invoke(pipeline, new object[3] { renderGraph, hdCamera, _afterDynamicResUpscaleValue });
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 SetCurrentResolutionGroup failed: {arg}");
			}
		}

		private static bool TryGetFinalViewport(HDCamera hdCamera, out Rect viewport)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			viewport = default(Rect);
			if (!_finalViewportFieldInitialized)
			{
				_finalViewportField = typeof(HDCamera).GetField("finalViewport", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				_finalViewportFieldInitialized = true;
				if (_finalViewportField == null)
				{
					Plugin.Log.LogError((object)"FSR2 could not find HDCamera.finalViewport via reflection.");
				}
			}
			if (_finalViewportField == null)
			{
				return false;
			}
			try
			{
				if (_finalViewportField.GetValue(hdCamera) is Rect val)
				{
					viewport = val;
					return true;
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 failed to read HDCamera.finalViewport: {arg}");
			}
			return false;
		}

		private static bool TryConsumeHdrpResetSignal(HDCamera hdCamera)
		{
			if (!_resetFieldInitialized)
			{
				_resetPostProcessingHistoryField = typeof(HDCamera).GetField("resetPostProcessingHistory", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				_resetFieldInitialized = true;
				if (_resetPostProcessingHistoryField == null)
				{
					Plugin.Log.LogWarning((object)"FSR2 could not find HDCamera.resetPostProcessingHistory via reflection.");
				}
			}
			if (_resetPostProcessingHistoryField == null)
			{
				return false;
			}
			try
			{
				object value = _resetPostProcessingHistoryField.GetValue(hdCamera);
				bool flag = default(bool);
				int num;
				if (value is bool)
				{
					flag = (bool)value;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 failed to read resetPostProcessingHistory: {arg}");
				return false;
			}
		}

		private static object GetMemberValue(object instance, string name)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(name, bindingAttr);
			if (field != null)
			{
				return field.GetValue(instance);
			}
			PropertyInfo property = type.GetProperty(name, bindingAttr);
			if (property != null)
			{
				return property.GetValue(instance);
			}
			return null;
		}

		private static bool EnsureExposureReflection(HDCamera hdCamera)
		{
			if (_exposureReflectionInitialized)
			{
				return _exposureReflectionValid;
			}
			_exposureReflectionInitialized = true;
			object memberValue = GetMemberValue(hdCamera, "currentExposureTextures");
			if (memberValue == null)
			{
				Plugin.Log.LogWarning((object)"FSR2 could not find HDCamera.currentExposureTextures via reflection - FSR2 will not receive HDRP's real exposure value.");
				return false;
			}
			if (!(GetMemberValue(memberValue, "current") is RTHandle))
			{
				Plugin.Log.LogWarning((object)"FSR2 could not find a valid 'current' RTHandle on HDCamera's exposure textures - FSR2 will not receive HDRP's real exposure value.");
				return false;
			}
			_exposureReflectionValid = true;
			return true;
		}

		public static void RequestExposureReadback(HDCamera hdCamera)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			if (_exposureReadbackPending || hdCamera == null || !EnsureExposureReflection(hdCamera))
			{
				return;
			}
			object memberValue = GetMemberValue(GetMemberValue(hdCamera, "currentExposureTextures"), "current");
			RTHandle val = (RTHandle)((memberValue is RTHandle) ? memberValue : null);
			if (val != null)
			{
				RenderTexture rt = val.rt;
				if (!((Object)(object)rt == (Object)null))
				{
					_exposureReadbackPending = true;
					AsyncGPUReadback.Request((Texture)(object)rt, 0, (Action<AsyncGPUReadbackRequest>)OnExposureReadback);
				}
			}
		}

		private static void OnExposureReadback(AsyncGPUReadbackRequest request)
		{
			//IL_0014: 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)
			_exposureReadbackPending = false;
			if (((AsyncGPUReadbackRequest)(ref request)).hasError)
			{
				return;
			}
			try
			{
				NativeArray<float> data = ((AsyncGPUReadbackRequest)(ref request)).GetData<float>(0);
				if (data.Length >= 1)
				{
					_cachedHdrpExposure = data[0];
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 exposure readback failed: {arg}");
			}
		}

		public static float GetCachedHdrpExposure()
		{
			return _cachedHdrpExposure;
		}

		private static void EnsureDynamicResolutionAllowed(Camera camera)
		{
			if ((Object)(object)camera == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)camera).GetInstanceID();
			if (_drsEnabledCameraInstanceId == instanceID)
			{
				return;
			}
			HDAdditionalCameraData component = ((Component)camera).GetComponent<HDAdditionalCameraData>();
			if ((Object)(object)component == (Object)null)
			{
				Plugin.Log.LogWarning((object)("FSR2 could not find HDAdditionalCameraData on '" + ((Object)camera).name + "' to enable Dynamic Resolution."));
				return;
			}
			if (!component.allowDynamicResolution)
			{
				component.allowDynamicResolution = true;
			}
			_drsEnabledCameraInstanceId = instanceID;
		}

		public static TextureHandle Replace(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle color, TextureHandle depthBuffer, TextureHandle motionVectors)
		{
			//IL_03d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: 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_03dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			if (renderGraph == null)
			{
				return color;
			}
			if (hdCamera == null || (Object)(object)hdCamera.camera == (Object)null)
			{
				return color;
			}
			if (((Object)hdCamera.camera).name == "UICamera")
			{
				return color;
			}
			if (!ExternalUpscalerManager.FSR2Requested)
			{
				return color;
			}
			if (!FSR2Runtime.Available)
			{
				return color;
			}
			EnsureDynamicResolutionAllowed(hdCamera.camera);
			if (!((TextureHandle)(ref color)).IsValid() || !((TextureHandle)(ref depthBuffer)).IsValid())
			{
				Plugin.Log.LogWarning((object)$"FSR2 source handles invalid: color={((TextureHandle)(ref color)).IsValid()}, depth={((TextureHandle)(ref depthBuffer)).IsValid()}, motionVectors={((TextureHandle)(ref motionVectors)).IsValid()}");
				return color;
			}
			try
			{
				RenderPipeline currentPipeline = RenderPipelineManager.currentPipeline;
				HDRenderPipeline val = (HDRenderPipeline)(object)((currentPipeline is HDRenderPipeline) ? currentPipeline : null);
				if (val == null)
				{
					Plugin.Log.LogWarning((object)"FSR2 could not resolve the active HDRenderPipeline instance.");
					return color;
				}
				int actualWidth = hdCamera.actualWidth;
				int actualHeight = hdCamera.actualHeight;
				if (!TryGetFinalViewport(hdCamera, out var viewport))
				{
					return color;
				}
				int num = Mathf.RoundToInt(((Rect)(ref viewport)).width);
				int num2 = Mathf.RoundToInt(((Rect)(ref viewport)).height);
				if (actualWidth <= 0 || actualHeight <= 0 || num <= 0 || num2 <= 0)
				{
					Plugin.Log.LogWarning((object)$"FSR2 invalid dimensions: render={actualWidth}x{actualHeight}, display={num}x{num2}");
					return color;
				}
				FSR2Runtime.Initialize(hdCamera, num, num2, actualWidth, actualHeight);
				FSR2Runtime.NotifyCamera(hdCamera);
				if (TryConsumeHdrpResetSignal(hdCamera))
				{
					FSR2Runtime.RequestReset();
				}
				if (!TryGetUpsampledOutputHandle(val, renderGraph, hdCamera, out var output))
				{
					Plugin.Log.LogWarning((object)"FSR2 could not obtain the HDRP postprocess upsampled output handle.");
					return color;
				}
				bool flag = _colorOpaqueOnlyCaptured && ((TextureHandle)(ref _capturedColorOpaqueOnly)).IsValid();
				TextureHandle val2 = TextureHandle.nullHandle;
				if (flag)
				{
					TextureDesc textureDesc = renderGraph.GetTextureDesc(color);
					textureDesc.colorFormat = (GraphicsFormat)5;
					textureDesc.depthBufferBits = (DepthBits)0;
					textureDesc.msaaSamples = (MSAASamples)1;
					textureDesc.enableRandomWrite = true;
					textureDesc.clearBuffer = false;
					textureDesc.name = "FSR2 Reactive Mask";
					try
					{
						val2 = renderGraph.CreateTexture(ref textureDesc);
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"FSR2 failed to create reactive mask texture: {arg}");
						flag = false;
					}
				}
				PassData passData = default(PassData);
				RenderGraphBuilder val3 = renderGraph.AddRenderPass<PassData>("FSR2", ref passData, ProfilingSampler);
				passData.Color = ((RenderGraphBuilder)(ref val3)).ReadTexture(ref color);
				passData.Depth = ((RenderGraphBuilder)(ref val3)).ReadTexture(ref depthBuffer);
				if (((TextureHandle)(ref motionVectors)).IsValid())
				{
					passData.MotionVectors = ((RenderGraphBuilder)(ref val3)).ReadTexture(ref motionVectors);
				}
				else
				{
					passData.MotionVectors = TextureHandle.nullHandle;
				}
				passData.HasReactiveMask = flag;
				if (flag)
				{
					passData.ColorOpaqueOnly = ((RenderGraphBuilder)(ref val3)).ReadTexture(ref _capturedColorOpaqueOnly);
					passData.Reactive = ((RenderGraphBuilder)(ref val3)).WriteTexture(ref val2);
				}
				else
				{
					passData.ColorOpaqueOnly = TextureHandle.nullHandle;
					passData.Reactive = TextureHandle.nullHandle;
				}
				passData.Output = ((RenderGraphBuilder)(ref val3)).UseColorBuffer(ref output, 0);
				passData.RenderWidth = actualWidth;
				passData.RenderHeight = actualHeight;
				passData.DisplayWidth = num;
				passData.DisplayHeight = num2;
				passData.CameraNear = hdCamera.camera.nearClipPlane;
				passData.CameraFar = hdCamera.camera.farClipPlane;
				passData.CameraFov = hdCamera.camera.fieldOfView * (MathF.PI / 180f);
				passData.JitterX = hdCamera.taaJitter.x;
				passData.JitterY = hdCamera.taaJitter.y;
				passData.HdCamera = hdCamera;
				passData.DeltaTime = Time.deltaTime;
				RequestExposureReadback(hdCamera);
				passData.PreExposure = GetCachedHdrpExposure();
				((RenderGraphBuilder)(ref val3)).AllowPassCulling(false);
				((RenderGraphBuilder)(ref val3)).SetRenderFunc<PassData>((RenderFunc<PassData>)delegate(PassData data, RenderGraphContext context)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_000d: 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_0035: 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_007e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0238: 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_0250: 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_0383: Unknown result type (might be due to invalid IL or missing references)
					//IL_0389: Unknown result type (might be due to invalid IL or missing references)
					//IL_027b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0282: 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_02f4: Unknown result type (might be due to invalid IL or missing references)
					RenderTexture val4 = TextureHandle.op_Implicit(data.Color);
					RenderTexture val5 = TextureHandle.op_Implicit(data.Depth);
					RenderTexture val6 = (((TextureHandle)(ref data.MotionVectors)).IsValid() ? TextureHandle.op_Implicit(data.MotionVectors) : null);
					RenderTexture val7 = TextureHandle.op_Implicit(data.Output);
					RenderTexture val8 = ((data.HasReactiveMask && ((TextureHandle)(ref data.ColorOpaqueOnly)).IsValid()) ? TextureHandle.op_Implicit(data.ColorOpaqueOnly) : null);
					RenderTexture val9 = ((data.HasReactiveMask && ((TextureHandle)(ref data.Reactive)).IsValid()) ? TextureHandle.op_Implicit(data.Reactive) : null);
					if ((Object)(object)val4 == (Object)null)
					{
						Plugin.Log.LogError((object)"FSR2 execution received null color texture.");
					}
					else if ((Object)(object)val5 == (Object)null)
					{
						Plugin.Log.LogError((object)"FSR2 execution received null depth texture.");
					}
					else if ((Object)(object)val7 == (Object)null)
					{
						Plugin.Log.LogError((object)"FSR2 execution received null output texture.");
					}
					else
					{
						if (DebugLogging)
						{
							Plugin.Log.LogInfo((object)($"FSR2 Execute pass: color={data.RenderWidth}x{data.RenderHeight}, output={data.DisplayWidth}x{data.DisplayHeight}, " + $"DRS.scale={DynamicResolutionHandler.instance.GetCurrentScale():F3}, " + $"reactiveMask={(Object)(object)val9 != (Object)null}, " + $"JitterX={data.JitterX:F4}, JitterY={data.JitterY:F4}"));
						}
						IntPtr renderEventFunc = FSR2Runtime.GetRenderEventFunc();
						if (renderEventFunc == IntPtr.Zero)
						{
							Plugin.Log.LogError((object)"FSR2 dispatch not scheduled: render event function pointer is null.");
						}
						else
						{
							RenderTexture orCreatePrivate = GetOrCreatePrivate(ref _privateColor, val4, enableRandomWrite: false, "FSR2 Private Color");
							RenderTexture orCreatePrivate2 = GetOrCreatePrivate(ref _privateDepth, val5, enableRandomWrite: false, "FSR2 Private Depth");
							RenderTexture val10 = (((Object)(object)val6 != (Object)null) ? GetOrCreatePrivate(ref _privateMotion, val6, enableRandomWrite: false, "FSR2 Private Motion") : null);
							RenderTexture orCreatePrivate3 = GetOrCreatePrivate(ref _privateOutput, val7, enableRandomWrite: true, "FSR2 Private Output");
							if ((Object)(object)orCreatePrivate == (Object)null || (Object)(object)orCreatePrivate2 == (Object)null || (Object)(object)orCreatePrivate3 == (Object)null)
							{
								Plugin.Log.LogError((object)"FSR2 failed to allocate private staging textures.");
							}
							else
							{
								context.cmd.CopyTexture(RenderTargetIdentifier.op_Implicit((Texture)(object)val4), RenderTargetIdentifier.op_Implicit((Texture)(object)orCreatePrivate));
								context.cmd.CopyTexture(RenderTargetIdentifier.op_Implicit((Texture)(object)val5), RenderTargetIdentifier.op_Implicit((Texture)(object)orCreatePrivate2));
								if ((Object)(object)val6 != (Object)null && (Object)(object)val10 != (Object)null)
								{
									context.cmd.CopyTexture(RenderTargetIdentifier.op_Implicit((Texture)(object)val6), RenderTargetIdentifier.op_Implicit((Texture)(object)val10));
								}
								RenderTexture val11 = null;
								RenderTexture val12 = null;
								if ((Object)(object)val8 != (Object)null && (Object)(object)val9 != (Object)null)
								{
									val11 = GetOrCreatePrivate(ref _privateColorOpaqueOnly, val8, enableRandomWrite: false, "FSR2 Private ColorOpaqueOnly");
									val12 = GetOrCreatePrivate(ref _privateReactive, val9, enableRandomWrite: true, "FSR2 Private Reactive");
									if ((Object)(object)val11 != (Object)null && (Object)(object)val12 != (Object)null)
									{
										context.cmd.CopyTexture(RenderTargetIdentifier.op_Implicit((Texture)(object)val8), RenderTargetIdentifier.op_Implicit((Texture)(object)val11));
										FSR2Runtime.GenerateReactiveMask(val11, orCreatePrivate, val12, data.RenderWidth, data.RenderHeight);
										context.cmd.IssuePluginEvent(renderEventFunc, 2);
									}
									else
									{
										val12 = null;
									}
								}
								FSR2Runtime.Execute(orCreatePrivate, orCreatePrivate2, val10, orCreatePrivate3, val12, data.RenderWidth, data.RenderHeight, data.CameraNear, data.CameraFar, data.CameraFov, data.DeltaTime, data.JitterX, data.JitterY, data.PreExposure);
								context.cmd.IssuePluginEvent(renderEventFunc, 1);
								context.cmd.CopyTexture(RenderTargetIdentifier.op_Implicit((Texture)(object)orCreatePrivate3), RenderTargetIdentifier.op_Implicit((Texture)(object)val7));
							}
						}
					}
				});
				((RenderGraphBuilder)(ref val3)).Dispose();
				MarkAfterDynamicResUpscale(val, renderGraph, hdCamera);
				return output;
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"FSR2 render bridge failed: {arg2}");
				return color;
			}
		}
	}
	internal static class FSR2Runtime
	{
		private static readonly FSR2State State = new FSR2State();

		private static IntPtr _renderEventFunc = IntPtr.Zero;

		private static bool _renderEventFuncFetched;

		private static bool DebugLogging
		{
			get
			{
				if (ModConfig.UpscalerDebug != null)
				{
					return ModConfig.UpscalerDebug.Value;
				}
				return false;
			}
		}

		public static bool Available => (int)SystemInfo.graphicsDeviceType == 2;

		public static bool Initialized => State.Initialized;

		public static IntPtr GetRenderEventFunc()
		{
			if (!_renderEventFuncFetched)
			{
				try
				{
					_renderEventFunc = FSR2Native.FSR2GetRenderEventFunc();
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"FSR2 failed to fetch render event function pointer: {arg}");
					_renderEventFunc = IntPtr.Zero;
				}
				_renderEventFuncFetched = true;
				if (_renderEventFunc == IntPtr.Zero)
				{
					Plugin.Log.LogError((object)"FSR2 render event function pointer is null - FSR2 dispatch will never actually run.");
				}
			}
			return _renderEventFunc;
		}

		public static FSR2State GetState()
		{
			return State;
		}

		public static void Initialize(HDCamera hdCamera, int displayWidth, int displayHeight, int renderWidth, int renderHeight)
		{
			if (!Available)
			{
				return;
			}
			if (hdCamera == null || (Object)(object)hdCamera.camera == (Object)null)
			{
				Plugin.Log.LogError((object)"FSR2 cannot initialize because the camera is null.");
				return;
			}
			if (displayWidth <= 0 || displayHeight <= 0 || renderWidth <= 0 || renderHeight <= 0)
			{
				Plugin.Log.LogError((object)$"FSR2 received invalid dimensions: display={displayWidth}x{displayHeight}, render={renderWidth}x{renderHeight}.");
				return;
			}
			bool allowHDR = hdCamera.camera.allowHDR;
			if (!State.Initialized || State.DisplayWidth != displayWidth || State.DisplayHeight != displayHeight || State.RenderWidth != renderWidth || State.RenderHeight != renderHeight || State.Hdr != allowHDR)
			{
				if (State.Initialized)
				{
					State.Reset();
				}
				FSR2Native.InitializeParam initParam = new FSR2Native.InitializeParam
				{
					Flags = 0u,
					DisplaySize = new uint[2]
					{
						(uint)displayWidth,
						(uint)displayHeight
					}
				};
				initParam.Flags |= 8u;
				initParam.Flags |= 16u;
				initParam.Flags |= 64u;
				if (allowHDR)
				{
					initParam.Flags |= 1u;
				}
				try
				{
					FSR2Native.FSR2Initialize(initParam);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"FSR2 native initialization failed: {arg}");
					State.Reset();
					return;
				}
				State.Initialized = true;
				State.DisplayWidth = displayWidth;
				State.DisplayHeight = displayHeight;
				State.RenderWidth = renderWidth;
				State.RenderHeight = renderHeight;
				State.Hdr = allowHDR;
				State.LastFrame = -1;
				State.PendingReset = true;
				State.LastCameraInstanceId = ((Object)hdCamera.camera).GetInstanceID();
				if (DebugLogging)
				{
					Plugin.Log.LogInfo((object)$"FSR2 context initialized: {renderWidth}x{renderHeight} -> {displayWidth}x{displayHeight}");
				}
			}
		}

		public static void NotifyCamera(HDCamera hdCamera)
		{
			if (!State.Initialized || hdCamera == null || (Object)(object)hdCamera.camera == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)hdCamera.camera).GetInstanceID();
			if (State.LastCameraInstanceId != instanceID)
			{
				if (DebugLogging)
				{
					Plugin.Log.LogInfo((object)$"FSR2 camera identity changed ({State.LastCameraInstanceId} -> {instanceID}), requesting history reset.");
				}
				State.LastCameraInstanceId = instanceID;
				State.PendingReset = true;
			}
		}

		public static void RequestReset()
		{
			if (State.Initialized)
			{
				State.PendingReset = true;
			}
		}

		public static void GetJitter(int renderWidth, int renderHeight, int displayWidth, float[] output)
		{
			if (!State.Initialized || renderWidth <= 0 || renderHeight <= 0 || displayWidth <= 0 || output == null || output.Length < 2)
			{
				return;
			}
			try
			{
				FSR2Native.FSR2GetProjectionMatrixJitterOffset((uint)renderWidth, (uint)renderHeight, (uint)displayWidth, output);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 jitter generation failed: {arg}");
			}
		}

		public static void GenerateReactiveMask(RenderTexture colorOpaqueOnly, RenderTexture colorPreUpscale, RenderTexture outReactive, int renderWidth, int renderHeight)
		{
			if (!State.Initialized || (Object)(object)colorOpaqueOnly == (Object)null || (Object)(object)colorPreUpscale == (Object)null || (Object)(object)outReactive == (Object)null)
			{
				return;
			}
			IntPtr nativeTexturePtr = ((Texture)colorOpaqueOnly).GetNativeTexturePtr();
			IntPtr nativeTexturePtr2 = ((Texture)colorPreUpscale).GetNativeTexturePtr();
			IntPtr nativeTexturePtr3 = ((Texture)outReactive).GetNativeTexturePtr();
			if (nativeTexturePtr == IntPtr.Zero || nativeTexturePtr2 == IntPtr.Zero || nativeTexturePtr3 == IntPtr.Zero)
			{
				Plugin.Log.LogWarning((object)"FSR2 GenerateReactiveMask received an invalid texture pointer.");
				return;
			}
			FSR2Native.GenReactiveParam reactiveParam = new FSR2Native.GenReactiveParam
			{
				ColorOpaqueOnly = nativeTexturePtr,
				ColorPreUpscale = nativeTexturePtr2,
				OutReactive = nativeTexturePtr3,
				RenderSize = new uint[2]
				{
					(uint)renderWidth,
					(uint)renderHeight
				},
				Scale = 1f,
				CutoffThreshold = 0.2f,
				BinaryValue = 0.9f,
				Flags = 5u
			};
			try
			{
				FSR2Native.FSR2GenReactiveMask(reactiveParam);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 native GenerateReactiveMask failed: {arg}");
			}
		}

		public static void Execute(RenderTexture color, RenderTexture depth, RenderTexture motionVectors, RenderTexture output, RenderTexture reactive, int renderWidth, int renderHeight, float cameraNear, float cameraFar, float cameraFov, float deltaTime, float jitterX, float jitterY, float preExposure)
		{
			if (!State.Initialized)
			{
				Plugin.Log.LogWarning((object)"FSR2 Execute requested before initialization.");
				return;
			}
			if ((Object)(object)color == (Object)null || (Object)(object)depth == (Object)null || (Object)(object)output == (Object)null)
			{
				Plugin.Log.LogError((object)"FSR2 Execute received null render textures.");
				return;
			}
			if (renderWidth <= 0 || renderHeight <= 0)
			{
				Plugin.Log.LogError((object)$"FSR2 received invalid render dimensions: {renderWidth}x{renderHeight}.");
				return;
			}
			IntPtr nativeTexturePtr = ((Texture)color).GetNativeTexturePtr();
			IntPtr nativeTexturePtr2 = ((Texture)depth).GetNativeTexturePtr();
			IntPtr motionVectors2 = (((Object)(object)motionVectors != (Object)null) ? ((Texture)motionVectors).GetNativeTexturePtr() : IntPtr.Zero);
			IntPtr reactive2 = (((Object)(object)reactive != (Object)null) ? ((Texture)reactive).GetNativeTexturePtr() : IntPtr.Zero);
			IntPtr nativeTexturePtr3 = ((Texture)output).GetNativeTexturePtr();
			if (nativeTexturePtr == IntPtr.Zero)
			{
				Plugin.Log.LogWarning((object)"FSR2 received an invalid color texture pointer.");
				return;
			}
			if (nativeTexturePtr2 == IntPtr.Zero)
			{
				Plugin.Log.LogWarning((object)"FSR2 received an invalid depth texture pointer.");
				return;
			}
			if (nativeTexturePtr3 == IntPtr.Zero)
			{
				Plugin.Log.LogWarning((object)"FSR2 received an invalid output texture pointer.");
				return;
			}
			bool pendingReset = State.PendingReset;
			FSR2Native.ExecuteParam executeParam = new FSR2Native.ExecuteParam
			{
				Color = nativeTexturePtr,
				Depth = nativeTexturePtr2,
				MotionVectors = motionVectors2,
				Reactive = reactive2,
				TransparencyAndComposition = IntPtr.Zero,
				Output = nativeTexturePtr3,
				MotionVectorScale = new float[2]
				{
					-renderWidth,
					renderHeight
				},
				RenderSize = new uint[2]
				{
					(uint)renderWidth,
					(uint)renderHeight
				},
				EnableSharpening = (ModConfig.UpscalerSharpness != null && ModConfig.UpscalerSharpness.Value > 0f),
				Sharpness = ((ModConfig.UpscalerSharpness != null) ? Mathf.Clamp01(ModConfig.UpscalerSharpness.Value) : 0f),
				FrameTimeDeltaInSec = Mathf.Max(deltaTime, 0.0001f),
				CameraNear = cameraNear,
				CameraFar = cameraFar,
				CameraFov = cameraFov,
				PreExposure = ((preExposure > 0f) ? preExposure : 1f),
				JitterOffset = new float[2]
				{
					jitterX,
					0f - jitterY
				},
				Reset = (pendingReset ? ((byte)1) : ((byte)0))
			};
			try
			{
				FSR2Native.FSR2Execute(executeParam);
				State.PendingReset = false;
				State.LastFrame++;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"FSR2 native execution failed: {arg}");
			}
		}

		public static void Cleanup()
		{
			if (State.Initialized)
			{
				State.Reset();
			}
		}
	}
	internal sealed class FSR2State
	{
		public bool Initialized;

		public int DisplayWidth;

		public int DisplayHeight;

		public int RenderWidth;

		public int RenderHeight;

		public bool Hdr;

		public int LastFrame = -1;

		public bool PendingReset = true;

		public int LastCameraInstanceId = int.MinValue;

		public readonly float[] JitterOffset = new float[2];

		public void Reset()
		{
			Initialized = false;
			DisplayWidth = 0;
			DisplayHeight = 0;
			RenderWidth = 0;
			RenderHeight = 0;
			Hdr = false;
			LastFrame = -1;
			PendingReset = true;
			LastCameraInstanceId = int.MinValue;
			JitterOffset[0] = 0f;
			JitterOffset[1] = 0f;
		}
	}
}
namespace LethalGraphics.Lighting
{
	public static class EnvironmentLightingManager
	{
		private static float _nextUpdate;

		private static LevelWeatherType _lastWeather = (LevelWeatherType)(-999);

		private static string _lastLevelName;

		public static void Update()
		{
			//IL_0054: 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_0073: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected I4, but got Unknown
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			if (!ModConfig.EnableWeatherLighting.Value || Time.unscaledTime < _nextUpdate)
			{
				return;
			}
			_nextUpdate = Time.unscaledTime + 0.35f;
			if ((Object)(object)RoundManager.Instance == (Object)null || (Object)(object)RoundManager.Instance.currentLevel == (Object)null)
			{
				return;
			}
			LevelWeatherType currentWeather = RoundManager.Instance.currentLevel.currentWeather;
			string text = RoundManager.Instance.currentLevel.PlanetName ?? string.Empty;
			if (currentWeather != _lastWeather || !string.Equals(text, _lastLevelName, StringComparison.Ordinal))
			{
				_lastWeather = currentWeather;
				_lastLevelName = text;
				float exposureOffset = 0f;
				float saturationOffset = 0f;
				float fogAnisotropy = ModConfig.VolumetricFogAnisotropy.Value;
				float wetness = 0f;
				switch ((int)currentWeather)
				{
				case 1:
					exposureOffset = ModConfig.RainExposureOffset.Value;
					saturationOffset = -0.4f;
					fogAnisotropy = 0.55f;
					wetness = 0.7f;
					break;
				case 2:
					exposureOffset = ModConfig.StormExposureOffset.Value;
					saturationOffset = -0.7f;
					fogAnisotropy = 0.45f;
					wetness = 1f;
					break;
				case 3:
					exposureOffset = ModConfig.FoggyExposureOffset.Value;
					saturationOffset = -0.8f;
					fogAnisotropy = 0.35f;
					break;
				case 0:
					exposureOffset = ModConfig.DustExposureOffset.Value;
					saturationOffset = -0.6f;
					fogAnisotropy = 0.4f;
					break;
				case 4:
					exposureOffset = ModConfig.FloodedExposureOffset.Value;
					saturationOffset = -0.25f;
					fogAnisotropy = 0.5f;
					wetness = 1f;
					break;
				case 5:
					exposureOffset = ModConfig.EclipsedExposureOffset.Value;
					saturationOffset = -1.2f;
					fogAnisotropy = 0.45f;
					break;
				}
				LightingManager.Instance?.ApplyEnvironmentSettings(exposureOffset, saturationOffset, fogAnisotropy);
				LightingManager.Instance?.ApplyWetness(wetness);
				if (ModConfig.Debug.Value)
				{
					Plugin.Log.LogInfo((object)$"Environment lighting updated for {text} with weather {currentWeather}.");
				}
			}
		}
	}
	public sealed class FlashlightDustMotes : MonoBehaviour
	{
		private const string ROOT_NAME = "LethalLightning_FlashlightDustMotes";

		private ParticleSystem _particles;

		private Material _material;

		private Light _light;

		private static Mesh _dustMesh;

		public static FlashlightDustMotes Attach(FlashlightItem item)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)item == (Object)null)
			{
				return null;
			}
			FlashlightDustMotes componentInChildren = ((Component)item).GetComponentInChildren<FlashlightDustMotes>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				return componentInChildren;
			}
			GameObject val = new GameObject("LethalLightning_FlashlightDustMotes");
			Transform val2 = (((Object)(object)item.flashlightBulb != (Object)null) ? ((Component)item.flashlightBulb).transform : ((Component)item).transform);
			val.transform.SetParent(val2, false);
			FlashlightDustMotes flashlightDustMotes = val.AddComponent<FlashlightDustMotes>();
			flashlightDustMotes.Initialize(item);
			return flashlightDustMotes;
		}

		private void Initialize(FlashlightItem item)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			_light = item.flashlightBulb;
			_material = CreateParticleMaterial();
			_particles = ((Component)this).gameObject.AddComponent<ParticleSystem>();
			MainModule main = _particles.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).maxParticles = 150;
			((MainModule)(ref main)).startLifetime = new MinMaxCurve(8f, 14f);
			((MainModule)(ref main)).startSpeed = new MinMaxCurve(0.01f, 0.03f);
			float value = ModConfig.FlashlightDustMotesSize.Value;
			((MainModule)(ref main)).startSize = new MinMaxCurve(value * 0.6f, value * 1.4f);
			((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(Color.white);
			((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(0f);
			EmissionModule emission = _particles.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(ModConfig.FlashlightDustMotesDensity.Value);
			ShapeModule shape = _particles.shape;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0;
			((ShapeModule)(ref shape)).radius = 3f;
			NoiseModule noise = _particles.noise;
			((NoiseModule)(ref noise)).enabled = true;
			((NoiseModule)(ref noise)).strength = MinMaxCurve.op_Implicit(Mathf.Max(0.01f, ModConfig.FlashlightDustMotesSpeed.Value) * 0.4f);
			((NoiseModule)(ref noise)).frequency = 0.15f;
			((NoiseModule)(ref noise)).scrollSpeed = MinMaxCurve.op_Implicit(0.05f);
			ParticleSystemRenderer component = ((Component)_particles).GetComponent<ParticleSystemRenderer>();
			((Renderer)component).material = _material;
			component.renderMode = (ParticleSystemRenderMode)4;
			component.mesh = GetOrCreateDustMesh();
			((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)component).receiveShadows = false;
			((Component)this).gameObject.SetActive(((GrabbableObject)item).isBeingUsed);
		}

		private static Mesh GetOrCreateDustMesh()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			if ((Object)(object)_dustMesh != (Object)null)
			{
				return _dustMesh;
			}
			Vector3[] vertices = (Vector3[])(object)new Vector3[6]
			{
				new Vector3(0.5f, 0f, 0f),
				new Vector3(-0.5f, 0f, 0f),
				new Vector3(0f, 0.5f, 0f),
				new Vector3(0f, -0.5f, 0f),
				new Vector3(0f, 0f, 0.5f),
				new Vector3(0f, 0f, -0.5f)
			};
			int[] array = new int[24]
			{
				0, 2, 4, 2, 1, 4, 1, 3, 4, 3,
				0, 4, 2, 0, 5, 1, 2, 5, 3, 1,
				5, 0, 3, 5
			};
			Mesh val = new Mesh
			{
				name = "LethalLightning_DustMoteMesh"
			};
			val.SetVertices(vertices);
			val.SetTriangles(array, 0);
			val.RecalculateNormals();
			val.RecalculateBounds();
			_dustMesh = val;
			return _dustMesh;
		}

		public void Refresh(bool enabled)
		{
			//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_005f: Unknown result type (might be due to invalid IL or missing references)
			bool active = enabled && ModConfig.EnableFlashlightDustMotes.Value && (Object)(object)_light != (Object)null && ((Behaviour)_light).enabled;
			((Component)this).gameObject.SetActive(active);
			if (!((Object)(object)_particles == (Object)null))
			{
				EmissionModule emission = _particles.emission;
				((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(ModConfig.FlashlightDustMotesDensity.Value);
			}
		}

		private static Material CreateParticleMaterial()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0044: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			Shader val = Shader.Find("HDRP/Lit");
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"FlashlightDustMotes could not find the HDRP/Lit shader - dust motes will not render.");
				return null;
			}
			Material val2 = new Material(val)
			{
				name = "LethalLightning_DustMoteMaterial"
			};
			HDMaterial.SetSurfaceType(val2, false);
			HDMaterial.ValidateMaterial(val2);
			val2.SetColor("_BaseColor", new Color(0.85f, 0.82f, 0.75f) * Mathf.Max(0.1f, ModConfig.FlashlightDustMotesBrightness.Value));
			val2.SetFloat("_Metallic", 0f);
			val2.SetFloat("_Smoothness", 0.15f);
			return val2;
		}

		private void OnDestroy()
		{
			if ((Object)(object)_material != (Object)null)
			{
				Object.Destroy((Object)(object)_material);
			}
		}
	}
	public static class GodRaysManager
	{
		public static void Apply()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Invalid comparison between Unknown and I4
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			if (!ModConfig.EnableGodRays.Value)
			{
				return;
			}
			Light[] array = Object.FindObjectsOfType<Light>();
			int num = 0;
			foreach (Light val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				bool num2 = (int)val.type == 1;
				bool flag = ((Object)val).name.IndexOf("Sun", StringComparison.OrdinalIgnoreCase) >= 0 || ((Object)val).name.IndexOf("Moon", StringComparison.OrdinalIgnoreCase) >= 0 || ((Object)val).name.IndexOf("Window", StringComparison.OrdinalIgnoreCase) >= 0;
				if (!num2 && !flag)
				{
					continue;
				}
				HDAdditionalLightData component = ((Component)val).GetComponent<HDAdditionalLightData>();
				if (!((Object)(object)component == (Object)null))
				{
					if ((int)val.shadows == 0)
					{
						val.shadows = (LightShadows)2;
					}
					component.volumetricDimmer = ModConfig.GodRaysIntensity.Value;
					num++;
				}
			}
			if (ModConfig.Debug.Value)
			{
				Plugin.Log.LogInfo((object)$"God rays applied to {num} light(s).");
			}
		}
	}
	public class LightingManager : MonoBehaviour
	{
		private static LightingManager _instance;

		private Volume _volume;

		private VolumeProfile _profile;

		private GlobalIllumination _gi;

		private IndirectLightingController _indirectController;

		private ScreenSpaceAmbientOcclusion _ao;

		private ContactShadows _contactShadows;

		private Tonemapping _tonemapping;

		private SplitToning _splitToning;

		private Exposure _exposure;

		private ColorAdjustments _colorAdjustments;

		private Bloom _bloom;

		private Vignette _vignette;

		private FilmGrain _filmGrain;

		private ChromaticAberration _chromaticAberration;

		private LensDistortion _lensDistortion;

		private ScreenSpaceReflection _ssr;

		private Fog _fog;

		public static LightingManager Instance => _instance;

		public static void EnsureInitialized()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			if (!((Object)(object)_instance != (Object)null))
			{
				GameObject val = new GameObject("LethalLightning_Core");
				Object.DontDestroyOnLoad((Object)val);
				_instance = val.AddComponent<LightingManager>();
				_instance.BuildStack();
			}
		}

		public static void RefreshEnvironment()
		{
			if (!((Object)(object)_instance == (Object)null))
			{
				_instance.ApplyEnvironmentSettings();
			}
		}

		public static void RefreshAll()
		{
			if (!((Object)(object)_instance == (Object)null))
			{
				_instance.RefreshAllSettings();
			}
		}

		private void BuildStack()
		{
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			_volume = ((Component)this).gameObject.AddComponent<Volume>();
			_volume.isGlobal = true;
			_volume.priority = 50f;
			_profile = ScriptableObject.CreateInstance<VolumeProfile>();
			((Object)_profile).name = "LethalLightning_Profile";
			_volume.sharedProfile = _profile;
			_gi = _profile.Add<GlobalIllumination>(true);
			_indirectController = _profile.Add<IndirectLightingController>(true);
			_ao = _profile.Add<ScreenSpaceAmbientOcclusion>(true);
			_contactShadows = _profile.Add<ContactShadows>(true);
			_tonemapping = _profile.Add<Tonemapping>(true);
			_splitToning = _profile.Add<SplitToning>(true);
			_colorAdjustments = _profile.Add<ColorAdjustments>(true);
			_exposure = _profile.Add<Exposure>(true);
			_bloom = _profile.Add<Bloom>(true);
			_vignette = _profile.Add<Vignette>(true);
			_filmGrain = _profile.Add<FilmGrain>(true);
			_chromaticAberration = _profile.Add<ChromaticAberration>(true);
			_lensDistortion = _profile.Add<LensDistortion>(true);
			_ssr = _profile.Add<ScreenSpaceReflection>(true);
			_fog = _profile.Add<Fog>(true);
			((VolumeParameter<Color>)(object)_splitToning.shadows).Override(new Color(0.01f, 0.015f, 0.035f));
			((VolumeParameter<Color>)(object)_splitToning.highlights).Override(new Color(1.01f, 0.99f, 0.96f));
			((VolumeParameter<float>)(object)_splitToning.balance).Override(0f);
			RefreshAllSettings();
			if (ModConfig.Debug.Value)
			{
				Plugin.Log.LogInfo((object)"Global lighting volume stack configured.");
			}
		}

		private void Update()
		{
			RenderSettings.ambientIntensity = ModConfig.AmbientProbeDimmer.Value;
			EnvironmentLightingManager.Update();
		}

		private void RefreshAllSettings()
		{
			((VolumeComponent)_gi).active = ModConfig.EnableGlobalIllumination.Value;
			((VolumeParameter<bool>)(object)_gi.enable).Override(ModConfig.EnableGlobalIllumination.Value);
			((VolumeParameter<bool>)(object)_gi.fullResolutionSS).Override(true);
			((VolumeParameter<float>)(object)_gi.depthBufferThickness).Override(0.04f);
			((VolumeParameter<int>)(object)_gi.bounceCount).Override(Mathf.Clamp(ModConfig.GIBounceCount.Value, 1, 2));
			((VolumeComponent)_indirectController).active = ModConfig.EnableGlobalIllumination.Value;
			((VolumeParameter<float>)(object)_indirectController.indirectDiffuseLightingMultiplier).Override(ModConfig.IndirectDiffuseMultiplier.Value);
			((VolumeComponent)_ao).active = ModConfig.EnableAmbientOcclusion.Value;
			((VolumeParameter<float>)(object)_ao.intensity).Override(ModConfig.AOIntensity.Value);
			((VolumeParameter<float>)(object)_ao.directLightingStrength).Override(ModConfig.AODirectLightingStrength.Value);
			((VolumeParameter<float>)(object)_ao.radius).Override(ModConfig.AORadius.Value);
			((VolumeParameter<bool>)(object)_ao.temporalAccumulation).Override(true);
			((VolumeParameter<float>)(object)_ao.ghostingReduction).Override(0.5f);
			((VolumeComponent)_contactShadows).active = ModConfig.EnableContactShadows.Value;
			((VolumeParameter<bool>)(object)_contactShadows.enable).Override(ModConfig.EnableContactShadows.Value);
			((VolumeParameter<float>)(object)_contactShadows.opacity).Override(ModConfig.ContactShadowOpacity.Value);
			((VolumeParameter<float>)(object)_contactShadows.maxDistance).Override(ModConfig.ContactShadowMaxDistance.Value);
			((VolumeParameter<float>)(object)_contactShadows.fadeDistance).Override(ModConfig.ContactShadowFadeDistance.Value);
			_contactShadows.sampleCount = Mathf.Clamp(ModConfig.ShadowSampleCount.Value, 4, 32);
			((VolumeParameter<TonemappingMode>)(object)_tonemapping.mode).Override((TonemappingMode)((!string.Equals(ModConfig.TonemapperType.Value, "ACES", StringComparison.OrdinalIgnoreCase)) ? 1 : 2));
			((VolumeParameter<float>)(object)_colorAdjustments.postExposure).Override(ModConfig.ExposureCompensation.Value + (ExternalUpscalerManager.FSR2Requested ? ModConfig.FSR2ExposureCompensation.Value : 0f));
			((VolumeParameter<float>)(object)_colorAdjustments.contrast).Override(ModConfig.ContrastAmount.Value);
			((VolumeParameter<float>)(object)_colorAdjustments.saturation).Override(ModConfig.SaturationAmount.Value);
			((VolumeComponent)_exposure).active = ModConfig.EnableAutoExposure.Value;
			((VolumeParameter<ExposureMode>)(object)_exposure.mode).Override((ExposureMode)1);
			((VolumeParameter<float>)(object)_exposure.limitMin).Override(ModConfig.AutoExposureLimitMin.Value);
			((VolumeParameter<float>)(object)_exposure.limitMax).Override(ModConfig.AutoExposureLimitMax.Value);
			((VolumeParameter<float>)(object)_exposure.adaptationSpeedDarkToLight).Override(ModConfig.AutoExposureDarkToLightSpeed.Value);
			((VolumeParameter<float>)(object)_exposure.adaptationSpeedLightToDark).Override(ModConfig.AutoExposureLightToDarkSpeed.Value);
			((VolumeComponent)_bloom).active = ModConfig.EnableBloom.Value;
			((VolumeParameter<float>)(object)_bloom.intensity).Override(ModConfig.BloomIntensity.Value);
			((VolumeParameter<float>)(object)_bloom.threshold).Override(ModConfig.BloomThreshold.Value);
			((VolumeParameter<float>)(object)_bloom.scatter).Override(0.26f);
			((VolumeComponent)_vignette).active = ModConfig.EnableVignette.Value;
			((VolumeParameter<float>)(object)_vignette.intensity).Override(ModConfig.VignetteIntensity.Value);
			((VolumeParameter<float>)(object)_vignette.smoothness).Override(0.4f);
			((VolumeComponent)_filmGrain).active = ModConfig.EnableFilmGrain.Value;
			((VolumeParameter<float>)(object)_filmGrain.intensity).Override(ModConfig.FilmGrainIntensity.Value);
			((VolumeParameter<float>)(object)_filmGrain.response).Override(ModConfig.FilmGrainResponse.Value);
			((VolumeComponent)_chromaticAberration).active = ModConfig.EnableChromaticAberration.Value;
			((VolumeParameter<float>)(object)_chromaticAberration.intensity).Override(ModConfig.ChromaticAberrationIntensity.Value);
			_chromaticAberration.maxSamples = 4;
			((VolumeComponent)_lensDistortion).active = ModConfig.EnableLensDistortion.Value;
			((VolumeParameter<float>)(object)_lensDistortion.intensity).Override(ModConfig.LensDistortionIntensity.Value);
			((VolumeParameter<float>)(object)_lensDistortion.scale).Override(ModConfig.LensDistortionScale.Value);
			((VolumeParameter<float>)(object)_lensDistortion.xMultiplier).Override(1f);
			((VolumeParameter<float>)(object)_lensDistortion.yMultiplier).Override(1f);
			((VolumeComponent)_ssr).active = ModConfig.EnableScreenSpaceReflections.Value;
			((VolumeParameter<bool>)(object)_ssr.enabled).Override(ModConfig.EnableScreenSpaceReflections.Value);
			((VolumeParameter<int>)(object)((VolumeComponentWithQuality)_ssr).quality).Override(ModConfig.SSRQuality.Value);
			((VolumeParameter<float>)(object)_ssr.depthBufferThickness).Override(ModConfig.SSRDepthThickness.Value);
			((VolumeParameter<float>)(object)_ssr.screenFadeDistance).Override(ModConfig.SSRScreenFadeDistance.Value);
			((VolumeParameter<float>)(object)_ssr.accumulationFactor).Override(ModConfig.SSRAccumulationFactor.Value);
			_ssr.rayLength = ModConfig.SSRRayLength.Value;
			_ssr.rayMaxIterations = ModConfig.SSRRayIterations.Value;
			_ssr.minSmoothness = ModConfig.SSRMinSmoothness.Value;
			((VolumeParameter<bool>)(object)_fog.enabled).Override(true);
			((VolumeParameter<float>)(object)_fog.anisotropy).Override(ModConfig.EnableGodRays.Value ? ModConfig.GodRaysAnisotropy.Value : ModConfig.VolumetricFogAnisotropy.Value);
			((VolumeParameter<float>)(object)_fog.globalLightProbeDimmer).Override(ModConfig.AmbientProbeDimmer.Value);
		}

		public void ApplyWetness(float wetness)
		{
			if (!((Object)(object)_ssr == (Object)null))
			{
				wetness = Mathf.Clamp01(wetness);
				if (!ModConfig.EnableWetSurfaces.Value)
				{
					wetness = 0f;
				}
				float value = ModConfig.SSRMinSmoothness.Value;
				float value2 = ModConfig.SSRRayLength.Value;
				_ssr.minSmoothness = Mathf.Lerp(value, ModConfig.WetSurfaceMinSmoothness.Value, wetness);
				_ssr.rayLength = Mathf.Lerp(value2, value2 * ModConfig.WetSurfaceRayLengthMultiplier.Value, wetness);
			}
		}

		public void ApplyEnvironmentSettings(float exposureOffset = 0f, float saturationOffset = 0f, float fogAnisotropy = -999f)
		{
			if ((Object)(object)_colorAdjustments != (Object)null)
			{
				((VolumeParameter<float>)(object)_colorAdjustments.postExposure).Override(ModConfig.ExposureCompensation.Value + exposureOffset + (ExternalUpscalerManager.FSR2Requested ? ModConfig.FSR2ExposureCompensation.Value : 0f));
			}
			if ((Object)(object)_colorAdjustments != (Object)null)
			{
				((VolumeParameter<float>)(object)_colorAdjustments.saturation).Override(ModConfig.SaturationAmount.Value + saturationOffset);
			}
			if ((Object)(object)_fog != (Object)null && fogAnisotropy > -900f)
			{
				((VolumeParameter<float>)(object)_fog.anisotropy).Override(Mathf.Clamp(fogAnisotropy, -1f, 1f));
			}
		}

		public void SetBloomIntensity(float value)
		{
			if ((Object)(object)_bloom != (Object)null)
			{
				((VolumeParameter<float>)(object)_bloom.intensity).Override(value);
			}
		}
	}
	public sealed class FlashlightVolumetric : MonoBehaviour
	{
		private const string VOLUME_NAME = "LethalLightning_FlashlightVolumetric";

		private LocalVolumetricFog _fog;

		private Texture3D _mask;

		private Light _light;

		public static FlashlightVolumetric Attach(FlashlightItem item)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)item == (Object)null)
			{
				return null;
			}
			FlashlightVolumetric componentInChildren = ((Component)item).GetComponentInChildren<FlashlightVolumetric>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				return componentInChildren;
			}
			GameObject val = new GameObject("LethalLightning_FlashlightVolumetric");
			val.transform.SetParent(((Component)item).transform, false);
			FlashlightVolumetric flashlightVolumetric = val.AddComponent<FlashlightVolumetric>();
			flashlightVolumetric.Initialize(item);
			return flashlightVolumetric;
		}

		private void Initialize(FlashlightItem item)
		{
			//IL_0055: 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_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			_light = item.flashlightBulb;
			_fog = ((Component)this).gameObject.AddComponent<LocalVolumetricFog>();
			_mask = CreateBeamMask();
			LocalVolumetricFogArtistParameters parameters = default(LocalVolumetricFogArtistParameters);
			((LocalVolumetricFogArtistParameters)(ref parameters))..ctor((Color)(((Object)(object)_light != (Object)null) ? _light.color : new Color(1f, 0.96f, 0.9f)), Mathf.Max(1f, 1f / Mathf.Max(0.001f, ModConfig.FlashlightVolumetricDensity.Value)), ModConfig.FlashlightVolumetricAnisotropy.Value);
			parameters.size = new Vector3(ModConfig.FlashlightVolumetricWidth.Value, ModConfig.FlashlightVolumetricWidth.Value, ModConfig.FlashlightVolumetricRange.Value);
			parameters.positiveFade = new Vector3(ModConfig.FlashlightVolumetricFade.Value, ModConfig.FlashlightVolumetricFade.Value, ModConfig.FlashlightVolumetricFade.Value);
			parameters.negativeFade = new Vector3(ModConfig.FlashlightVolumetricFade.Value, ModConfig.FlashlightVolumetricFade.Value, ModConfig.FlashlightVolumetricFade.Value);
			parameters.volumeMask = (Texture)(object)_mask;
			parameters.maskMode = (LocalVolumetricFogMaskMode)0;
			parameters.blendingMode = (LocalVolumetricFogBlendingMode)1;
			parameters.priority = 100;
			_fog.parameters = parameters;
			((Component)this).transform.localPosition = new Vector3(0f, 0f, ModConfig.FlashlightVolumetricRange.Value * 0.5f);
			((Component)this).transform.localRotation = Quaternion.identity;
			((Component)this).gameObject.SetActive(((GrabbableObject)item).isBeingUsed);
		}

		public void Refresh(bool enabled)
		{
			((Component)this).gameObject.SetActive(enabled && ModConfig.EnableFlashlightVolumetric.Value && (Object)(object)_light != (Object)null && ((Behaviour)_light).enabled);
		}

		private Texture3D CreateBeamMask()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			Texture3D val = new Texture3D(24, 24, 24, (TextureFormat)4, false);
			Color[] array = (Color[])(object)new Color[13824];
			for (int i = 0; i < 24; i++)
			{
				float num = ((float)i + 0.5f) / 24f;
				float num2 = Mathf.Lerp(0.12f, 0.5f, num);
				float num3 = Mathf.SmoothStep(1f, 0.35f, num);
				for (int j = 0; j < 24; j++)
				{
					float num4 = (((float)j + 0.5f) / 24f - 0.5f) * 2f;
					for (int k = 0; k < 24; k++)
					{
						float num5 = (((float)k + 0.5f) / 24f - 0.5f) * 2f;
						float num6 = Mathf.Sqrt(num5 * num5 + num4 * num4);
						float num7 = Mathf.Clamp01((num2 - num6) / Mathf.Max(0.001f, num2 * 0.35f));
						float num8 = Mathf.SmoothStep(0f, 1f, num7);
						num8 *= num3;
						int num9 = k + j * 24 + i * 24 * 24;
						array[num9] = new Color(1f, 1f, 1f, num8);
					}
				}
			}
			val.SetPixels(array);
			((Texture)val).wrapMode = (TextureWrapMode)1;
			((Texture)val).filterMode = (FilterMode)2;
			val.Apply(false, true);
			return val;
		}

		private void OnDestroy()
		{
			if ((Object)(object)_mask != (Object)null)
			{
				Object.Destroy((Object)(object)_mask);
			}
		}
	}
}
namespace LethalGraphics.Lighting.Patches
{
	[HarmonyPatch]
	public static class AtmospherePatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		private static void Postfix_StartOfRoundStart()
		{
			LightingManager.EnsureInitialized();
			if ((Object)(object)LightingManager.Instance != (Object)null)
			{
				((Component)LightingManager.Instance).gameObject.SetActive(true);
			}
			GodRaysManager.Apply();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(MenuManager), "Awake")]
		private static void Postfix_MenuManagerAwake()
		{
			if ((Object)(object)LightingManager.Instance != (Object)null)
			{
				((Component)LightingManager.Instance).gameObject.SetActive(false);
				if (ModConfig.Debug.Value)
				{
					Plugin.Log.LogInfo((object)"Deactivated LethalLightning's Volume for the main menu scene.");
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDManager), "Start")]
		private static void Postfix_HUDManagerStart(HUDManager __instance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (ModConfig.FixUiColors.Value && (Object)(object)__instance.UICamera != (Object)null)
			{
				HDAdditionalCameraData component = ((Component)__instance.UICamera).GetComponent<HDAdditionalCameraData>();
				if ((Object)(object)component != (Object)null)
				{
					component.volumeLayerMask = LayerMask.op_Implicit(0);
					if (ModConfig.Debug.Value)
					{
						Plugin.Log.LogInfo((object)"UI Camera isolated from lighting volume stack.");
					}
				}
			}
			if (ModConfig.BypassVanillaPosterization.Value && (Object)(object)__instance.mainCustomPass != (Object)null && ((Behaviour)__instance.mainCustomPass).enabled)
			{
				((Behaviour)__instance.mainCustomPass).enabled = false;
				if (ModConfig.Debug.Value)
				{
					Plugin.Log.LogInfo((object)"Bypassed vanilla posterization pass.");
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "SetNightVisionEnabled")]
		private static void Postfix_SetNightVisionEnabled(PlayerControllerB __instance)
		{
			if (ModConfig.TuneNightVision.Value && !((Object)(object)__instance.nightVision == (Object)null) && ((Behaviour)__instance.nightVision).enabled)
			{
				__instance.nightVision.intensity = ModConfig.NightVisionIntensity.Value;
				__instance.nightVision.range = ModConfig.NightVisionRange.Value;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		private static void Postfix_PlayerUpdate(PlayerControllerB __instance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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)
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				if (ModConfig.HideHelmetVisor.Value && (Object)(object)__instance.localVisor != (Object)null && __instance.localVisor.localScale != Vector3.zero)
				{
					__instance.localVisor.localScale = Vector3.zero;
				}
				Camera gameplayCamera = __instance.gameplayCamera;
				if (!((Object)(object)gameplayCamera == (Object)null))
				{
					ResolutionManager.Apply(gameplayCamera);
				}
			}
		}
	}
	public sealed class DynamicLightFlicker : MonoBehaviour
	{
		private Light _light;

		private float _baseIntensity;

		private float _lastAppliedIntensity;

		private float _seed;

		private bool _initialized;

		public void Initialize(Light light)
		{
			_light = light;
			if (!((Object)(object)_light == (Object)null))
			{
				_baseIntensity = _light.intensity;
				_lastAppliedIntensity = _light.intensity;
				_seed = Random.value * 1000f;
				_initialized = true;
			}
		}

		private void Update()
		{
			if (_initialized && !((Object)(object)_light == (Object)null) && ((Behaviour)_light).enabled)
			{
				if (Mathf.Abs(_light.intensity - _lastAppliedIntensity) > Mathf.Max(0.2f, _baseIntensity * 0.25f))
				{
					_baseIntensity = _light.intensity;
				}
				float num = Time.time * ModConfig.LightFlickerSpeed.Value + _seed;
				float num2 = Mathf.PerlinNoise(num, _seed) * 2f - 1f;
				float num3 = Mathf.PerlinNoise(num * 7.5f, _seed + 31.7f) * 2f - 1f;
				float num4 = 1f + num2 * ModConfig.LightFlickerAmount.Value + num3 * ModConfig.LightFlickerMicroAmount.Value;
				float num5 = Mathf.Max(0f, _baseIntensity * num4);
				_light.intensity = num5;
				_lastAppliedIntensity = num5;
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	public static class FacilityLightingPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("RefreshLightsList")]
		public static void Postfix_RefreshLightsList(RoundManager __instance)
		{
			ApplyToLights(__instance);
		}

		public static void RefreshAll()
		{
			ApplyToLights(RoundManager.Instance);
		}

		private static void ApplyToLights(RoundManager roundManager)
		{
			if ((Object)(object)roundManager == (Object)null || roundManager.allPoweredLights == null || roundManager.allPoweredLights.Count == 0)
			{
				return;
			}
			LightingManager.EnsureInitialized();
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < roundManager.allPoweredLights.Count; i++)
			{
				Light val = roundManager.allPoweredLights[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				HDAdditionalLightData component = ((Component)val).GetComponent<HDAdditionalLightData>();
				if (!((Object)(object)component == (Object)null))
				{
					if (ModConfig.EnableContactShadows.Value)
					{
						((ScalableSettingValue<bool>)(object)component.useContactShadow).useOverride = true;
						((ScalableSettingValue<bool>)(object)component.useContactShadow).@override = true;
					}
					component.volumetricDimmer = ModConfig.VolumetricFogDimmer.Value;
					if (ModConfig.EnableDynamicShadowTuning.Value)
					{
						component.shadowDimmer = 1f;
						component.shadowFadeDistance = ModConfig.ShadowDistance.Value;
					}
					if (ModConfig.EnableLightFlicker.Value && (Object)(object)((Component)val).GetComponent<DynamicLightFlicker>() == (Object)null)
					{
						((Component)val).gameObject.AddComponent<DynamicLightFlicker>().Initialize(val);
						num2++;
					}
					num++;
				}
			}
			if (ModConfig.Debug.Value)
			{
				Plugin.Log.LogInfo((object)$"Upgraded {num} facility lights and attached {num2} flicker controllers.");
			}
		}
	}
	[HarmonyPatch(typeof(FlashlightItem))]
	public static class FlashlightPatch
	{
		private const string FILL_LIGHT_NAME = "LethalLightning_FillLight";

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		public static void Postfix_Start(FlashlightItem __instance)
		{
			LightingManager.EnsureInitialized();
			UpdateFlashlightProperties(__instance);
		}

		public static void RefreshAll()
		{
			FlashlightItem[] array = Object.FindObjectsOfType<FlashlightItem>(true);
			for (int i = 0; i < array.Length; i++)
			{
				UpdateFlashlightProperties(array[i]);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("SwitchFlashlight")]
		public static void Postfix_SwitchFlashlight(FlashlightItem __instance, bool on)
		{
			UpdateFlashlightProperties(__instance);
			Transform val = ((Component)__instance).transform.Find("LethalLightning_FillLight");
			if ((Object)(object)val != (Object)null)
			{
				((Component)val).gameObject.SetActive(on && ((GrabbableObject)__instance).isBeingUsed);
			}
			FlashlightVolumetric componentInChildren = ((Component)__instance).GetComponentInChildren<FlashlightVolumetric>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.Refresh(on && ((GrabbableObject)__instance).isBeingUsed);
			}
		}

		private static void UpdateFlashlightProperties(FlashlightItem item)
		{
			if ((Object)(object)item.flashlightBulb == (Object)null)
			{
				return;
			}
			if (ModConfig.SoftFlashlight.Value)
			{
				item.flashlightBulb.innerSpotAngle = item.flashlightBulb.spotAngle * 0.45f;
			}
			HDAdditionalLightData component = ((Component)item.flashlightBulb).GetComponent<HDAdditionalLightData>();
			if ((Object)(object)component != (Object)null)
			{
				if (ModConfig.EnableContactShadows.Value)
				{
					((ScalableSettingValue<bool>)(object)component.useContactShadow).useOverride = true;
					((ScalableSettingValue<bool>)(object)component.useContactShadow).@override = true;
				}
				component.volumetricDimmer = ModConfig.VolumetricFogDimmer.Value;
				component.shadowDimmer = 0.95f;
			}
			if (ModConfig.FlashlightFillLight.Value)
			{
				AttachFillLight(item);
				RefreshFillLight(item);
			}
			bool enabled = ((GrabbableObject)item).isBeingUsed && ((Behaviour)item.flashlightBulb).enabled;
			if (ModConfig.EnableFlashlightVolumetric.Value)
			{
				FlashlightVolumetric.Attach(item)?.Refresh(enabled);
			}
			else
			{
				((Component)item).GetComponentInChildren<FlashlightVolumetric>(true)?.Refresh(enabled: false);
			}
			if (ModConfig.EnableFlashlightDustMotes.Value)
			{
				FlashlightDustMotes.Attach(item)?.Refresh(enabled);
			}
			else
			{
				((Component)item).GetComponentInChildren<FlashlightDustMotes>(true)?.Refresh(enabled: false);
			}
		}

		private static void AttachFillLight(FlashlightItem item)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing

patchers/LethalGraphics/LethalGraphics.Patcher.dll

Decompiled 2 weeks 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.Versioning;
using Microsoft.CodeAnalysis;
using Mono.Cecil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalGraphics.Patcher")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LethalGraphics.Patcher")]
[assembly: AssemblyTitle("LethalGraphics.Patcher")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 LethalGraphics.Patcher
{
	public static class FSR2NativePatcher
	{
		public static IEnumerable<string> TargetDLLs { get; } = Enumerable.Empty<string>();

		public static void Patch(ref AssemblyDefinition assembly)
		{
		}

		public static void Initialize()
		{
			try
			{
				CopyNativePluginIfNeeded();
			}
			catch (Exception arg)
			{
				Console.WriteLine($"[LethalGraphics.Patcher] FSR2 native plugin copy failed: {arg}");
			}
		}

		private static void CopyNativePluginIfNeeded()
		{
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			if (directoryName == null)
			{
				return;
			}
			string text = Path.Combine(directoryName, "fsr2-unity-plugin.dll");
			if (!File.Exists(text))
			{
				Console.WriteLine("[LethalGraphics.Patcher] fsr2-unity-plugin.dll not found next to the patcher at " + text + ", skipping.");
				return;
			}
			string text2 = Path.Combine(Path.GetFullPath(Path.Combine(directoryName, "..", "..", "..")), "Lethal Company_Data", "Plugins", "x86_64");
			string text3 = Path.Combine(text2, "fsr2-unity-plugin.dll");
			Directory.CreateDirectory(text2);
			if (!File.Exists(text3) || new FileInfo(text).Length != new FileInfo(text3).Length || File.GetLastWriteTimeUtc(text) > File.GetLastWriteTimeUtc(text3))
			{
				File.Copy(text, text3, overwrite: true);
				Console.WriteLine("[LethalGraphics.Patcher] Copied fsr2-unity-plugin.dll to " + text2 + ".");
			}
		}
	}
}