Decompiled source of Performance Traffic Control v1.1.0

BepInEx/plugins/PerformanceTrafficControl/PerformanceTrafficControl.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using AIGraph;
using Agents;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Enemies;
using HarmonyLib;
using IRF;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using PerformanceTrafficControl.Api;
using PerformanceTrafficControl.Core;
using PerformanceTrafficControl.Diagnostics;
using PerformanceTrafficControl.Modules;
using PerformanceTrafficControl.Optimization;
using PerformanceTrafficControl.Performance;
using Player;
using UnityEngine;
using UnityEngine.Rendering;
using WindVolume;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Performance Traffic Control")]
[assembly: AssemblyProduct("Performance Traffic Control")]
[assembly: AssemblyFileVersion("0.2.4.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.2.4.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace PerformanceTrafficControl.Performance
{
	internal sealed class AdaptivePerformanceModule : TrafficControlModuleBase
	{
		private const float SampleInterval = 0.25f;

		private const float InitialWarmupSeconds = 5f;

		private const float EnvironmentCheckInterval = 10f;

		private const float MaximumValidSampleSeconds = 1.5f;

		private const float MinimumValidFps = 5f;

		private const float MaximumValidFps = 500f;

		private const float FpsSmoothingAlpha = 0.35f;

		private const float DefaultHighTriggerRatio = 0.85f;

		private const float DefaultCriticalTriggerRatio = 0.75f;

		private const float HighRecoveryRatio = 0.9f;

		private const float CriticalRecoveryRatio = 0.86f;

		private const int HighEnterSampleCount = 6;

		private const int CriticalEnterSampleCount = 3;

		private const int HighRecoverySampleCount = 32;

		private const int CriticalRecoverySampleCount = 20;

		private const int BaselineSamplesPerWindow = 8;

		private const int BaselineWindowCapacity = 20;

		private const int MinimumBaselineWindowCount = 12;

		private const float StableWindowLowerRatio = 0.82f;

		private const float StableWindowUpperRatio = 1.18f;

		private const float BaselinePercentile = 0.65f;

		private const float BaselinePersistInterval = 60f;

		private const float AudioStatePruneInterval = 10f;

		private const float DiagnosticInterval = 30f;

		private readonly float[] _stableBaselineWindows = new float[20];

		private readonly float[] _baselineSortScratch = new float[20];

		private TrafficControlConfig? _config;

		private bool _profileInitialized;

		private bool _sampleAnchorSet;

		private string _environmentFingerprint = string.Empty;

		private float _monitoringStartsAt;

		private float _nextSampleAt;

		private float _nextEnvironmentCheckAt;

		private float _lastSampleRealtime;

		private int _lastSampleFrame;

		private float _latestWindowFps;

		private float _smoothedFps;

		private float _baselineFps;

		private float _lastPersistedBaselineFps;

		private float _nextBaselinePersistAt;

		private float _baselineWindowFpsSum;

		private float _baselineWindowMinFps;

		private float _baselineWindowMaxFps;

		private int _baselineWindowSampleCount;

		private int _stableBaselineWindowCount;

		private int _stableBaselineWindowWriteIndex;

		private int _highPressureSamples;

		private int _criticalPressureSamples;

		private int _recoverySamples;

		private float _nextAudioStatePruneAt;

		private float _nextDiagnosticAt;

		public override string Name => "Adaptive performance pressure";

		private bool AdaptivePerformanceEnabled => _config?.AdaptivePerformanceEnabled.Value ?? true;

		private float HighTriggerRatio
		{
			get
			{
				float num = _config?.HighTriggerRatio.Value ?? 0.85f;
				if (!float.IsNaN(num))
				{
					return Mathf.Clamp(num, 0.5f, 0.95f);
				}
				return 0.85f;
			}
		}

		private float CriticalTriggerRatio
		{
			get
			{
				float num = _config?.CriticalTriggerRatio.Value ?? 0.75f;
				if (!float.IsNaN(num))
				{
					return Mathf.Clamp(num, 0.3f, HighTriggerRatio - 0.05f);
				}
				return 0.75f;
			}
		}

		public override void Initialize(TrafficControlModuleContext context)
		{
			_config = context.Config;
			_config.AdaptivePerformanceEnabled.SettingChanged += delegate
			{
				HandleAdaptiveSettingsChanged();
			};
			_config.HighTriggerRatio.SettingChanged += delegate
			{
				ResetPressureCounters();
			};
			_config.CriticalTriggerRatio.SettingChanged += delegate
			{
				ResetPressureCounters();
			};
			_config.ResetLearnedBaseline.SettingChanged += delegate
			{
				HandleResetRequested();
			};
			_config.BenchmarkForcedPressureLevel.SettingChanged += delegate
			{
				HandleBenchmarkOverrideChanged();
			};
			HandleResetRequested();
		}

		public override void Tick(float now, bool isInLevel)
		{
			PerformancePressureLevel level;
			if (!isInLevel)
			{
				SetLevel(PerformancePressureLevel.Normal, "outside an active level");
				SuspendSampling();
			}
			else if (TryGetBenchmarkPressure(out level))
			{
				SetLevel(level, "diagnostic benchmark override");
				SuspendSampling();
			}
			else if (!AdaptivePerformanceEnabled)
			{
				SetLevel(PerformancePressureLevel.Normal, "adaptive performance disabled");
				SuspendSampling();
			}
			else if (!_profileInitialized)
			{
				InitializeEnvironmentProfile(now);
			}
			else if (_monitoringStartsAt <= 0f)
			{
				_monitoringStartsAt = now + 5f;
				_nextSampleAt = _monitoringStartsAt;
			}
			else
			{
				if (now < _monitoringStartsAt || now < _nextSampleAt)
				{
					return;
				}
				_nextSampleAt = now + 0.25f;
				if (!Application.isFocused)
				{
					ResetSampleAnchor();
					ResetPressureCounters();
					return;
				}
				if (now >= _nextEnvironmentCheckAt)
				{
					_nextEnvironmentCheckAt = now + 10f;
					string text = BuildEnvironmentFingerprint();
					if (!string.Equals(text, _environmentFingerprint, StringComparison.Ordinal))
					{
						InitializeEnvironmentProfile(now, text);
						return;
					}
				}
				SamplePerformance(now);
				RunMaintenance(now);
			}
		}

		public override void OnLevelEntered()
		{
			_monitoringStartsAt = 0f;
			_nextSampleAt = 0f;
			_nextDiagnosticAt = 0f;
			_nextAudioStatePruneAt = 0f;
			ResetSampleAnchor();
			ResetPressureCounters();
			ResetBaselineAccumulator();
		}

		public override void OnLevelExited()
		{
			PersistLearnedProfile(float.MaxValue, force: true);
			SetLevel(PerformancePressureLevel.Normal, "level exited");
			SuspendSampling();
			ResetPressureCounters();
			ResetBaselineAccumulator();
			TrafficControlPerformance.ResetForLevelExit();
			TrafficControlPerformance.UpdateMeasurements(0f, _baselineFps);
		}

		private void SamplePerformance(float now)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			int frameCount = Time.frameCount;
			if (!_sampleAnchorSet)
			{
				_sampleAnchorSet = true;
				_lastSampleRealtime = realtimeSinceStartup;
				_lastSampleFrame = frameCount;
				return;
			}
			float num = realtimeSinceStartup - _lastSampleRealtime;
			int num2 = frameCount - _lastSampleFrame;
			_lastSampleRealtime = realtimeSinceStartup;
			_lastSampleFrame = frameCount;
			if (num <= 0.05f || num > 1.5f || num2 <= 0)
			{
				ResetPressureCounters();
				ResetBaselineAccumulator();
				return;
			}
			float num3 = (float)num2 / num;
			if (num3 < 5f || num3 > 500f)
			{
				ResetPressureCounters();
				ResetBaselineAccumulator();
				return;
			}
			_latestWindowFps = num3;
			_smoothedFps = ((_smoothedFps <= 0.01f) ? num3 : Mathf.Lerp(_smoothedFps, num3, 0.35f));
			TrafficControlPerformance.UpdateMeasurements(_smoothedFps, _baselineFps);
			AccumulateBaselineSample(num3, now);
			if (_baselineFps > 0f)
			{
				EvaluatePressure();
			}
		}

		private void EvaluatePressure()
		{
			float num = _baselineFps * HighTriggerRatio;
			float num2 = _baselineFps * CriticalTriggerRatio;
			_highPressureSamples = ((_smoothedFps < num) ? (_highPressureSamples + 1) : 0);
			_criticalPressureSamples = ((_smoothedFps < num2) ? (_criticalPressureSamples + 1) : 0);
			switch (TrafficControlPerformance.Level)
			{
			case PerformancePressureLevel.Normal:
				_recoverySamples = 0;
				if (_criticalPressureSamples >= 3)
				{
					SetLevel(PerformancePressureLevel.Critical, "FPS stayed below the learned critical ratio");
				}
				else if (_highPressureSamples >= 6)
				{
					SetLevel(PerformancePressureLevel.High, "FPS stayed below the learned high ratio");
				}
				break;
			case PerformancePressureLevel.High:
				if (_criticalPressureSamples >= 3)
				{
					SetLevel(PerformancePressureLevel.Critical, "FPS stayed below the learned critical ratio");
					break;
				}
				_recoverySamples = ((_smoothedFps >= _baselineFps * 0.9f) ? (_recoverySamples + 1) : 0);
				if (_recoverySamples >= 32)
				{
					SetLevel(PerformancePressureLevel.Normal, "FPS recovered toward the learned baseline");
				}
				break;
			case PerformancePressureLevel.Critical:
				_recoverySamples = ((_smoothedFps >= _baselineFps * 0.86f) ? (_recoverySamples + 1) : 0);
				if (_recoverySamples >= 20)
				{
					SetLevel(PerformancePressureLevel.High, "FPS recovered from critical pressure");
				}
				break;
			}
		}

		private void AccumulateBaselineSample(float windowFps, float now)
		{
			if (_baselineWindowSampleCount == 0)
			{
				_baselineWindowMinFps = windowFps;
				_baselineWindowMaxFps = windowFps;
			}
			else
			{
				_baselineWindowMinFps = Mathf.Min(_baselineWindowMinFps, windowFps);
				_baselineWindowMaxFps = Mathf.Max(_baselineWindowMaxFps, windowFps);
			}
			_baselineWindowFpsSum += windowFps;
			_baselineWindowSampleCount++;
			if (_baselineWindowSampleCount < 8)
			{
				return;
			}
			float num = _baselineWindowFpsSum / (float)_baselineWindowSampleCount;
			bool num2 = _baselineWindowMinFps >= num * 0.82f && _baselineWindowMaxFps <= num * 1.18f;
			ResetBaselineAccumulator();
			if (!num2)
			{
				return;
			}
			_stableBaselineWindows[_stableBaselineWindowWriteIndex] = num;
			_stableBaselineWindowWriteIndex = (_stableBaselineWindowWriteIndex + 1) % 20;
			_stableBaselineWindowCount = Math.Min(20, _stableBaselineWindowCount + 1);
			if (_stableBaselineWindowCount >= 12)
			{
				float num3 = CalculateBaselineCandidate();
				if (_baselineFps <= 0f)
				{
					_baselineFps = num3;
					TrafficControlPerformance.UpdateMeasurements(_smoothedFps, _baselineFps);
					PersistLearnedProfile(now, force: true);
					TrafficControlLog.Info($"[PTC_PERF] Learned initial baseline {_baselineFps:0.0} FPS. " + $"High<{_baselineFps * HighTriggerRatio:0.0} Critical<{_baselineFps * CriticalTriggerRatio:0.0}.");
				}
				else if (!(num3 <= _baselineFps * 1.01f))
				{
					float num4 = Mathf.Max(0.5f, _baselineFps * 0.005f);
					_baselineFps = Mathf.Min(num3, _baselineFps + num4);
					TrafficControlPerformance.UpdateMeasurements(_smoothedFps, _baselineFps);
					PersistLearnedProfile(now, force: false);
				}
			}
		}

		private float CalculateBaselineCandidate()
		{
			for (int i = 0; i < _stableBaselineWindowCount; i++)
			{
				_baselineSortScratch[i] = _stableBaselineWindows[i];
			}
			Array.Sort(_baselineSortScratch, 0, _stableBaselineWindowCount);
			int num = Mathf.RoundToInt((float)(_stableBaselineWindowCount - 1) * 0.65f);
			return Mathf.Clamp(_baselineSortScratch[num], 5f, 500f);
		}

		private void InitializeEnvironmentProfile(float now, string? fingerprint = null)
		{
			if (fingerprint == null)
			{
				fingerprint = BuildEnvironmentFingerprint();
			}
			string b = _config?.LearnedProfileFingerprint.Value ?? string.Empty;
			float num = _config?.LearnedBaselineFps.Value ?? 0f;
			bool flag = string.Equals(fingerprint, b, StringComparison.Ordinal) && !float.IsNaN(num) && num >= 5f;
			_environmentFingerprint = fingerprint;
			_profileInitialized = true;
			_baselineFps = (flag ? Mathf.Clamp(num, 5f, 500f) : 0f);
			_lastPersistedBaselineFps = _baselineFps;
			_latestWindowFps = 0f;
			_smoothedFps = 0f;
			_monitoringStartsAt = now + 5f;
			_nextSampleAt = _monitoringStartsAt;
			_nextEnvironmentCheckAt = now + 10f;
			_nextBaselinePersistAt = now + 60f;
			ResetSampleAnchor();
			ResetPressureCounters();
			ClearBaselineLearningState();
			SetLevel(PerformancePressureLevel.Normal, flag ? "performance profile initialized" : "graphics profile changed; learning a new baseline");
			TrafficControlPerformance.UpdateMeasurements(0f, _baselineFps);
			if (!flag && _config != null)
			{
				_config.LearnedBaselineFps.Value = 0f;
				_config.LearnedProfileFingerprint.Value = fingerprint;
			}
			TrafficControlLog.Info(flag ? $"[PTC_PERF] Loaded baseline {_baselineFps:0.0} FPS; sampling at 4 Hz." : "[PTC_PERF] No matching graphics profile; learning a baseline after warmup.");
		}

		private static string BuildEnvironmentFingerprint()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return $"GPU={SystemInfo.graphicsDeviceName}|Screen={Screen.width}x{Screen.height}|" + $"Display={Screen.currentResolution}|Fullscreen={Screen.fullScreen}|" + $"Quality={QualitySettings.GetQualityLevel()}|VSync={QualitySettings.vSyncCount}|" + $"Target={Application.targetFrameRate}";
			}
			catch (Exception ex)
			{
				TrafficControlLog.InfoRateLimited("Performance:EnvironmentFingerprint", "[PTC_PERF] Could not read graphics profile: " + ex.Message, 30f);
				return "GraphicsEnvironmentUnavailable";
			}
		}

		private void PersistLearnedProfile(float now, bool force)
		{
			if (_config == null || !_profileInitialized || _baselineFps < 5f)
			{
				return;
			}
			bool flag = _lastPersistedBaselineFps <= 0f || Mathf.Abs(_baselineFps - _lastPersistedBaselineFps) >= Mathf.Max(2f, _lastPersistedBaselineFps * 0.02f);
			if (force || (!(now < _nextBaselinePersistAt) && flag))
			{
				if (!string.Equals(_config.LearnedProfileFingerprint.Value, _environmentFingerprint, StringComparison.Ordinal))
				{
					_config.LearnedProfileFingerprint.Value = _environmentFingerprint;
				}
				if (Mathf.Abs(_config.LearnedBaselineFps.Value - _baselineFps) >= 0.05f)
				{
					_config.LearnedBaselineFps.Value = _baselineFps;
				}
				_lastPersistedBaselineFps = _baselineFps;
				_nextBaselinePersistAt = now + 60f;
			}
		}

		private void RunMaintenance(float now)
		{
			if (now >= _nextAudioStatePruneAt)
			{
				_nextAudioStatePruneAt = now + 10f;
				TrafficControlPerformance.PruneAudioState(now, 10f);
			}
			TrafficControlConfig? config = _config;
			if (config != null && config.PerformanceDiagnosticsEnabled.Value && !(now < _nextDiagnosticAt))
			{
				_nextDiagnosticAt = now + 30f;
				float num = Mathf.Clamp01((float)_stableBaselineWindowCount / 12f) * 100f;
				TrafficControlLog.Info($"[PTC_PERF] Level={TrafficControlPerformance.Level} FPS={_smoothedFps:0.0} " + $"WindowFPS={_latestWindowFps:0.0} Baseline={_baselineFps:0.0} Confidence={num:0}% " + $"DeniedPhysics={TrafficControlPerformance.DeniedPhysicsQueries} " + $"DeniedVisual={TrafficControlPerformance.DeniedVisualSpawns} " + $"DeniedAudio={TrafficControlPerformance.DeniedAudioEvents}.");
			}
		}

		private void HandleAdaptiveSettingsChanged()
		{
			ResetPressureCounters();
			SuspendSampling();
			if (!AdaptivePerformanceEnabled && !TryGetBenchmarkPressure(out var _))
			{
				SetLevel(PerformancePressureLevel.Normal, "disabled by config");
			}
		}

		private void HandleBenchmarkOverrideChanged()
		{
			ResetPressureCounters();
			SuspendSampling();
		}

		private bool TryGetBenchmarkPressure(out PerformancePressureLevel level)
		{
			level = PerformancePressureLevel.Normal;
			switch (_config?.BenchmarkForcedPressureLevel.Value ?? 0)
			{
			case 1:
				return true;
			case 2:
				level = PerformancePressureLevel.High;
				return true;
			case 3:
				level = PerformancePressureLevel.Critical;
				return true;
			default:
				return false;
			}
		}

		private void HandleResetRequested()
		{
			TrafficControlConfig? config = _config;
			if (config != null && config.ResetLearnedBaseline.Value)
			{
				ClearLearnedProfile("config reset requested");
				_config.ResetLearnedBaseline.Value = false;
			}
		}

		private void ClearLearnedProfile(string reason)
		{
			_profileInitialized = false;
			_environmentFingerprint = string.Empty;
			_baselineFps = 0f;
			_lastPersistedBaselineFps = 0f;
			_latestWindowFps = 0f;
			_smoothedFps = 0f;
			SuspendSampling();
			ResetPressureCounters();
			ClearBaselineLearningState();
			if (_config != null)
			{
				_config.LearnedBaselineFps.Value = 0f;
				_config.LearnedProfileFingerprint.Value = string.Empty;
			}
			SetLevel(PerformancePressureLevel.Normal, reason);
			TrafficControlPerformance.UpdateMeasurements(0f, 0f);
			TrafficControlLog.Info("[PTC_PERF] Cleared learned baseline. Reason=" + reason + ".");
		}

		private void SuspendSampling()
		{
			_monitoringStartsAt = 0f;
			_nextSampleAt = 0f;
			ResetSampleAnchor();
			ResetBaselineAccumulator();
		}

		private void ResetSampleAnchor()
		{
			_sampleAnchorSet = false;
			_lastSampleRealtime = 0f;
			_lastSampleFrame = 0;
		}

		private void ResetPressureCounters()
		{
			_highPressureSamples = 0;
			_criticalPressureSamples = 0;
			_recoverySamples = 0;
		}

		private void ResetBaselineAccumulator()
		{
			_baselineWindowFpsSum = 0f;
			_baselineWindowMinFps = 0f;
			_baselineWindowMaxFps = 0f;
			_baselineWindowSampleCount = 0;
		}

		private void ClearBaselineLearningState()
		{
			ResetBaselineAccumulator();
			Array.Clear(_stableBaselineWindows, 0, _stableBaselineWindows.Length);
			Array.Clear(_baselineSortScratch, 0, _baselineSortScratch.Length);
			_stableBaselineWindowCount = 0;
			_stableBaselineWindowWriteIndex = 0;
		}

		private void SetLevel(PerformancePressureLevel level, string reason)
		{
			if (TrafficControlPerformance.Level != level)
			{
				PerformancePressureLevel level2 = TrafficControlPerformance.Level;
				ResetPressureCounters();
				TrafficControlPerformance.UpdateMeasurements(_smoothedFps, _baselineFps);
				TrafficControlPerformance.SetPressure(level);
				TrafficControlLog.Info($"[PTC_PERF] Pressure {level2} -> {level}. FPS={_smoothedFps:0.0}, " + $"Baseline={_baselineFps:0.0}. Reason={reason}.");
			}
		}
	}
}
namespace PerformanceTrafficControl.Optimization
{
	internal sealed class EnemyVisualOptimizationModule : TrafficControlModuleBase
	{
		public override string Name => "Adaptive enemy visual optimization";

		public override void Initialize(TrafficControlModuleContext context)
		{
			EnemyVisualRuntime.Configure(context.Config);
			context.Harmony.PatchAll(typeof(EnemyVisualPatches));
		}

		public override void OnLevelEntered()
		{
			EnemyVisualRuntime.OnLevelEntered();
		}

		public override void OnLevelExited()
		{
			EnemyVisualRuntime.OnLevelExited();
		}
	}
	internal static class EnemyVisualRuntime
	{
		private sealed class EnemyVisualState
		{
			private readonly RendererEntry[] _renderers;

			private readonly SkinnedRendererEntry[] _skinnedRenderers;

			private bool _shadowsSuppressed;

			private bool _modelQualityApplied;

			internal EnemyAgent Enemy { get; set; }

			internal bool Alive { get; set; }

			internal bool Active { get; set; }

			private EnemyVisualState(EnemyAgent enemy, RendererEntry[] renderers, SkinnedRendererEntry[] skinnedRenderers)
			{
				Enemy = enemy;
				_renderers = renderers;
				_skinnedRenderers = skinnedRenderers;
				Alive = IsEnemyAlive(enemy);
			}

			internal static EnemyVisualState Capture(EnemyAgent enemy)
			{
				try
				{
					Il2CppArrayBase<Renderer> componentsInChildren = ((Component)enemy).GetComponentsInChildren<Renderer>(true);
					RendererEntry[] array = new RendererEntry[componentsInChildren.Length];
					for (int i = 0; i < componentsInChildren.Length; i++)
					{
						array[i] = new RendererEntry(componentsInChildren[i]);
					}
					Il2CppArrayBase<SkinnedMeshRenderer> componentsInChildren2 = ((Component)enemy).GetComponentsInChildren<SkinnedMeshRenderer>(true);
					SkinnedRendererEntry[] array2 = new SkinnedRendererEntry[componentsInChildren2.Length];
					for (int j = 0; j < componentsInChildren2.Length; j++)
					{
						array2[j] = new SkinnedRendererEntry(componentsInChildren2[j]);
					}
					return new EnemyVisualState(enemy, array, array2);
				}
				catch (Exception ex)
				{
					TrafficControlLog.InfoRateLimited("EnemyVisuals:Capture", "[EnemyVisuals] Failed to cache enemy renderers: " + ex.Message, 2f);
					return new EnemyVisualState(enemy, Array.Empty<RendererEntry>(), Array.Empty<SkinnedRendererEntry>());
				}
			}

			internal void ApplyPressureOverrides()
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				SuppressShadows();
				if (TryGetConfiguredModelSkinQuality(out var quality))
				{
					ApplyModelSkinQuality(quality);
				}
				else
				{
					RestoreModelSkinQuality();
				}
			}

			internal void SuppressShadows()
			{
				//IL_0033: 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)
				if (!s_shadowSuppressionAllowed || IsShadowLikeEnemy(Enemy))
				{
					return;
				}
				for (int i = 0; i < _renderers.Length; i++)
				{
					RendererEntry rendererEntry = _renderers[i];
					Renderer renderer = rendererEntry.Renderer;
					if ((Object)(object)renderer != (Object)null && (int)renderer.shadowCastingMode != 0)
					{
						if (!_shadowsSuppressed)
						{
							rendererEntry.ShadowMode = renderer.shadowCastingMode;
						}
						renderer.shadowCastingMode = (ShadowCastingMode)0;
					}
				}
				_shadowsSuppressed = true;
			}

			internal void RestoreShadows()
			{
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				if (!_shadowsSuppressed)
				{
					return;
				}
				for (int i = 0; i < _renderers.Length; i++)
				{
					RendererEntry rendererEntry = _renderers[i];
					if ((Object)(object)rendererEntry.Renderer != (Object)null && rendererEntry.Renderer.shadowCastingMode != rendererEntry.ShadowMode)
					{
						rendererEntry.Renderer.shadowCastingMode = rendererEntry.ShadowMode;
					}
				}
				_shadowsSuppressed = false;
			}

			private void ApplyModelSkinQuality(SkinQuality quality)
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_003a: 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_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				for (int i = 0; i < _skinnedRenderers.Length; i++)
				{
					SkinnedRendererEntry skinnedRendererEntry = _skinnedRenderers[i];
					SkinnedMeshRenderer renderer = skinnedRendererEntry.Renderer;
					if (!((Object)(object)renderer == (Object)null) && (renderer.quality == skinnedRendererEntry.OriginalQuality || renderer.quality == skinnedRendererEntry.AppliedQuality))
					{
						renderer.quality = quality;
						skinnedRendererEntry.AppliedQuality = quality;
						_modelQualityApplied = true;
					}
				}
			}

			private void RestoreModelSkinQuality()
			{
				//IL_004a: 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_0030: 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)
				if (!_modelQualityApplied)
				{
					return;
				}
				for (int i = 0; i < _skinnedRenderers.Length; i++)
				{
					SkinnedRendererEntry skinnedRendererEntry = _skinnedRenderers[i];
					if ((Object)(object)skinnedRendererEntry.Renderer != (Object)null && skinnedRendererEntry.Renderer.quality == skinnedRendererEntry.AppliedQuality)
					{
						skinnedRendererEntry.Renderer.quality = skinnedRendererEntry.OriginalQuality;
					}
					skinnedRendererEntry.AppliedQuality = skinnedRendererEntry.OriginalQuality;
				}
				_modelQualityApplied = false;
			}

			internal void RestorePressureOverrides()
			{
				RestoreShadows();
				RestoreModelSkinQuality();
			}
		}

		private sealed class RagdollState
		{
			internal ES_Dead DeadState { get; }

			internal LinkedListNode<ulong> Node { get; }

			internal RagdollState(ES_Dead deadState, LinkedListNode<ulong> node)
			{
				DeadState = deadState;
				Node = node;
			}
		}

		private sealed class RendererEntry
		{
			internal Renderer Renderer { get; }

			internal ShadowCastingMode ShadowMode { get; set; }

			internal RendererEntry(Renderer renderer)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				Renderer = renderer;
				ShadowMode = (ShadowCastingMode)(((Object)(object)renderer != (Object)null) ? ((int)renderer.shadowCastingMode) : 0);
			}
		}

		private sealed class SkinnedRendererEntry
		{
			internal SkinnedMeshRenderer Renderer { get; }

			internal SkinQuality OriginalQuality { get; }

			internal SkinQuality AppliedQuality { get; set; }

			internal SkinnedRendererEntry(SkinnedMeshRenderer renderer)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				Renderer = renderer;
				OriginalQuality = (SkinQuality)(((Object)(object)renderer != (Object)null) ? ((int)renderer.quality) : 0);
				AppliedQuality = OriginalQuality;
			}
		}

		private static readonly Dictionary<ulong, EnemyVisualState> Enemies = new Dictionary<ulong, EnemyVisualState>();

		private static readonly Dictionary<ulong, RagdollState> Ragdolls = new Dictionary<ulong, RagdollState>();

		private static readonly LinkedList<ulong> RagdollOrder = new LinkedList<ulong>();

		private static TrafficControlConfig? s_config;

		private static bool s_levelActive;

		private static bool s_pressureActive;

		private static int s_activeEnemyCount;

		private static bool s_shadowSuppressionAllowed = true;

		private static readonly int[] ShadowEnemyDataIds = new int[3] { 21, 35, 40 };

		internal static bool Enabled => s_config?.EnemyVisualOptimizationEnabled.Value ?? false;

		internal static int ActiveEnemyCount => s_activeEnemyCount;

		internal static int RagdollCount => Ragdolls.Count;

		private static int MaximumRagdolls => Math.Max(0, s_config?.MaximumRagdollsUnderPressure.Value ?? 12);

		internal static void Configure(TrafficControlConfig config)
		{
			s_config = config;
			s_shadowSuppressionAllowed = DetectShadowSuppressionSupport();
			if (!s_shadowSuppressionAllowed)
			{
				TrafficControlLog.Warning("[EnemyVisuals] AMD GPU detected; enemy shadow suppression is disabled to avoid stale shadow-map artifacts.");
			}
			TrafficControlPerformance.PressureChanged += OnPressureChanged;
			config.EnemyVisualOptimizationEnabled.SettingChanged += delegate
			{
				OnEnabledSettingChanged();
			};
			config.MaximumRagdollsUnderPressure.SettingChanged += delegate
			{
				ReapplyPressureSettings();
			};
			config.CorpseDecaySecondsUnderPressure.SettingChanged += delegate
			{
				ReapplyPressureSettings();
			};
			config.EnemyModelSkinQualityUnderPressure.SettingChanged += delegate
			{
				ReapplyPressureSettings();
			};
		}

		internal static void OnLevelEntered()
		{
			s_levelActive = true;
			UpdatePressureMode();
		}

		internal static void OnLevelExited()
		{
			s_levelActive = false;
			s_pressureActive = false;
			RestoreAllVisuals();
			Enemies.Clear();
			Ragdolls.Clear();
			RagdollOrder.Clear();
			s_activeEnemyCount = 0;
		}

		internal static void RegisterEnemy(EnemyAgent? enemy)
		{
			if (!Enabled || (Object)(object)enemy == (Object)null)
			{
				return;
			}
			ulong enemyKey = GetEnemyKey(enemy);
			if (enemyKey != 0L)
			{
				if (!Enemies.TryGetValue(enemyKey, out EnemyVisualState value))
				{
					value = EnemyVisualState.Capture(enemy);
					Enemies[enemyKey] = value;
				}
				else
				{
					value.Enemy = enemy;
				}
				SetActiveState(value, IsActiveEnemy(enemy));
				if (s_pressureActive)
				{
					value.ApplyPressureOverrides();
				}
			}
		}

		internal static void OnModeChanged(EnemyAI? ai)
		{
			RegisterEnemy((ai != null) ? ai.m_enemyAgent : null);
		}

		internal static void OnEnemyDamaged(EnemyAgent? enemy)
		{
			if (Enabled && !((Object)(object)enemy == (Object)null) && IsEnemyAlive(enemy))
			{
				EnemyVisualState orRegister = GetOrRegister(enemy);
				if (orRegister != null)
				{
					SetActiveState(orRegister, active: true);
				}
			}
		}

		internal static void OnEnemyDead(EnemyAgent? enemy)
		{
			if ((Object)(object)enemy == (Object)null)
			{
				return;
			}
			EnemyVisualState orRegister = GetOrRegister(enemy);
			if (orRegister != null)
			{
				orRegister.Alive = false;
				SetActiveState(orRegister, active: false);
				if (s_pressureActive)
				{
					orRegister.ApplyPressureOverrides();
				}
			}
		}

		internal static void OnEnemyDespawned(EnemyAgent? enemy)
		{
			ulong enemyKey = GetEnemyKey(enemy);
			if (enemyKey == 0L)
			{
				return;
			}
			if (Enemies.TryGetValue(enemyKey, out EnemyVisualState value))
			{
				if (value.Active)
				{
					s_activeEnemyCount = Math.Max(0, s_activeEnemyCount - 1);
				}
				value.RestorePressureOverrides();
				Enemies.Remove(enemyKey);
			}
			RemoveRagdoll(enemyKey);
		}

		internal static void AdjustDecayDuration(ES_Dead? deadState, ref float duration)
		{
			if (s_pressureActive && !IsShadowLikeEnemy(TryGetDeadEnemy(deadState)))
			{
				float num = s_config?.CorpseDecaySecondsUnderPressure.Value ?? 1f;
				duration = (float.IsNaN(num) ? 1f : Mathf.Clamp(num, 1f, 30f));
			}
		}

		internal static void OnDeadStateEntered(ES_Dead? deadState)
		{
			if (s_pressureActive)
			{
				EnemyAgent enemy = TryGetDeadEnemy(deadState);
				if (!IsShadowLikeEnemy(enemy))
				{
					GetOrRegister(enemy)?.ApplyPressureOverrides();
				}
			}
		}

		internal static void OnRagdollStateChanged(ES_Dead? deadState, bool enabled)
		{
			if (!Enabled || deadState == null)
			{
				return;
			}
			EnemyAgent enemy = TryGetDeadEnemy(deadState);
			ulong enemyKey = GetEnemyKey(enemy);
			if (enemyKey == 0L)
			{
				return;
			}
			if (IsShadowLikeEnemy(enemy))
			{
				RemoveRagdoll(enemyKey);
				return;
			}
			if (!enabled)
			{
				RemoveRagdoll(enemyKey);
				return;
			}
			RemoveRagdoll(enemyKey);
			LinkedListNode<ulong> node = RagdollOrder.AddLast(enemyKey);
			Ragdolls[enemyKey] = new RagdollState(deadState, node);
			if (s_pressureActive)
			{
				TrimRagdolls(MaximumRagdolls, disableRagdoll: true);
			}
			else
			{
				TrimRagdolls(Math.Max(64, MaximumRagdolls * 4), disableRagdoll: false);
			}
		}

		private static void OnPressureChanged(PerformancePressureLevel previous, PerformancePressureLevel current)
		{
			UpdatePressureMode();
		}

		private static void OnEnabledSettingChanged()
		{
			if (!Enabled)
			{
				s_pressureActive = false;
				RestoreAllVisuals();
				Enemies.Clear();
				Ragdolls.Clear();
				RagdollOrder.Clear();
				s_activeEnemyCount = 0;
			}
			else
			{
				UpdatePressureMode();
			}
		}

		private static void ReapplyPressureSettings()
		{
			if (!s_pressureActive)
			{
				return;
			}
			foreach (EnemyVisualState value in Enemies.Values)
			{
				value.ApplyPressureOverrides();
			}
			TrimRagdolls(MaximumRagdolls, disableRagdoll: true);
		}

		private static void UpdatePressureMode()
		{
			bool flag = Enabled && s_levelActive && TrafficControlPerformance.IsHighOrWorse;
			if (flag == s_pressureActive)
			{
				return;
			}
			s_pressureActive = flag;
			if (flag)
			{
				foreach (EnemyVisualState value in Enemies.Values)
				{
					value.ApplyPressureOverrides();
				}
				TrimRagdolls(MaximumRagdolls, disableRagdoll: true);
				TrafficControlLog.Info($"[EnemyVisuals] Pressure mode enabled. Level={TrafficControlPerformance.Level} " + $"FPS={TrafficControlPerformance.SmoothedFps:0.0}/{TrafficControlPerformance.LearnedBaselineFps:0.0} " + $"ActiveEnemies={s_activeEnemyCount} Ragdolls={Ragdolls.Count}/{MaximumRagdolls}.");
			}
			else
			{
				RestoreAllVisuals();
				TrafficControlLog.Info("[EnemyVisuals] Pressure mode disabled; cached shadow modes restored.");
			}
		}

		private static EnemyVisualState? GetOrRegister(EnemyAgent? enemy)
		{
			if (!Enabled || (Object)(object)enemy == (Object)null)
			{
				return null;
			}
			ulong enemyKey = GetEnemyKey(enemy);
			if (enemyKey == 0L)
			{
				return null;
			}
			if (Enemies.TryGetValue(enemyKey, out EnemyVisualState value))
			{
				value.Enemy = enemy;
				return value;
			}
			value = EnemyVisualState.Capture(enemy);
			Enemies[enemyKey] = value;
			if (s_pressureActive)
			{
				value.ApplyPressureOverrides();
			}
			return value;
		}

		private static void SetActiveState(EnemyVisualState state, bool active)
		{
			state.Alive = IsEnemyAlive(state.Enemy);
			active &= state.Alive;
			if (state.Active != active)
			{
				state.Active = active;
				s_activeEnemyCount += (active ? 1 : (-1));
				if (s_activeEnemyCount < 0)
				{
					s_activeEnemyCount = 0;
				}
			}
		}

		private static bool IsActiveEnemy(EnemyAgent enemy)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			if (!IsEnemyAlive(enemy) || (Object)(object)enemy.AI == (Object)null)
			{
				return false;
			}
			try
			{
				AgentMode mode = ((AgentAI)enemy.AI).Mode;
				return (int)mode != 4 && (int)mode > 0;
			}
			catch
			{
				return false;
			}
		}

		private static bool IsEnemyAlive(EnemyAgent? enemy)
		{
			if ((Object)(object)enemy == (Object)null || !((Agent)enemy).Alive)
			{
				return false;
			}
			try
			{
				return (Object)(object)enemy.Damage != (Object)null && ((Dam_SyncedDamageBase)enemy.Damage).Health > 0f;
			}
			catch
			{
				return true;
			}
		}

		private static ulong GetEnemyKey(EnemyAgent? enemy)
		{
			if ((Object)(object)enemy == (Object)null)
			{
				return 0uL;
			}
			try
			{
				return (uint)((Object)enemy).GetInstanceID();
			}
			catch
			{
				return 0uL;
			}
		}

		private static EnemyAgent? TryGetDeadEnemy(ES_Dead? deadState)
		{
			try
			{
				object result;
				if (deadState == null)
				{
					result = null;
				}
				else
				{
					EnemyRagdollBodyController bodyController = deadState.m_bodyController;
					result = ((bodyController != null) ? bodyController.m_owner : null);
				}
				return (EnemyAgent?)result;
			}
			catch
			{
				return null;
			}
		}

		private static void TrimRagdolls(int maximum, bool disableRagdoll)
		{
			while (Ragdolls.Count > maximum && RagdollOrder.First != null)
			{
				ulong value = RagdollOrder.First.Value;
				if (!Ragdolls.TryGetValue(value, out RagdollState value2))
				{
					RagdollOrder.RemoveFirst();
					continue;
				}
				Ragdolls.Remove(value);
				RagdollOrder.Remove(value2.Node);
				if (!disableRagdoll)
				{
					continue;
				}
				try
				{
					if (value2.DeadState != null)
					{
						value2.DeadState.SetRagdollEnabled(false);
					}
				}
				catch (Exception ex)
				{
					TrafficControlLog.InfoRateLimited("EnemyVisuals:RagdollDisable", "[EnemyVisuals] Failed to disable an expired ragdoll: " + ex.Message, 2f);
				}
			}
		}

		private static void RemoveRagdoll(ulong key)
		{
			if (Ragdolls.TryGetValue(key, out RagdollState value))
			{
				Ragdolls.Remove(key);
				RagdollOrder.Remove(value.Node);
			}
		}

		private static void RestoreAllVisuals()
		{
			foreach (EnemyVisualState value in Enemies.Values)
			{
				value.RestorePressureOverrides();
			}
		}

		private static bool TryGetConfiguredModelSkinQuality(out SkinQuality quality)
		{
			quality = (SkinQuality)0;
			switch (s_config?.EnemyModelSkinQualityUnderPressure.Value ?? 0)
			{
			case 1:
				quality = (SkinQuality)1;
				return true;
			case 2:
				quality = (SkinQuality)2;
				return true;
			case 4:
				quality = (SkinQuality)4;
				return true;
			default:
				return false;
			}
		}

		private static bool IsShadowLikeEnemy(EnemyAgent? enemy)
		{
			if ((Object)(object)enemy == (Object)null)
			{
				return false;
			}
			try
			{
				uint enemyDataID = enemy.EnemyDataID;
				for (int i = 0; i < ShadowEnemyDataIds.Length; i++)
				{
					if (enemyDataID == ShadowEnemyDataIds[i])
					{
						return true;
					}
				}
			}
			catch
			{
			}
			try
			{
				return ((Object)enemy).name.IndexOf("shadow", StringComparison.OrdinalIgnoreCase) >= 0 || ((Object)enemy).name.IndexOf("blackthorn", StringComparison.OrdinalIgnoreCase) >= 0 || ((Object)enemy).name.IndexOf("black_thorn", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			catch
			{
				return false;
			}
		}

		private static bool DetectShadowSuppressionSupport()
		{
			try
			{
				string text = SystemInfo.graphicsDeviceVendor ?? string.Empty;
				string text2 = SystemInfo.graphicsDeviceName ?? string.Empty;
				return text.IndexOf("amd", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("ati", StringComparison.OrdinalIgnoreCase) < 0 && text2.IndexOf("amd", StringComparison.OrdinalIgnoreCase) < 0 && text2.IndexOf("radeon", StringComparison.OrdinalIgnoreCase) < 0 && text2.IndexOf("ati", StringComparison.OrdinalIgnoreCase) < 0;
			}
			catch
			{
				return false;
			}
		}
	}
	[HarmonyPatch]
	internal static class EnemyVisualPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAgent), "Setup")]
		private static void EnemyAgentSetupPostfix(EnemyAgent __instance)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.RegisterEnemy(__instance);
			}, "register enemy");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "ModeChange")]
		private static void EnemyAiModeChangePostfix(EnemyAI __instance)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.OnModeChanged(__instance);
			}, "update enemy mode");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAgent), "OnTakeDamage")]
		private static void EnemyAgentTakeDamagePostfix(EnemyAgent __instance)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.OnEnemyDamaged(__instance);
			}, "wake damaged enemy");
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyAgent), "OnDead")]
		private static void EnemyAgentOnDeadPrefix(EnemyAgent __instance)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.OnEnemyDead(__instance);
			}, "record enemy death");
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyAgent), "OnDeSpawn")]
		private static void EnemyAgentOnDespawnPrefix(EnemyAgent __instance)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.OnEnemyDespawned(__instance);
			}, "remove despawned enemy");
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ES_Dead), "DecayDelayed")]
		private static void EnemyDecayPrefix(ES_Dead __instance, ref float duration)
		{
			EnemyVisualRuntime.AdjustDecayDuration(__instance, ref duration);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ES_Dead), "CommonEnter")]
		private static void EnemyDeadEnterPostfix(ES_Dead __instance)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.OnDeadStateEntered(__instance);
			}, "suppress corpse shadows");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ES_Dead), "SetRagdollEnabled")]
		private static void EnemyRagdollPostfix(ES_Dead __instance, bool enabled)
		{
			RunSafe(delegate
			{
				EnemyVisualRuntime.OnRagdollStateChanged(__instance, enabled);
			}, "update ragdoll budget");
		}

		private static void RunSafe(Action action, string operation)
		{
			try
			{
				action();
			}
			catch (Exception ex)
			{
				TrafficControlLog.InfoRateLimited("EnemyVisuals:" + operation, "[EnemyVisuals] Failed to " + operation + ": " + ex.Message, 2f);
			}
		}
	}
	internal sealed class FogOptimizationModule : TrafficControlModuleBase
	{
		public override string Name => "Adaptive volumetric fog traffic control";

		public override void Initialize(TrafficControlModuleContext context)
		{
			FogOptimizationRuntime.Configure(context.Config);
			context.Harmony.PatchAll(typeof(FogOptimizationPatches));
		}

		public override void Tick(float now, bool isInLevel)
		{
			FogOptimizationRuntime.Tick(now, isInLevel);
		}

		public override void OnLevelEntered()
		{
			FogOptimizationRuntime.OnLevelEntered();
		}

		public override void OnLevelExited()
		{
			FogOptimizationRuntime.OnLevelExited();
		}
	}
	internal static class FogOptimizationRuntime
	{
		private sealed class FogQualityState
		{
			internal PreLitVolume Volume { get; }

			internal int OriginalAa { get; }

			internal int OriginalBlur { get; }

			internal int OriginalPostBlur { get; }

			internal int AppliedAa { get; private set; }

			internal int AppliedBlur { get; private set; }

			internal int AppliedPostBlur { get; private set; }

			internal FogQualityState(PreLitVolume volume)
			{
				Volume = volume;
				OriginalAa = volume.FogAACount;
				OriginalBlur = volume.IndirectBlurSamples;
				OriginalPostBlur = volume.FogPostBlur;
				AppliedAa = OriginalAa;
				AppliedBlur = OriginalBlur;
				AppliedPostBlur = OriginalPostBlur;
			}

			internal bool Apply(int maximumAa, int maximumBlur, bool disablePostBlur)
			{
				bool flag = false;
				try
				{
					int num = Math.Min(OriginalAa, maximumAa);
					int num2 = Math.Min(OriginalBlur, maximumBlur);
					int num3 = ((!disablePostBlur) ? OriginalPostBlur : 0);
					if (Volume.FogAACount == OriginalAa || Volume.FogAACount == AppliedAa)
					{
						flag |= Volume.FogAACount != num;
						Volume.FogAACount = num;
						AppliedAa = num;
					}
					if (Volume.IndirectBlurSamples == OriginalBlur || Volume.IndirectBlurSamples == AppliedBlur)
					{
						flag |= Volume.IndirectBlurSamples != num2;
						Volume.IndirectBlurSamples = num2;
						AppliedBlur = num2;
					}
					if (Volume.FogPostBlur == OriginalPostBlur || Volume.FogPostBlur == AppliedPostBlur)
					{
						flag |= Volume.FogPostBlur != num3;
						Volume.FogPostBlur = num3;
						AppliedPostBlur = num3;
					}
				}
				catch
				{
				}
				return flag;
			}

			internal bool Restore()
			{
				bool flag = false;
				try
				{
					if (Volume.FogAACount == AppliedAa)
					{
						flag |= Volume.FogAACount != OriginalAa;
						Volume.FogAACount = OriginalAa;
					}
					if (Volume.IndirectBlurSamples == AppliedBlur)
					{
						flag |= Volume.IndirectBlurSamples != OriginalBlur;
						Volume.IndirectBlurSamples = OriginalBlur;
					}
					if (Volume.FogPostBlur == AppliedPostBlur)
					{
						flag |= Volume.FogPostBlur != OriginalPostBlur;
						Volume.FogPostBlur = OriginalPostBlur;
					}
					AppliedAa = OriginalAa;
					AppliedBlur = OriginalBlur;
					AppliedPostBlur = OriginalPostBlur;
				}
				catch
				{
				}
				return flag;
			}
		}

		private static readonly Dictionary<int, FogQualityState> QualityStates = new Dictionary<int, FogQualityState>();

		private static TrafficControlConfig? s_config;

		private static bool s_levelActive;

		private static bool s_forceNextUpdate = true;

		private static bool s_lastTransition;

		private static bool s_hasTransitionSample;

		private static float s_nextCollectAt;

		private static int s_lastActiveFogSphereCount = -1;

		private static long s_commandsAllowed;

		private static long s_commandsSkipped;

		internal static bool Enabled => s_config?.FogOptimizationEnabled.Value ?? false;

		internal static bool Active
		{
			get
			{
				if (Enabled && s_levelActive)
				{
					return TrafficControlPerformance.IsCritical;
				}
				return false;
			}
		}

		private static float VolumeUpdateHz
		{
			get
			{
				float num = s_config?.FogCriticalVolumeUpdateHz.Value ?? 10f;
				if (!float.IsNaN(num))
				{
					return Mathf.Clamp(num, 1f, 120f);
				}
				return 10f;
			}
		}

		internal static void Configure(TrafficControlConfig config)
		{
			s_config = config;
			TrafficControlPerformance.PressureChanged += OnPressureChanged;
			config.FogOptimizationEnabled.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogHighVolumeUpdateHz.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogCriticalVolumeUpdateHz.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogHighAaCount.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogCriticalAaCount.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogHighIndirectBlurSamples.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogCriticalIndirectBlurSamples.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.FogDisablePostBlurCritical.SettingChanged += delegate
			{
				ReapplySettings();
			};
		}

		internal static void Tick(float now, bool isInLevel)
		{
			if (!isInLevel)
			{
				return;
			}
			try
			{
				PreLitVolume current = PreLitVolume.Current;
				if ((Object)(object)current != (Object)null)
				{
					RegisterVolume(current);
					ApplyQuality(current);
				}
			}
			catch
			{
			}
		}

		internal static void OnLevelEntered()
		{
			s_levelActive = true;
			ResetCadence();
			ResetCounters();
		}

		internal static void OnLevelExited()
		{
			s_levelActive = false;
			RestoreQuality();
			QualityStates.Clear();
			ResetCadence();
			ResetCounters();
		}

		internal static bool ShouldCollectCommands(PreLitVolume? volume)
		{
			if (!Active || (Object)(object)volume == (Object)null)
			{
				s_commandsAllowed++;
				return true;
			}
			try
			{
				RegisterVolume(volume);
				ApplyQuality(volume);
				EnvironmentStateManager current = EnvironmentStateManager.Current;
				bool flag = current != null && current.m_hasOngoingFogTransition;
				bool flag2 = !s_hasTransitionSample || flag != s_lastTransition;
				s_hasTransitionSample = true;
				s_lastTransition = flag;
				int num = PreLitVolume.s_activeFogSpheres?.Count ?? 0;
				bool flag3 = num != s_lastActiveFogSphereCount;
				s_lastActiveFogSphereCount = num;
				float unscaledTime = Time.unscaledTime;
				if (!s_forceNextUpdate && !flag2 && !flag3 && unscaledTime + 0.0001f < s_nextCollectAt)
				{
					s_commandsSkipped++;
					return false;
				}
				s_forceNextUpdate = false;
				s_nextCollectAt = unscaledTime + 1f / VolumeUpdateHz;
				s_commandsAllowed++;
				return true;
			}
			catch
			{
				s_commandsAllowed++;
				return true;
			}
		}

		internal static void ForceNextUpdate()
		{
			s_forceNextUpdate = true;
			s_nextCollectAt = 0f;
		}

		internal static FogOptimizationSnapshot ConsumeSnapshot()
		{
			int aa = -1;
			int blur = -1;
			int postBlur = -1;
			try
			{
				PreLitVolume current = PreLitVolume.Current;
				if ((Object)(object)current != (Object)null)
				{
					aa = current.FogAACount;
					blur = current.IndirectBlurSamples;
					postBlur = current.FogPostBlur;
				}
			}
			catch
			{
			}
			FogOptimizationSnapshot result = new FogOptimizationSnapshot(s_commandsAllowed, s_commandsSkipped, aa, blur, postBlur);
			ResetCounters();
			return result;
		}

		private static void OnPressureChanged(PerformancePressureLevel previous, PerformancePressureLevel current)
		{
			ResetCadence();
			ApplyQualityToCurrent();
		}

		private static void ReapplySettings()
		{
			ResetCadence();
			ApplyQualityToCurrent();
		}

		private static void ApplyQualityToCurrent()
		{
			if (!Active)
			{
				RestoreQuality();
				return;
			}
			try
			{
				PreLitVolume current = PreLitVolume.Current;
				if ((Object)(object)current != (Object)null)
				{
					RegisterVolume(current);
					ApplyQuality(current);
				}
			}
			catch
			{
			}
		}

		private static void RegisterVolume(PreLitVolume volume)
		{
			try
			{
				int instanceID = ((Object)volume).GetInstanceID();
				if (!QualityStates.ContainsKey(instanceID))
				{
					QualityStates[instanceID] = new FogQualityState(volume);
				}
			}
			catch
			{
			}
		}

		private static void ApplyQuality(PreLitVolume volume)
		{
			if (!Active)
			{
				RestoreQuality();
				return;
			}
			try
			{
				if (!QualityStates.TryGetValue(((Object)volume).GetInstanceID(), out FogQualityState value))
				{
					RegisterVolume(volume);
					if (!QualityStates.TryGetValue(((Object)volume).GetInstanceID(), out value))
					{
						return;
					}
				}
				int num = ((!TrafficControlPerformance.IsCritical) ? (s_config?.FogHighAaCount.Value ?? 2) : (s_config?.FogCriticalAaCount.Value ?? 1));
				int num2 = ((!TrafficControlPerformance.IsCritical) ? (s_config?.FogHighIndirectBlurSamples.Value ?? 2) : (s_config?.FogCriticalIndirectBlurSamples.Value ?? 1));
				bool disablePostBlur = TrafficControlPerformance.IsCritical && (s_config?.FogDisablePostBlurCritical.Value ?? true);
				if (value.Apply(Mathf.Clamp(num, 1, 8), Mathf.Clamp(num2, 0, 8), disablePostBlur))
				{
					ForceNextUpdate();
				}
			}
			catch
			{
			}
		}

		private static void RestoreQuality()
		{
			bool flag = false;
			foreach (FogQualityState value in QualityStates.Values)
			{
				flag |= value.Restore();
			}
			if (flag)
			{
				ForceNextUpdate();
			}
		}

		private static void ResetCadence()
		{
			s_forceNextUpdate = true;
			s_nextCollectAt = 0f;
			s_hasTransitionSample = false;
			s_lastActiveFogSphereCount = -1;
		}

		private static void ResetCounters()
		{
			s_commandsAllowed = 0L;
			s_commandsSkipped = 0L;
		}
	}
	internal readonly struct FogOptimizationSnapshot
	{
		internal long CommandsAllowed { get; }

		internal long CommandsSkipped { get; }

		internal int Aa { get; }

		internal int Blur { get; }

		internal int PostBlur { get; }

		internal FogOptimizationSnapshot(long commandsAllowed, long commandsSkipped, int aa, int blur, int postBlur)
		{
			CommandsAllowed = commandsAllowed;
			CommandsSkipped = commandsSkipped;
			Aa = aa;
			Blur = blur;
			PostBlur = postBlur;
		}
	}
	[HarmonyPatch]
	internal static class FogOptimizationPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(PreLitVolume), "CollectCommands", new Type[] { typeof(CommandBuffer) })]
		private static bool CollectCommandsPrefix(PreLitVolume __instance)
		{
			return FogOptimizationRuntime.ShouldCollectCommands(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnvironmentStateManager), "AttemptStartFogTransition", new Type[]
		{
			typeof(uint),
			typeof(float),
			typeof(eDimensionIndex)
		})]
		private static void FogTransitionPostfix()
		{
			FogOptimizationRuntime.ForceNextUpdate();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PreLitVolume), "OnResolutionChange", new Type[]
		{
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		private static void ResolutionChangedPostfix()
		{
			FogOptimizationRuntime.ForceNextUpdate();
		}
	}
	internal static class VegetationClassifier
	{
		internal static bool IsVegetation(InstancedRenderFeature? irf, out string descriptorName)
		{
			descriptorName = string.Empty;
			if ((Object)(object)irf == (Object)null)
			{
				return false;
			}
			try
			{
				InstancedRenderFeatureDescriptor descriptor = irf.Descriptor;
				descriptorName = ((descriptor != null) ? ((Object)descriptor).name : null) ?? string.Empty;
				GameObject gameObject = ((Component)irf).gameObject;
				string text = ((gameObject != null) ? ((Object)gameObject).name : null) ?? string.Empty;
				if ((Object)(object)irf.m_enemyRoot != (Object)null || irf.DynamicTransforms)
				{
					return false;
				}
				string text2 = (descriptorName + "|" + text).ToLowerInvariant();
				if (text2.Contains("enemy") || text2.Contains("tentacle") || text2.Contains("cable") || text2.Contains("ragdoll"))
				{
					return false;
				}
				return text2.Contains("plant") || text2.Contains("grass") || text2.Contains("ivy") || text2.Contains("fern") || text2.Contains("flower") || text2.Contains("mushroom") || text2.Contains("vine") || text2.Contains("tree") || text2.Contains("branch") || text2.Contains("weed") || text2.Contains("monstera") || text2.Contains("philodendron") || text2.Contains("banana") || text2.Contains("poppy") || text2.Contains("ficus") || text2.Contains("tropicalstick") || text2.Contains("snakeplant");
			}
			catch
			{
				return false;
			}
		}
	}
	internal sealed class VegetationOptimizationModule : TrafficControlModuleBase
	{
		public override string Name => "Adaptive vegetation traffic control";

		public override void Initialize(TrafficControlModuleContext context)
		{
			VegetationOptimizationRuntime.Configure(context.Config);
			context.Harmony.PatchAll(typeof(VegetationOptimizationPatches));
		}

		public override void Tick(float now, bool isInLevel)
		{
			VegetationOptimizationRuntime.Tick(now, isInLevel);
		}

		public override void OnLevelEntered()
		{
			VegetationOptimizationRuntime.OnLevelEntered();
		}

		public override void OnLevelExited()
		{
			VegetationOptimizationRuntime.OnLevelExited();
		}
	}
	internal static class VegetationOptimizationRuntime
	{
		private sealed class VegetationState
		{
			internal InstancedRenderFeature Instance { get; set; }

			internal string DescriptorName { get; }

			internal float Phase { get; }

			internal float NextLateUpdateAt { get; set; }

			internal float NextRendererUpdateAt { get; set; }

			internal float AccumulatedDeltaTime { get; set; }

			internal Vector3 LastCameraPosition { get; set; }

			internal Quaternion LastCameraRotation { get; set; }

			internal bool HasCameraSample { get; set; }

			internal bool ForceNextUpdate { get; set; }

			internal VegetationState(InstancedRenderFeature instance, string descriptorName, int key)
			{
				Instance = instance;
				DescriptorName = descriptorName;
				Phase = (float)(uint)((key * -1640531535) & 0x3FF) / 1024f;
			}
		}

		private sealed class DescriptorState
		{
			private const float FloatTolerance = 0.001f;

			internal InstancedRenderFeatureDescriptor Descriptor { get; }

			internal float OriginalMaxDistance { get; }

			internal bool OriginalCastShadows { get; }

			internal float OriginalWindAmount { get; }

			internal float OriginalTurbulenceAmount { get; }

			internal float AppliedMaxDistance { get; private set; }

			internal bool AppliedCastShadows { get; private set; }

			internal float AppliedWindAmount { get; private set; }

			internal float AppliedTurbulenceAmount { get; private set; }

			internal DescriptorState(InstancedRenderFeatureDescriptor descriptor)
			{
				Descriptor = descriptor;
				OriginalMaxDistance = descriptor.MaxDistance;
				OriginalCastShadows = descriptor.CastShadows;
				OriginalWindAmount = descriptor.WindAmount;
				OriginalTurbulenceAmount = descriptor.TurbulenceAmount;
				AppliedMaxDistance = OriginalMaxDistance;
				AppliedCastShadows = OriginalCastShadows;
				AppliedWindAmount = OriginalWindAmount;
				AppliedTurbulenceAmount = OriginalTurbulenceAmount;
			}

			internal void Apply(float distanceScale, bool suppressShadows, bool freezeAnimation)
			{
				try
				{
					float num = ((OriginalMaxDistance > 1f) ? (OriginalMaxDistance * distanceScale) : OriginalMaxDistance);
					if (ApproximatelyOwned(Descriptor.MaxDistance, OriginalMaxDistance, AppliedMaxDistance))
					{
						Descriptor.MaxDistance = num;
						AppliedMaxDistance = num;
					}
					bool flag = !suppressShadows && OriginalCastShadows;
					if (Descriptor.CastShadows == OriginalCastShadows || Descriptor.CastShadows == AppliedCastShadows)
					{
						Descriptor.CastShadows = flag;
						AppliedCastShadows = flag;
					}
					float num2 = (freezeAnimation ? 0f : OriginalWindAmount);
					if (ApproximatelyOwned(Descriptor.WindAmount, OriginalWindAmount, AppliedWindAmount))
					{
						Descriptor.WindAmount = num2;
						AppliedWindAmount = num2;
					}
					float num3 = (freezeAnimation ? 0f : OriginalTurbulenceAmount);
					if (ApproximatelyOwned(Descriptor.TurbulenceAmount, OriginalTurbulenceAmount, AppliedTurbulenceAmount))
					{
						Descriptor.TurbulenceAmount = num3;
						AppliedTurbulenceAmount = num3;
					}
				}
				catch
				{
				}
			}

			internal void Restore()
			{
				try
				{
					if (Mathf.Abs(Descriptor.MaxDistance - AppliedMaxDistance) <= 0.001f)
					{
						Descriptor.MaxDistance = OriginalMaxDistance;
					}
					if (Descriptor.CastShadows == AppliedCastShadows)
					{
						Descriptor.CastShadows = OriginalCastShadows;
					}
					if (Mathf.Abs(Descriptor.WindAmount - AppliedWindAmount) <= 0.001f)
					{
						Descriptor.WindAmount = OriginalWindAmount;
					}
					if (Mathf.Abs(Descriptor.TurbulenceAmount - AppliedTurbulenceAmount) <= 0.001f)
					{
						Descriptor.TurbulenceAmount = OriginalTurbulenceAmount;
					}
					AppliedMaxDistance = OriginalMaxDistance;
					AppliedCastShadows = OriginalCastShadows;
					AppliedWindAmount = OriginalWindAmount;
					AppliedTurbulenceAmount = OriginalTurbulenceAmount;
				}
				catch
				{
				}
			}

			private static bool ApproximatelyOwned(float current, float original, float applied)
			{
				if (!(Mathf.Abs(current - original) <= 0.001f))
				{
					return Mathf.Abs(current - applied) <= 0.001f;
				}
				return true;
			}
		}

		private const float ZoneCheckInterval = 0.1f;

		private const float CameraMoveThresholdSqr = 0.0625f;

		private const float CameraAngleThreshold = 2f;

		private const float MaximumAccumulatedDeltaTime = 0.25f;

		private static readonly Dictionary<int, VegetationState> States = new Dictionary<int, VegetationState>();

		private static readonly Dictionary<int, DescriptorState> Descriptors = new Dictionary<int, DescriptorState>();

		private static TrafficControlConfig? s_config;

		private static bool s_levelActive;

		private static int s_currentZoneInstanceId;

		private static float s_nextZoneCheckAt;

		private static long s_lateUpdateAllowed;

		private static long s_lateUpdateSkipped;

		private static long s_rendererUpdateAllowed;

		private static long s_rendererUpdateSkipped;

		internal static bool Enabled => s_config?.VegetationOptimizationEnabled.Value ?? false;

		internal static bool Active
		{
			get
			{
				if (Enabled && s_levelActive)
				{
					return TrafficControlPerformance.IsHighOrWorse;
				}
				return false;
			}
		}

		private static float VisibleUpdateHz => ClampHz((!TrafficControlPerformance.IsCritical) ? (s_config?.VegetationHighVisibleUpdateHz.Value ?? 5f) : (s_config?.VegetationCriticalVisibleUpdateHz.Value ?? 2f), 0.5f, 120f);

		private static float HiddenUpdateHz => ClampHz((!TrafficControlPerformance.IsCritical) ? (s_config?.VegetationHighHiddenUpdateHz.Value ?? 2f) : (s_config?.VegetationCriticalHiddenUpdateHz.Value ?? 1f), 0.25f, 60f);

		private static float RemoteUpdateHz => ClampHz((!TrafficControlPerformance.IsCritical) ? (s_config?.VegetationHighRemoteUpdateHz.Value ?? 0.5f) : (s_config?.VegetationCriticalRemoteUpdateHz.Value ?? 0.25f), 0.25f, 30f);

		private static float DistanceScale => Mathf.Clamp((!TrafficControlPerformance.IsCritical) ? (s_config?.VegetationHighDistanceScale.Value ?? 0.75f) : (s_config?.VegetationCriticalDistanceScale.Value ?? 0.5f), 0.25f, 1f);

		private static bool FreezeAnimation => s_config?.VegetationFreezeAnimationUnderPressure.Value ?? true;

		internal static void Configure(TrafficControlConfig config)
		{
			s_config = config;
			TrafficControlPerformance.PressureChanged += OnPressureChanged;
			config.VegetationOptimizationEnabled.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.VegetationFreezeAnimationUnderPressure.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.VegetationHighVisibleUpdateHz.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.VegetationCriticalVisibleUpdateHz.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.VegetationHighHiddenUpdateHz.SettingChanged += delegate
			{
				ResetSchedules();
			};
			config.VegetationCriticalHiddenUpdateHz.SettingChanged += delegate
			{
				ResetSchedules();
			};
			config.VegetationHighRemoteUpdateHz.SettingChanged += delegate
			{
				ResetSchedules();
			};
			config.VegetationCriticalRemoteUpdateHz.SettingChanged += delegate
			{
				ResetSchedules();
			};
			config.VegetationHighDistanceScale.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.VegetationCriticalDistanceScale.SettingChanged += delegate
			{
				ReapplySettings();
			};
			config.VegetationDisableShadowsCritical.SettingChanged += delegate
			{
				ReapplySettings();
			};
		}

		internal static void Tick(float now, bool isInLevel)
		{
			if (!isInLevel || now < s_nextZoneCheckAt)
			{
				return;
			}
			s_nextZoneCheckAt = now + 0.1f;
			int currentZoneInstanceId = GetCurrentZoneInstanceId();
			if (currentZoneInstanceId == s_currentZoneInstanceId)
			{
				return;
			}
			s_currentZoneInstanceId = currentZoneInstanceId;
			foreach (VegetationState value in States.Values)
			{
				value.ForceNextUpdate = IsCurrentZone(value.Instance);
			}
		}

		internal static void OnLevelEntered()
		{
			s_levelActive = true;
			s_currentZoneInstanceId = 0;
			s_nextZoneCheckAt = 0f;
			ResetSchedules();
			ApplyDescriptorQuality();
		}

		internal static void OnLevelExited()
		{
			s_levelActive = false;
			RestoreDescriptors();
			States.Clear();
			Descriptors.Clear();
			s_currentZoneInstanceId = 0;
			s_nextZoneCheckAt = 0f;
			ResetCounters();
		}

		internal static void Register(InstancedRenderFeature? irf)
		{
			if (!VegetationClassifier.IsVegetation(irf, out string descriptorName) || (Object)(object)irf == (Object)null)
			{
				return;
			}
			try
			{
				int instanceID = ((Object)irf).GetInstanceID();
				if (!States.TryGetValue(instanceID, out VegetationState value))
				{
					value = new VegetationState(irf, descriptorName, instanceID);
					States[instanceID] = value;
				}
				else
				{
					value.Instance = irf;
				}
				DescriptorState descriptorState = RegisterDescriptor(irf.Descriptor);
				if (!Active)
				{
					return;
				}
				InitializeSchedule(value, Time.unscaledTime);
				descriptorState?.Apply(DistanceScale, TrafficControlPerformance.IsCritical && (s_config?.VegetationDisableShadowsCritical.Value ?? true), FreezeAnimation);
				try
				{
					InstancedRenderFeatureRenderer renderer = irf.Renderer;
					if (renderer != null)
					{
						renderer.ResetCulling(true);
					}
				}
				catch
				{
				}
			}
			catch
			{
			}
		}

		internal static void Unregister(InstancedRenderFeature? irf)
		{
			if ((Object)(object)irf == (Object)null)
			{
				return;
			}
			try
			{
				States.Remove(((Object)irf).GetInstanceID());
			}
			catch
			{
			}
		}

		internal static bool ShouldRunLateUpdate(InstancedRenderFeature? irf)
		{
			if (!Active || (Object)(object)irf == (Object)null)
			{
				return true;
			}
			try
			{
				if (!States.TryGetValue(((Object)irf).GetInstanceID(), out VegetationState value))
				{
					Register(irf);
					if (!States.TryGetValue(((Object)irf).GetInstanceID(), out value))
					{
						return true;
					}
				}
				if (value.ForceNextUpdate)
				{
					value.ForceNextUpdate = false;
					ScheduleNextLateUpdate(value, Time.unscaledTime, IsCurrentZone(irf));
					s_lateUpdateAllowed++;
					return true;
				}
				if (irf.IsShown)
				{
					s_lateUpdateAllowed++;
					return true;
				}
				float unscaledTime = Time.unscaledTime;
				if (unscaledTime + 0.0001f < value.NextLateUpdateAt)
				{
					s_lateUpdateSkipped++;
					return false;
				}
				ScheduleNextLateUpdate(value, unscaledTime, IsCurrentZone(irf));
				s_lateUpdateAllowed++;
				return true;
			}
			catch
			{
				return true;
			}
		}

		internal static bool PrepareRendererUpdate(InstancedRenderFeatureRenderer? renderer, ref float deltaTime, Camera? cullCamera)
		{
			if (!Active || (Object)(object)((renderer != null) ? renderer.m_irf : null) == (Object)null)
			{
				return true;
			}
			try
			{
				InstancedRenderFeature irf = renderer.m_irf;
				if (!States.TryGetValue(((Object)irf).GetInstanceID(), out VegetationState value))
				{
					Register(irf);
					if (!States.TryGetValue(((Object)irf).GetInstanceID(), out value))
					{
						return true;
					}
				}
				if (FreezeAnimation)
				{
					value.AccumulatedDeltaTime = 0f;
				}
				else
				{
					value.AccumulatedDeltaTime = Mathf.Min(0.25f, value.AccumulatedDeltaTime + Mathf.Max(0f, deltaTime));
				}
				bool flag = HasCameraMoved(value, cullCamera);
				float unscaledTime = Time.unscaledTime;
				if (!value.ForceNextUpdate && !flag && unscaledTime + 0.0001f < value.NextRendererUpdateAt)
				{
					s_rendererUpdateSkipped++;
					return false;
				}
				value.ForceNextUpdate = false;
				deltaTime = (FreezeAnimation ? 0f : Mathf.Max(deltaTime, value.AccumulatedDeltaTime));
				value.AccumulatedDeltaTime = 0f;
				value.NextRendererUpdateAt = unscaledTime + 1f / VisibleUpdateHz;
				CaptureCamera(value, cullCamera);
				s_rendererUpdateAllowed++;
				return true;
			}
			catch
			{
				return true;
			}
		}

		internal static bool ShouldRunControllerUpdate(IRFController? controller)
		{
			if (!Active || !FreezeAnimation || (Object)(object)((controller != null) ? controller.m_target : null) == (Object)null)
			{
				return true;
			}
			try
			{
				InstancedRenderFeature target = controller.m_target;
				if (States.ContainsKey(((Object)target).GetInstanceID()))
				{
					return false;
				}
				Register(target);
				return !States.ContainsKey(((Object)target).GetInstanceID());
			}
			catch
			{
				return true;
			}
		}

		internal static VegetationOptimizationSnapshot ConsumeSnapshot()
		{
			VegetationOptimizationSnapshot result = new VegetationOptimizationSnapshot(States.Count, s_lateUpdateAllowed, s_lateUpdateSkipped, s_rendererUpdateAllowed, s_rendererUpdateSkipped);
			ResetCounters();
			return result;
		}

		private static void OnPressureChanged(PerformancePressureLevel previous, PerformancePressureLevel current)
		{
			ResetSchedules();
			ApplyDescriptorQuality();
		}

		private static void ReapplySettings()
		{
			ResetSchedules();
			ApplyDescriptorQuality();
		}

		private static void ResetSchedules()
		{
			float unscaledTime = Time.unscaledTime;
			foreach (VegetationState value in States.Values)
			{
				InitializeSchedule(value, unscaledTime);
			}
		}

		private static void InitializeSchedule(VegetationState state, float now)
		{
			float phase = state.Phase;
			state.NextLateUpdateAt = now + phase / HiddenUpdateHz;
			state.NextRendererUpdateAt = now + phase / VisibleUpdateHz;
			state.AccumulatedDeltaTime = 0f;
			state.HasCameraSample = false;
			state.ForceNextUpdate = IsCurrentZone(state.Instance);
		}

		private static void ScheduleNextLateUpdate(VegetationState state, float now, bool currentZone)
		{
			float num = (currentZone ? HiddenUpdateHz : RemoteUpdateHz);
			state.NextLateUpdateAt = now + 1f / num;
		}

		private static bool HasCameraMoved(VegetationState state, Camera? camera)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)camera == (Object)null)
			{
				return false;
			}
			Transform transform = ((Component)camera).transform;
			if ((Object)(object)transform == (Object)null || !state.HasCameraSample)
			{
				return false;
			}
			Vector3 val = transform.position - state.LastCameraPosition;
			if (!(((Vector3)(ref val)).sqrMagnitude >= 0.0625f))
			{
				return Quaternion.Angle(transform.rotation, state.LastCameraRotation) >= 2f;
			}
			return true;
		}

		private static void CaptureCamera(VegetationState state, Camera? camera)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)((camera != null) ? ((Component)camera).transform : null) == (Object)null))
			{
				state.LastCameraPosition = ((Component)camera).transform.position;
				state.LastCameraRotation = ((Component)camera).transform.rotation;
				state.HasCameraSample = true;
			}
		}

		private static bool IsCurrentZone(InstancedRenderFeature? irf)
		{
			if ((Object)(object)irf == (Object)null || s_currentZoneInstanceId == 0)
			{
				return true;
			}
			try
			{
				LG_Zone ownerZone = irf.OwnerZone;
				return (Object)(object)ownerZone == (Object)null || ((Object)ownerZone).GetInstanceID() == s_currentZoneInstanceId;
			}
			catch
			{
				return true;
			}
		}

		private static int GetCurrentZoneInstanceId()
		{
			try
			{
				PlayerAgent val = default(PlayerAgent);
				int result;
				if (PlayerManager.TryGetLocalPlayerAgent(ref val))
				{
					object obj;
					if (val == null)
					{
						obj = null;
					}
					else
					{
						AIG_CourseNode courseNode = ((Agent)val).CourseNode;
						obj = ((courseNode != null) ? courseNode.m_zone : null);
					}
					if ((Object)obj != (Object)null)
					{
						result = ((Object)((Agent)val).CourseNode.m_zone).GetInstanceID();
						goto IL_003c;
					}
				}
				result = 0;
				goto IL_003c;
				IL_003c:
				return result;
			}
			catch
			{
				return 0;
			}
		}

		private static DescriptorState? RegisterDescriptor(InstancedRenderFeatureDescriptor? descriptor)
		{
			if ((Object)(object)descriptor == (Object)null)
			{
				return null;
			}
			try
			{
				int instanceID = ((Object)descriptor).GetInstanceID();
				if (!Descriptors.ContainsKey(instanceID))
				{
					Descriptors[instanceID] = new DescriptorState(descriptor);
				}
				return Descriptors[instanceID];
			}
			catch
			{
				return null;
			}
		}

		private static void ApplyDescriptorQuality()
		{
			if (!Active)
			{
				RestoreDescriptors();
				return;
			}
			float distanceScale = DistanceScale;
			bool suppressShadows = TrafficControlPerformance.IsCritical && (s_config?.VegetationDisableShadowsCritical.Value ?? true);
			foreach (DescriptorState value in Descriptors.Values)
			{
				value.Apply(distanceScale, suppressShadows, FreezeAnimation);
			}
			foreach (VegetationState value2 in States.Values)
			{
				try
				{
					InstancedRenderFeature instance = value2.Instance;
					if (instance != null)
					{
						InstancedRenderFeatureRenderer renderer = instance.Renderer;
						if (renderer != null)
						{
							renderer.ResetCulling(true);
						}
					}
				}
				catch
				{
				}
			}
		}

		private static void RestoreDescriptors()
		{
			foreach (DescriptorState value in Descriptors.Values)
			{
				value.Restore();
			}
		}

		private static float ClampHz(float value, float minimum, float maximum)
		{
			if (!float.IsNaN(value))
			{
				return Mathf.Clamp(value, minimum, maximum);
			}
			return minimum;
		}

		private static void ResetCounters()
		{
			s_lateUpdateAllowed = 0L;
			s_lateUpdateSkipped = 0L;
			s_rendererUpdateAllowed = 0L;
			s_rendererUpdateSkipped = 0L;
		}
	}
	internal readonly struct VegetationOptimizationSnapshot
	{
		internal int Registered { get; }

		internal long LateUpdateAllowed { get; }

		internal long LateUpdateSkipped { get; }

		internal long RendererUpdateAllowed { get; }

		internal long RendererUpdateSkipped { get; }

		internal VegetationOptimizationSnapshot(int registered, long lateUpdateAllowed, long lateUpdateSkipped, long rendererUpdateAllowed, long rendererUpdateSkipped)
		{
			Registered = registered;
			LateUpdateAllowed = lateUpdateAllowed;
			LateUpdateSkipped = lateUpdateSkipped;
			RendererUpdateAllowed = rendererUpdateAllowed;
			RendererUpdateSkipped = rendererUpdateSkipped;
		}
	}
	[HarmonyPatch]
	internal static class VegetationOptimizationPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(IRFController), "Update")]
		private static bool IrfControllerUpdatePrefix(IRFController __instance)
		{
			return VegetationOptimizationRuntime.ShouldRunControllerUpdate(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(InstancedRenderFeature), "OnEnable")]
		private static void IrfEnablePostfix(InstancedRenderFeature __instance)
		{
			VegetationOptimizationRuntime.Register(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InstancedRenderFeature), "OnDisable")]
		private static void IrfDisablePrefix(InstancedRenderFeature __instance)
		{
			VegetationOptimizationRuntime.Unregister(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InstancedRenderFeature), "OnDestroy")]
		private static void IrfDestroyPrefix(InstancedRenderFeature __instance)
		{
			VegetationOptimizationRuntime.Unregister(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(InstancedRenderFeature), "Rebuild")]
		private static void IrfRebuildPostfix(InstancedRenderFeature __instance)
		{
			VegetationOptimizationRuntime.Register(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InstancedRenderFeature), "LateUpdate")]
		private static bool IrfLateUpdatePrefix(InstancedRenderFeature __instance)
		{
			return VegetationOptimizationRuntime.ShouldRunLateUpdate(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(InstancedRenderFeatureRenderer), "Update", new Type[]
		{
			typeof(float),
			typeof(Camera)
		})]
		private static bool IrfRendererUpdatePrefix(InstancedRenderFeatureRenderer __instance, ref float deltaTime, Camera cullCamera)
		{
			return VegetationOptimizationRuntime.PrepareRendererUpdate(__instance, ref deltaTime, cullCamera);
		}
	}
	internal sealed class WindVolumeCapacityModule : TrafficControlModuleBase
	{
		public override string Name => "WindVolume capacity guard";

		public override void Initialize(TrafficControlModuleContext context)
		{
			WindVolumeCapacityPatches.Configure(context.Config);
			context.Harmony.PatchAll(typeof(WindVolumeCapacityPatches));
		}
	}
	[HarmonyPatch(typeof(WindVolumeCamera), "UpdateVolume")]
	internal static class WindVolumeCapacityPatches
	{
		private static readonly List<WindVolumeAffector> Suppressed = new List<WindVolumeAffector>();

		private static TrafficControlConfig? s_config;

		private static float s_nextReportAt;

		internal static void Configure(TrafficControlConfig config)
		{
			s_config = config;
		}

		[HarmonyPrefix]
		private static void Prefix()
		{
			Suppressed.Clear();
			TrafficControlConfig? trafficControlConfig = s_config;
			if (trafficControlConfig == null || !trafficControlConfig.WindVolumeCapacityGuardEnabled.Value)
			{
				return;
			}
			HashSet<WindVolumeAffector> instances = WindVolumeAffector.instances;
			if (instances == null)
			{
				return;
			}
			int mAX_AFFECTOR_COUNT = WindVolumeCamera.MAX_AFFECTOR_COUNT;
			if (mAX_AFFECTOR_COUNT <= 0 || instances.Count <= mAX_AFFECTOR_COUNT)
			{
				return;
			}
			int num = 0;
			Enumerator<WindVolumeAffector> enumerator = instances.GetEnumerator();
			while (enumerator.MoveNext())
			{
				WindVolumeAffector current = enumerator.Current;
				if (!((Object)(object)current == (Object)null) && num++ >= mAX_AFFECTOR_COUNT)
				{
					Suppressed.Add(current);
				}
			}
			for (int i = 0; i < Suppressed.Count; i++)
			{
				instances.Remove(Suppressed[i]);
			}
			if (Time.unscaledTime >= s_nextReportAt)
			{
				TrafficControlLog.Warning($"[WindVolumeGuard] Affectors={instances.Count + Suppressed.Count}/{mAX_AFFECTOR_COUNT} " + $"suppressed={Suppressed.Count}.");
				s_nextReportAt = Time.unscaledTime + 30f;
			}
		}

		[HarmonyFinalizer]
		private static void Finalizer()
		{
			HashSet<WindVolumeAffector> instances = WindVolumeAffector.instances;
			if (instances != null)
			{
				for (int i = 0; i < Suppressed.Count; i++)
				{
					WindVolumeAffector val = Suppressed[i];
					if ((Object)(object)val != (Object)null)
					{
						instances.Add(val);
					}
				}
			}
			Suppressed.Clear();
		}
	}
}
namespace PerformanceTrafficControl.Modules
{
	internal interface ITrafficControlModule
	{
		string Name { get; }

		void Initialize(TrafficControlModuleContext context);

		void Tick(float now, bool isInLevel);

		void OnLevelEntered();

		void OnLevelExited();
	}
	internal abstract class TrafficControlModuleBase : ITrafficControlModule
	{
		public abstract string Name { get; }

		public abstract void Initialize(TrafficControlModuleContext context);

		public virtual void Tick(float now, bool isInLevel)
		{
		}

		public virtual void OnLevelEntered()
		{
		}

		public virtual void OnLevelExited()
		{
		}
	}
	internal sealed class TrafficControlModuleContext
	{
		internal Harmony Harmony { get; }

		internal TrafficControlConfig Config { get; }

		internal TrafficControlModuleContext(Harmony harmony, TrafficControlConfig config)
		{
			Harmony = harmony;
			Config = config;
		}
	}
	internal sealed class TrafficControlModuleHost
	{
		private sealed class ModuleSlot
		{
			internal ITrafficControlModule Module { get; }

			internal bool Active { get; set; }

			internal int ConsecutiveFaults { get; set; }

			internal ModuleSlot(ITrafficControlModule module)
			{
				Module = module;
			}
		}

		private readonly List<ModuleSlot> _modules = new List<ModuleSlot>();

		private readonly TrafficControlModuleContext _context;

		internal TrafficControlModuleHost(TrafficControlModuleContext context)
		{
			_context = context;
		}

		internal void Add(ITrafficControlModule module)
		{
			_modules.Add(new ModuleSlot(module));
		}

		internal void Initialize()
		{
			for (int i = 0; i < _modules.Count; i++)
			{
				ModuleSlot moduleSlot = _modules[i];
				try
				{
					moduleSlot.Module.Initialize(_context);
					moduleSlot.Active = true;
					TrafficControlLog.Info("Module initialized: " + moduleSlot.Module.Name + ".");
				}
				catch (Exception exception)
				{
					moduleSlot.Active = false;
					TrafficControlLog.Error("Module initialization failed: " + moduleSlot.Module.Name + ". Other modules will continue.", exception);
				}
			}
		}

		internal void Tick(float now, bool isInLevel)
		{
			for (int i = 0; i < _modules.Count; i++)
			{
				Invoke(_modules[i], delegate(ITrafficControlModule module)
				{
					module.Tick(now, isInLevel);
				}, "tick");
			}
		}

		internal void OnLevelEntered()
		{
			for (int i = 0; i < _modules.Count; i++)
			{
				Invoke(_modules[i], delegate(ITrafficControlModule module)
				{
					module.OnLevelEntered();
				}, "level enter");
			}
		}

		internal void OnLevelExited()
		{
			for (int i = 0; i < _modules.Count; i++)
			{
				Invoke(_modules[i], delegate(ITrafficControlModule module)
				{
					module.OnLevelExited();
				}, "level exit");
			}
			TrafficControlLog.ClearRateLimits();
		}

		private static void Invoke(ModuleSlot slot, Action<ITrafficControlModule> action, string operation)
		{
			if (!slot.Active)
			{
				return;
			}
			try
			{
				action(slot.Module);
				slot.ConsecutiveFaults = 0;
			}
			catch (Exception ex)
			{
				slot.ConsecutiveFaults++;
				TrafficControlLog.InfoRateLimited("ModuleFault:" + slot.Module.Name + ":" + operation, "Module " + slot.Module.Name + " failed during " + operation + ": " + ex.Message, 2f);
				if (slot.ConsecutiveFaults >= 5)
				{
					slot.Active = false;
					TrafficControlLog.Error("Module disabled after repeated " + operation + " failures: " + slot.Module.Name + ".", ex);
				}
			}
		}
	}
}
namespace PerformanceTrafficControl.Diagnostics
{
	internal enum NativeDiagnosticProbe
	{
		FogStateUpdate,
		FogCommandCollection,
		FogVolumeUpdate,
		FogShaderParameters,
		FogGlobalCommands,
		FogResolutionChange,
		FogSphereUpdate,
		FogRepellerUpdate,
		VegetationControllerUpdate,
		VegetationLateUpdate,
		VegetationRendererUpdate,
		VegetationDraw,
		VegetationShadowInjection,
		Count
	}
	internal readonly struct NativeDiagnosticProbeSnapshot
	{
		internal long Calls { get; }

		internal long ElapsedTicks { get; }

		internal NativeDiagnosticProbeSnapshot(long calls, long elapsedTicks)
		{
			Calls = calls;
			ElapsedTicks = elapsedTicks;
		}
	}
	internal sealed class NativePerformanceDiagnosticsModule : TrafficControlModuleBase
	{
		private sealed class MetricAccumulator
		{
			private readonly double[] _samples;

			private readonly double[] _sortScratch;

			private int _sampleCount;

			private long _count;

			private double _sum;

			private double _maximum;

			internal MetricAccumulator(int capacity)
			{
				_samples = new double[capacity];
				_sortScratch = new double[capacity];
			}

			internal void Add(double value)
			{
				if (!double.IsNaN(value) && !double.IsInfinity(value) && !(value <= 0.0))
				{
					_count++;
					_sum += value;
					_maximum = Math.Max(_maximum, value);
					if (_sampleCount < _samples.Length)
					{
						_samples[_sampleCount++] = value;
					}
				}
			}

			internal MetricSnapshot TakeSnapshot()
			{
				double p = 0.0;
				if (_sampleCount > 0)
				{
					Array.Copy(_samples, _sortScratch, _sampleCount);
					Array.Sort(_sortScratch, 0, _sampleCount);
					int val = Math.Min(_sampleCount - 1, (int)Math.Ceiling((double)_sampleCount * 0.95) - 1);
					p = _sortScratch[Math.Max(0, val)];
				}
				MetricSnapshot result = new MetricSnapshot(_count, (_count > 0) ? (_sum / (double)_count) : 0.0, p, _maximum);
				Reset();
				return result;
			}

			internal void Reset()
			{
				_sampleCount = 0;
				_count = 0L;
				_sum = 0.0;
				_maximum = 0.0;
			}
		}

		private readonly struct MetricSnapshot
		{
			internal long Count { get; }

			internal double Average { get; }

			internal double P95 { get; }

			internal double Maximum { get; }

			internal MetricSnapshot(long count, double average, double p95, double maximum)
			{
				Count = count;
				Average = average;
				P95 = p95;
				Maximum = maximum;
			}
		}

		private const int MetricCapacity = 4096;

		private readonly MetricAccumulator _frameMilliseconds = new MetricAccumulator(4096);

		private readonly MetricAccumulator _cpuMilliseconds = new MetricAccumulator(4096);

		private readonly MetricAccumulator _gpuMilliseconds = new MetricAccumulator(4096);

		private Il2CppStructArray<FrameTiming>? _frameTimings;

		private TrafficControlConfig? _config;

		private float _windowStartedAt;

		private float _nextReportAt;

		private int _frameCount;

		private bool _frameTimingAvailable = true;

		public override string Name => "Native fog and vegetation diagnostics";

		private bool Enabled => _config?.NativePerformanceDiagnosticsEnabled.Value ?? true;

		private float ReportInterval => Mathf.Clamp(_config?.NativeDiagnosticsReportIntervalSeconds.Value ?? 5f, 2f, 30f);

		public override void Initialize(TrafficControlModuleContext context)
		{
			_config = context.Config;
			InitializeFrameTiming();
			NativePerformanceDiagnosticsRuntime.SetEnabled(Enabled);
			_config.NativePerformanceDiagnosticsEnabled.SettingChanged += delegate
			{
				HandleEnabledChanged();
			};
			context.Harmony.PatchAll(typeof(NativePerformanceDiagnosticsPatches));
		}

		public override void Tick(float now, bool isInLevel)
		{
			NativePerformanceDiagnosticsRuntime.SetEnabled(Enabled);
			if (!isInLevel || !Enabled || !Application.isFocused)
			{
				NativePerformanceDiagnosticsRuntime.SetDetailedSampleActive(active: false);
				return;
			}
			if (_windowStartedAt <= 0f)
			{
				StartWindow(now);
			}
			_frameCount++;
			_frameMilliseconds.Add((double)Time.unscaledDeltaTime * 1000.0);
			CaptureNativeFrameTiming();
			int num = Math.Max(1, _config?.NativeDiagnosticsDetailedSampleStride.Value ?? 30);
			NativePerformanceDiagnosticsRuntime.SetDetailedSampleActive(Time.frameCount % num == 0);
			if (now >= _nextReportAt)
			{
				Report(now, final: false);
				StartWindow(now);
			}
		}

		public override void OnLevelEntered()
		{
			ResetMetrics();
			NativePerformanceDiagnosticsRuntime.SetEnabled(Enabled);
			NativePerformanceDiagnosticsRuntime.ResetWindow();
			if (Enabled)
			{
				StartWindow(Time.unscaledTime);
				TrafficControlLog.Info("[PTC_DIAG] Native diagnostics started. Optimization state is reported in PTC_DIAG_OPT.");
			}
		}

		public override void OnLevelExited()
		{
			if (Enabled && _frameCount > 0)
			{
				Report(Time.unscaledTime, final: true);
			}
			ResetMetrics();
			NativePerformanceDiagnosticsRuntime.ResetLevel();
		}

		private void CaptureNativeFrameTiming()
		{
			//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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if (!_frameTimingAvailable || _frameTimings == null)
			{
				return;
			}
			try
			{
				FrameTimingManager.CaptureFrameTimings();
				if (FrameTimingManager.GetLatestTimings(1u, _frameTimings) != 0)
				{
					FrameTiming val = ((Il2CppArrayBase<FrameTiming>)(object)_frameTimings)[0];
					_cpuMilliseconds.Add(val.cpuFrameTime);
					_gpuMilliseconds.Add(val.gpuFrameTime);
				}
			}
			catch (Exception ex)
			{
				_frameTimingAvailable = false;
				TrafficControlLog.Warning("[PTC_DIAG] Native FrameTimingManager unavailable: " + ex.Message);
			}
		}

		private void InitializeFrameTiming()
		{
			try
			{
				RuntimeHelpers.RunClassConstructor(typeof(FrameTiming).TypeHandle);
				_frameTimings = new Il2CppStructArray<FrameTiming>(1L);
			}
			catch (Exception ex)
			{
				_frameTimingAvailable = false;
				_frameTimings = null;
				TrafficControlLog.Warning("[PTC_DIAG] Native FrameTimingManager initialization unavailable: " + ex.Message);
			}
		}

		private void Report(float now, bool final)
		{
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected I4, but got Unknown
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			float num = Math.Max(0.001f, now - _windowStartedAt);
			MetricSnapshot metric = _frameMilliseconds.TakeSnapshot();
			MetricSnapshot metric2 = _cpuMilliseconds.TakeSnapshot();
			MetricSnapshot metric3 = _gpuMilliseconds.TakeSnapshot();
			string arg = ClassifyBound(metric2.Average, metric3.Average);
			string arg2 = (final ? "FINAL " : string.Empty);
			eDimensionIndex dimensionIndex;
			string playerZone = GetPlayerZone(out dimensionIndex);
			BenchmarkDiagnosticState benchmarkState = NativePerformanceDiagnosticsRuntime.GetBenchmarkState(now);
			bool flag = IsBenchmarkWindowValid(benchmarkState, playerZone, now);
			TrafficControlLog.Info($"[PTC_DIAG_FRAME] {arg2}Window={num:0.0}s Frames={_frameCount} " + $"FPS={((metric.Average > 0.0) ? (1000.0 / metric.Average) : 0.0):0.0} " + "FrameMs=" + FormatMetric(metric) + " CPUms=" + FormatMetric(metric2) + " GPUms=" + FormatMetric(metric3) + " " + $"Bound={arg} Pressure={TrafficControlPerformance.Level} " + $"Test={benchmarkState.Scenario} TestElapsed={benchmarkState.Elapsed:0.0} TestValid={flag} " + $"Zone={playerZone} Dimension={(int)dimensionIndex}.");
			ReportFog(num, dimensionIndex);
			ReportVegetation();
			ReportOptimization();
			_frameCount = 0;
		}

		private static void ReportFog(float duration, eDimensionIndex dimensionIndex)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			NativeDiagnosticProbeSnapshot probe = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogStateUpdate);
			NativeDiagnosticProbeSnapshot probe2 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogCommandCollection);
			NativeDiagnosticProbeSnapshot probe3 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogVolumeUpdate);
			NativeDiagnosticProbeSnapshot probe4 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogShaderParameters);
			NativeDiagnosticProbeSnapshot probe5 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogGlobalCommands);
			NativeDiagnosticProbeSnapshot probe6 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogResolutionChange);
			NativeDiagnosticProbeSnapshot probe7 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogSphereUpdate);
			NativeDiagnosticProbeSnapshot probe8 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.FogRepellerUpdate);
			FogHandlerDiagnosticSnapshot fogHandlerSnapshot = NativePerformanceDiagnosticsRuntime.GetFogHandlerSnapshot();
			bool flag = false;
			int num = 0;
			string arg = "unavailable";
			string arg2 = "unavailable";
			try
			{
				EnvironmentStateManager current = EnvironmentStateManager.Current;
				flag = current != null && current.m_hasOngoingFogTransition;
				arg = EnvironmentStateManager.GetCurrentFogID(dimensionIndex).ToString();
				num = PreLitVolume.s_activeFogSpheres?.Count ?? 0;
				PreLitVolume current2 = PreLitVolume.Current;
				if ((Object)(object)current2 != (Object)null)
				{
					arg2 = $"{current2.Width}x{current2.Height}x{current2.Depth} AA={current2.FogAACount} " + $"Shadow={current2.FogShadowSamples} PostBlur={current2.FogPostBlur} " + $"IndirectBlur={current2.IndirectBlurSamples} AdvancedGI={current2.AdvancedGI}";
				}
			}
			catch (Exception ex)
			{
				arg2 = "read-error:" + ex.GetType().Name;
			}
			TrafficControlLog.Info($"[PTC_DIAG_FOG] FogID={arg} Transition={flag} Volume={arg2} " + $"FogSpheres={num} Handlers={fogHandlerSnapshot.Playing}/{fogHandlerSnapshot.Total} " + $"CPUmsPerSec UpdateFog={MillisecondsPerSecond(probe, duration):0.000} " + $"Commands={MillisecondsPerSecond(probe2, duration):0.000} " + $"VolumeUpdate={MillisecondsPerSecond(probe3, duration):0.000} " + $"ShaderParams={MillisecondsPerSecond(probe4, duration):0.000} " + $"Globals={MillisecondsPerSecond(probe5, duration):0.000} " + $"Resize={MillisecondsPerSecond(probe6, duration):0.000} " + $"SphereUpdate={MillisecondsPerSecond(probe7, duration):0.000} " + $"RepellerUpdate={MillisecondsPerSecond(probe8, duration):0.000} " + $"Calls={probe.Calls}/{probe2.Calls}/{probe3.Calls}/{probe4.Calls}/" + $"{probe5.Calls}/{probe6.Calls}/{probe7.Calls}/{probe8.Calls}.");
		}

		private static string GetPlayerZone(out eDimensionIndex dimensionIndex)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected I4, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected I4, but got Unknown
			dimensionIndex = (eDimensionIndex)0;
			try
			{
				PlayerAgent val = default(PlayerAgent);
				if (PlayerManager.TryGetLocalPlayerAgent(ref val))
				{
					object obj;
					if (val == null)
					{
						obj = null;
					}
					else
					{
						AIG_CourseNode courseNode = ((Agent)val).CourseNode;
						obj = ((courseNode != null) ? courseNode.m_zone : null);
					}
					if (!((Object)obj == (Object)null))
					{
						LG_Zone zone = ((Agent)val).CourseNode.m_zone;
						dimensionIndex = (eDimensionIndex)(int)zone.DimensionIndex;
						return $"{zone.AliasName}(L{(int)zone.LocalIndex})";
					}
				}
				return "unavailable";
			}
			catch
			{
				return "unavailable";
			}
		}

		private bool IsBenchmarkWindowValid(BenchmarkDiagnosticState benchmark, string zoneText, float now)
		{
			if (!benchmark.Active)
			{
				return true;
			}
			string value = ((benchmark.Scenario == "DenseGardens") ? "(L1)" : "(L4)");
			if (benchmark.Uncontaminated && zoneText.Contains(value, StringComparison.Ordinal) && _windowStartedAt >= benchmark.StartedAt)
			{
				return now >= _windowStartedAt;
			}
			return false;
		}

		private static void ReportVegetation()
		{
			long num = NativePerformanceDiagnosticsRuntime.ConsumeDetailedSampleFrames();
			long sampleFrames = Math.Max(1L, num);
			NativeDiagnosticProbeSnapshot probe = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.VegetationControllerUpdate);
			NativeDiagnosticProbeSnapshot probe2 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.VegetationLateUpdate);
			NativeDiagnosticProbeSnapshot probe3 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.VegetationRendererUpdate);
			NativeDiagnosticProbeSnapshot probe4 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.VegetationDraw);
			NativeDiagnosticProbeSnapshot probe5 = NativePerformanceDiagnosticsRuntime.ConsumeProbe(NativeDiagnosticProbe.VegetationShadowInjection);
			IrfDiagnosticSnapshot irfSnapshot = NativePerformanceDiagnosticsRuntime.GetIrfSnapshot();
			TrafficControlLog.Info($"[PTC_DIAG_IRF] Components={irfSnapshot.VegetationComponents}/{irfSnapshot.TotalComponents} " + $"VegetationInstances={irfSnapshot.VegetationInstances} SampleFrames={num} " + $"MsPerSampleFrame Controller={MillisecondsPerSampleFrame(probe, sampleFrames):0.000} " + $"LateUpdate={MillisecondsPerSampleFrame(probe2, sampleFrames):0.000} " + $"RendererUpdate={MillisecondsPerSampleFrame(probe3, sampleFrames):0.000} " + $"Draw={MillisecondsPerSampleFrame(probe4, sampleFrames):0.000} " + $"Shadow={MillisecondsPerSampleFrame(probe5, sampleFrames):0.000} " + $"CallsPerSampleFrame={CallsPerFrame(probe, sampleFrames):0.0}/" + $"{CallsPerFrame(probe2, sampleFrames):0.0}/" + $"{CallsPerFrame(probe3, sampleFrames):0.0}/" + $"{CallsPerFrame(probe4, sampleFrames):0.0}/" + $"{CallsPerFrame(probe5, sampleFrames):0.0}.");
		}

		private static void ReportOptimization()
		{
			VegetationOptimizationSnapshot vegetationOptimizationSnapshot = VegetationOptimizationRuntime.ConsumeSnapshot();
			FogOptimizationSnapshot fogOptimizationSnapshot = FogOptimizationRuntime.ConsumeSnapshot();
			string optimizationMode = GetOptimizationMode();
			TrafficControlLog.Info($"[PTC_DIAG_OPT] Mode={optimizationMode} Pressure={TrafficControlPerformance.Level} " + $"VegetationActive={VegetationOptimizationRuntime.Active} FogActive={FogOptimizationRuntime.Active} " + $"VegetationRegistered={vegetationOptimizationSnapshot.Registered} " + $"LateUpdate={vegetationOptimizationSnapshot.LateUpdateAllowed}/{vegetationOptimizationSnapshot.LateUpdateSkipped} " + $"RendererUpdate={vegetationOptimizationSnapshot.RendererUpdateAllowed}/{vegetationOptimizationSnapshot.RendererUpdateSkipped} " + $"FogCommands={fogOptimizationSnapshot.CommandsAllowed}/{fogOptimizationSnapshot.CommandsSkipped} " + $"FogQuality=AA{fogOptimizationSnapshot.Aa}/Blur{fogOptimizationSnapshot.Blur}/Post{fogOptimizationSnapshot.PostBlur}.");
		}

		private static string GetOptimizationMode()
		{
			if (VegetationOptimizationRuntime.Enabled)
			{
				if (!FogOptimizationRuntime.Enabled)
				{
					return "VegetationOnly";
				}
				return "Combined";
			}
			if (!FogOptimizationRuntime.Enabled)
			{
				return "Native";
			}
			return "FogOnly";
		}

		private void StartWindow(float now)
		{
			_windowStartedAt = now;
			_nextReportAt = now + ReportInterval;
		}

		private void ResetMetrics()
		{
			_windowStartedAt = 0f;
			_nextReportAt = 0f;
			_frameCount = 0;
			_frameTimingAvailable = _frameTimings != null;
			_frameMilliseconds.Reset();
			_cpuMilliseconds.Reset();
			_gpuMilliseconds.Reset();
		}

		private void HandleEnabledChanged()
		{
			NativePerformanceDiagnosticsRuntime.SetEnabled(Enabled);
			ResetMetrics();
			NativePerformanceDiagnosticsRuntime.ResetWindow();
			TrafficControlLog.Info($"[PTC_DIAG] Native diagnostics enabled={Enabled}.");
		}

		private static string ClassifyBound(double cpuMilliseconds, double gpuMilliseconds)
		{
			if (cpuMilliseconds <= 0.0 || gpuMilliseconds <= 0.0)
			{
				return "Unknown";
			}
			if (cpuMilliseconds >= gpuMilliseconds * 1.15)
			{
				return "CPU";
			}
			if (!(gpuMilliseconds >= cpuMilliseconds * 1.15))
			{
				return "Mixed";
			}
			return "GPU";
		}

		private static string FormatMetric(MetricSnapshot metric)
		{
			if (metric.Count > 0)
			{
				return $"{metric.Average:0.00}/{metric.P95:0.00}/{metric.Maximum:0.00}";
			}
			return "n/a";
		}

		private static double MillisecondsPerSecond(NativeDiagnosticProbeSnapshot probe, float duration)
		{
			return NativePerformanceDiagnosticsRuntime.TicksToMilliseconds(probe.ElapsedTicks) / (double)duration;
		}

		private static double MillisecondsPerSampleFrame(NativeDiagnosticProbeSnapshot probe, long sampleFrames)
		{
			return NativePerformanceDiagnosticsRuntime.TicksToMilliseconds(probe.ElapsedTicks) / (double)sampleFrames;
		}

		private static double CallsPerFrame(NativeDiagnosticProbeSnapshot probe, long sampleFrames)
		{
			return (double)probe.Calls / (double)sampleFrames;
		}
	}
	[HarmonyPatch]
	internal static class NativePerformanceDiagnosticsPatches
	{
		private const float BenchmarkDurationSeconds = 115f;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnvironmentStateManager), "UpdateFog")]
		private static void EnvironmentFogPrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnvironmentStateManager), "UpdateFog")]
		private static void EnvironmentFogPostfix(long __state)
		{
			NativePerformanceDiagnosticsRuntime.EndProbe(NativeDiagnosticProbe.FogStateUpdate, __state);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PreLitVolume), "CollectCommands", new Type[] { typeof(CommandBuffer) })]
		private static void FogCommandsPrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PreLitVolume), "CollectCommands", new Type[] { typeof(CommandBuffer) })]
		private static void FogCommandsPostfix(long __state)
		{
			NativePerformanceDiagnosticsRuntime.EndProbe(NativeDiagnosticProbe.FogCommandCollection, __state);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PreLitVolume), "Update")]
		private static void FogVolumeUpdatePrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PreLitVolume), "Update")]
		private static void FogVolumeUpdatePostfix(long __state)
		{
			NativePerformanceDiagnosticsRuntime.EndProbe(NativeDiagnosticProbe.FogVolumeUpdate, __state);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PreLitVolume), "UpdateShaderParameters")]
		private static void FogShaderParametersPrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PreLitVolume), "UpdateShaderParameters")]
		private static void FogShaderParametersPostfix(long __state)
		{
			NativePerformanceDiagnosticsRuntime.EndProbe(NativeDiagnosticProbe.FogShaderParameters, __state);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PreLitVolume), "CollectCommands_Globals", new Type[] { typeof(CommandBuffer) })]
		private static void FogGlobalCommandsPrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PreLitVolume), "CollectCommands_Globals", new Type[] { typeof(CommandBuffer) })]
		private static void FogGlobalCommandsPostfix(long __state)
		{
			NativePerformanceDiagnosticsRuntime.EndProbe(NativeDiagnosticProbe.FogGlobalCommands, __state);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PreLitVolume), "OnResolutionChange", new Type[]
		{
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		private static void FogResolutionPrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PreLitVolume), "OnResolutionChange", new Type[]
		{
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		private static void FogResolutionPostfix(long __state)
		{
			NativePerformanceDiagnosticsRuntime.EndProbe(NativeDiagnosticProbe.FogResolutionChange, __state);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FogSphereHandler), "Awake")]
		private static void FogSphereAwakePostfix(FogSphereHandler __instance)
		{
			NativePerformanceDiagnosticsRuntime.RegisterFogSphereHandler(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(FogSphereHandler), "Update")]
		private static void FogSphereUpdatePrefix(out long __state)
		{
			__state = NativePerformanceDiagnosticsRuntime.BeginProbe(detailed: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FogSphereHandler), "