Decompiled source of Threat Detection Terminal v0.9.0

BepInEx/plugins/ThreatDetectionComputer/ThreatComputerPhotoPrototype.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using Unity.Profiling;
using Unity.Profiling.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Networking;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ThreatComputerPhotoPrototype")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.12.72")]
[assembly: AssemblyInformationalVersion("0.1.12.72")]
[assembly: AssemblyProduct("ThreatComputerPhotoPrototype")]
[assembly: AssemblyTitle("ThreatComputerPhotoPrototype")]
[assembly: AssemblyVersion("0.1.12.72")]
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 ThreatDetectionComputer.PhotoPrototype
{
	internal sealed class PhotoVerifiedCameraOption
	{
		internal Vector3 Eye;

		internal Vector3 Floor;

		internal float EyeHeight;

		internal float Score;

		internal int Visible;
	}
	internal sealed class PhotoCameraPlan
	{
		internal Vector3 Position;

		internal Vector3 LookAt;

		internal Bounds TargetBounds;

		internal Transform TargetRoot;

		internal readonly List<Renderer> Meshes = new List<Renderer>();

		internal bool UsedCulledRenderers;

		internal PhotoInteriorValidator.Context? InteriorContext;

		internal PhotoCameraPlacementAudit PlacementAudit;

		internal Vector3 CameraNavFloor;

		internal float CameraEyeHeight;

		internal int VisibilitySamples;

		internal float PlacementScore;

		internal readonly List<PhotoVerifiedCameraOption> VerifiedOptions = new List<PhotoVerifiedCameraOption>();
	}
	internal static class CameraPlacement
	{
		private const int CandidateCount = 32;

		private const float ViewFovDegrees = 63f;

		private const float NearClip = 0.07f;

		private static readonly RaycastHit[] SightHits = (RaycastHit[])(object)new RaycastHit[96];

		private const int MapRadarLayer = 14;

		private const int ScanNodeLayer = 22;

		internal static bool TryPlan(EnemyAI target, float aspect, out PhotoCameraPlan plan, out string failure)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			plan = new PhotoCameraPlan
			{
				TargetRoot = ((Component)target).transform,
				PlacementAudit = new PhotoCameraPlacementAudit(target)
			};
			failure = "";
			try
			{
				if (!CollectMeshes(target, plan, includeCulled: false, out var bounds))
				{
					plan.Meshes.Clear();
					plan.UsedCulledRenderers = true;
					if (!CollectMeshes(target, plan, includeCulled: true, out bounds))
					{
						failure = "REJECT_NO_ENEMY_RENDERERS: no usable active enemy mesh";
						plan.PlacementAudit.Fail(failure);
						return false;
					}
				}
				plan.TargetBounds = bounds;
				plan.LookAt = ((Bounds)(ref bounds)).center;
				if (!PhotoInteriorValidator.TryCreateContext(target, plan.PlacementAudit, out PhotoInteriorValidator.Context context, out string reason) || context == null)
				{
					failure = reason + ": could not verify the target's same-floor indoor NavMesh anchor";
					plan.PlacementAudit.Fail(failure);
					return false;
				}
				plan.InteriorContext = context;
				Vector3 val = ((Bounds)(ref bounds)).extents;
				float num = Mathf.Clamp(Mathf.Max(((Vector3)(ref val)).magnitude, 0.6f) * 1.45f + 1.1f, 2.5f, 9f);
				val = Vector3.ProjectOnPlane(((Component)target).transform.forward, Vector3.up);
				Vector3 val2 = ((Vector3)(ref val)).normalized;
				if (((Vector3)(ref val2)).sqrMagnitude < 0.1f)
				{
					val2 = Vector3.forward;
				}
				float num2 = float.NegativeInfinity;
				int visible = 0;
				bool flag = false;
				int num3 = 0;
				Vector3 val4 = default(Vector3);
				for (int i = 0; i < 32; i++)
				{
					int num4 = i % 8;
					int num5 = i / 8;
					Vector3 val3 = Quaternion.AngleAxis((float)num4 * 45f + (((num5 & 1) != 0) ? 22.5f : 0f), Vector3.up) * val2;
					float num6 = Mathf.Max(1.9f, num * num5 switch
					{
						2 => 0.79f, 
						1 => 0.57f, 
						0 => 0.36f, 
						_ => 1.02f, 
					});
					((Vector3)(ref val4))..ctor(plan.LookAt.x + val3.x * num6, context.Anchor.y, plan.LookAt.z + val3.z * num6);
					for (int j = 0; j < 2; j++)
					{
						float num7 = ((j == 0) ? 1.45f : 1.15f);
						PhotoInteriorValidator.CandidateCheck check = PhotoInteriorValidator.CheckCandidate(target, context, val4, num7, plan.LookAt, 63f, aspect, 0.07f);
						int num8 = 0;
						float num9 = float.NegativeInfinity;
						if (check.Accepted)
						{
							num8 = CountVisibleTargetSamples(check.Eye, bounds, target);
							float num10 = Vector3.Distance(check.Eye, plan.LookAt);
							num9 = (float)num8 * 100f - Mathf.Abs(num10 - num) * 2f - check.PathLength * 0.55f - check.HorizontalSnap * 5f;
							if (num8 == 0)
							{
								num9 -= 150f;
							}
							plan.VerifiedOptions.Add(new PhotoVerifiedCameraOption
							{
								Eye = check.Eye,
								Floor = check.Floor,
								EyeHeight = num7,
								Score = num9,
								Visible = num8
							});
							if (!flag || num9 > num2)
							{
								flag = true;
								num2 = num9;
								visible = num8;
								plan.Position = check.Eye;
								plan.CameraNavFloor = check.Floor;
								plan.CameraEyeHeight = num7;
								plan.VisibilitySamples = num8;
								plan.PlacementScore = num9;
							}
						}
						plan.PlacementAudit.Candidate(++num3, val4, check, num9, num8);
						if (check.Accepted)
						{
							break;
						}
					}
				}
				if (!flag)
				{
					failure = "REJECT_NO_VALID_INDOOR_CAMERA: all " + num3 + " checked viewpoints failed strict NavMesh/structure/clearance validation";
					plan.PlacementAudit.Fail(failure);
					return false;
				}
				plan.VerifiedOptions.Sort((PhotoVerifiedCameraOption a, PhotoVerifiedCameraOption b) => b.Score.CompareTo(a.Score));
				if (!PhotoInteriorValidator.Revalidate(target, context, plan.CameraNavFloor, plan.Position, plan.LookAt, 63f, aspect, 0.07f, out string reason2))
				{
					failure = "REJECT_FINAL_REVALIDATION: " + reason2;
					plan.PlacementAudit.Fail(failure);
					return false;
				}
				plan.PlacementAudit.Finish(plan.Position, plan.CameraNavFloor, num2, visible);
				return true;
			}
			catch (Exception ex)
			{
				failure = "REJECT_VALIDATOR_EXCEPTION: " + ex.GetType().Name + ": " + ex.Message;
				plan.PlacementAudit.Fail(failure);
				return false;
			}
		}

		private static int CountVisibleTargetSamples(Vector3 eye, Bounds bounds, EnemyAI target)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Vector3.Cross(Vector3.up, ((Bounds)(ref bounds)).center - eye);
			Vector3 val2 = ((Vector3)(ref val)).normalized;
			if (((Vector3)(ref val2)).sqrMagnitude < 0.001f)
			{
				val2 = Vector3.right;
			}
			Vector3[] obj = new Vector3[5]
			{
				((Bounds)(ref bounds)).center,
				default(Vector3),
				default(Vector3),
				default(Vector3),
				default(Vector3)
			};
			Vector3 center = ((Bounds)(ref bounds)).center;
			Vector3 val3 = val2;
			val = ((Bounds)(ref bounds)).extents;
			obj[1] = center + val3 * ((Vector3)(ref val)).magnitude * 0.22f;
			Vector3 center2 = ((Bounds)(ref bounds)).center;
			Vector3 val4 = val2;
			val = ((Bounds)(ref bounds)).extents;
			obj[2] = center2 - val4 * ((Vector3)(ref val)).magnitude * 0.22f;
			obj[3] = ((Bounds)(ref bounds)).center + Vector3.up * Mathf.Min(((Bounds)(ref bounds)).extents.y * 0.55f, 1.1f);
			obj[4] = ((Bounds)(ref bounds)).center - Vector3.up * Mathf.Min(((Bounds)(ref bounds)).extents.y * 0.55f, 1.1f);
			int num = 0;
			Vector3[] array = (Vector3[])(object)obj;
			for (int i = 0; i < array.Length; i++)
			{
				Vector3 val5 = array[i] - eye;
				float magnitude = ((Vector3)(ref val5)).magnitude;
				if (magnitude < 0.1f)
				{
					continue;
				}
				int num2 = Physics.RaycastNonAlloc(eye, val5 / magnitude, SightHits, magnitude, -4210721, (QueryTriggerInteraction)1);
				if (num2 == SightHits.Length)
				{
					continue;
				}
				bool flag = false;
				for (int j = 0; j < num2; j++)
				{
					Collider collider = ((RaycastHit)(ref SightHits[j])).collider;
					if (!((Object)(object)collider == (Object)null) && !collider.isTrigger && !((Component)collider).transform.IsChildOf(((Component)target).transform) && !((Object)(object)((Component)collider).GetComponentInParent<PlayerControllerB>() != (Object)null))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					num++;
				}
			}
			return num;
		}

		private static bool CollectMeshes(EnemyAI target, PhotoCameraPlan plan, bool includeCulled, out Bounds bounds)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			bounds = new Bounds(((Component)target).transform.position + Vector3.up, Vector3.one);
			bool flag = false;
			Renderer[] componentsInChildren = ((Component)target).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null || !((Component)val).gameObject.activeInHierarchy || ShouldExcludeRenderer(val) || (!includeCulled && (!val.enabled || val.forceRenderingOff)))
				{
					continue;
				}
				SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)(object)((val is SkinnedMeshRenderer) ? val : null);
				if (val2 != null)
				{
					if ((Object)(object)val2.sharedMesh == (Object)null)
					{
						continue;
					}
				}
				else
				{
					if (!(val is MeshRenderer))
					{
						continue;
					}
					MeshFilter component = ((Component)val).GetComponent<MeshFilter>();
					if ((Object)(object)component == (Object)null || (Object)(object)component.sharedMesh == (Object)null)
					{
						continue;
					}
				}
				Bounds bounds2 = val.bounds;
				Vector3 size = ((Bounds)(ref bounds2)).size;
				if (((Vector3)(ref size)).sqrMagnitude < 0.0001f)
				{
					continue;
				}
				size = ((Bounds)(ref bounds2)).size;
				if (!(((Vector3)(ref size)).magnitude > 90f))
				{
					if (!flag)
					{
						bounds = bounds2;
					}
					else
					{
						((Bounds)(ref bounds)).Encapsulate(bounds2);
					}
					flag = true;
					plan.Meshes.Add(val);
					if (plan.Meshes.Count >= 96)
					{
						break;
					}
				}
			}
			return flag;
		}

		private static bool ShouldExcludeRenderer(Renderer renderer)
		{
			if ((Object)(object)renderer == (Object)null)
			{
				return true;
			}
			GameObject gameObject = ((Component)renderer).gameObject;
			int layer = gameObject.layer;
			if (layer == 14 || layer == 22)
			{
				return true;
			}
			string a = LayerMask.LayerToName(layer);
			if (string.Equals(a, "MapRadar", StringComparison.OrdinalIgnoreCase) || string.Equals(a, "ScanNode", StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			string name = ((Object)gameObject).name;
			if (!string.IsNullOrEmpty(name) && (name.IndexOf("MapDot", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("ScanNode", StringComparison.OrdinalIgnoreCase) >= 0))
			{
				return true;
			}
			return false;
		}
	}
	internal enum PhotoSceneStyle
	{
		Legacy,
		SyntheticScan,
		Compare
	}
	internal sealed class CaptureResult
	{
		internal byte[]? LegacyRawPng;

		internal byte[]? LegacyGreenPng;

		internal byte[]? ScanRawPng;

		internal byte[]? ScanGreenPng;

		internal string ScanFailure = "";

		internal string ScanOcclusionAuditText = "";

		internal int ScanGeometryAttempts;

		internal int ScanAlternateViewsUsed;

		internal bool DiagnosticSingleSafeView;

		internal bool DiagnosticAlternateLegacySkipped;

		internal bool DiagnosticAlternateLegacyRendered;

		internal bool DiagnosticFinalViewLegacy;

		internal bool DiagnosticLegacyFallbackFirstView;

		internal bool DiagnosticLegacyAlignedToScan;

		internal int DiagnosticLegacyRenderCount;

		internal string DiagnosticLegacyReferenceEye = "none";

		internal string DiagnosticViewTrace = "";

		internal string DiagnosticPassTrace = "";

		internal int ScanLODGroups;

		internal int ScanLODTiers;

		internal int EnemyMeshCount;

		internal string SilhouetteShaderName = "";

		internal bool UsedCulledRenderers;

		internal Vector3 CameraPosition;

		internal int SceneMeshCount;

		internal int SceneTriangleCount;

		internal int SceneExamined;

		internal int SceneRejected;

		internal int SceneCulledCandidates;

		internal int SceneOccluderHits;

		internal int SceneMovableSurfaces;

		internal int SceneTerrainComponents;

		internal int SceneBudgetSkipped;

		internal bool ColliderScanSaturated;

		internal string SceneShaderName = "";

		internal string ScanMaterialStyleName = "";

		internal int RadarContourMeshes;

		internal int RadarObjectMeshes;

		internal float RadarHeightMin;

		internal float RadarHeightMax;

		internal float RadarContourSpacing;

		internal float RadarContourWidth;

		internal int SceneLayer = -1;

		internal bool IsolatedHDRPVolumes;

		internal long SetupMilliseconds;

		internal long LegacyRenderMilliseconds;

		internal long ScanRenderMilliseconds;

		internal float ScanVisibleFraction;

		internal PhotoGeometryDiagnosticResult? Diagnostics;

		internal string RendererAuditText = "";

		internal string CameraPlacementAuditText = "";

		internal Vector3 CameraNavFloor;

		internal int CameraVisibleSamples;

		internal float CameraPlacementScore;

		internal string CameraPassBridge = "";

		internal int CameraPassExecutions;

		internal int CameraPassBlackExecutions;

		internal int CameraPassWhiteExecutions;

		internal int CameraPassDrawCalls;

		internal string SourceIntegrity = "not checked";

		internal string PerspectiveStatus = "not requested";

		internal string HDRPBufferAvailability = "not probed";

		internal bool PerspectiveApplied;

		internal float PerspectiveCoverage;

		internal int PerspectiveGpuOnlyPixels;

		internal int PerspectiveMeshOnlyPixels;

		internal int PerspectiveReadableTriangles;

		internal int PerspectiveUnreadableMeshes;

		internal long PerspectiveRasterMilliseconds;

		internal long PerspectiveCompositeMilliseconds;

		internal byte[]? ScanBasePng;

		internal byte[]? ScanBasePreviousPng;

		internal byte[]? ScanBaseDistanceOnlyPng;

		internal PhotoSilhouetteContrastResult? SilhouetteContrast;

		internal float ToneNearestDepth;

		internal float ToneFarthestDepth;

		internal int ToneBlackEnvironmentPixels;

		internal int ToneNearEnvironmentPixels;

		internal int ToneMiddleEnvironmentPixels;

		internal int ToneFarEnvironmentPixels;

		internal byte[]? ScanDepthMeshPng;

		internal byte[]? ScanNormalsMeshPng;

		internal byte[]? ScanMeshCoveragePng;

		internal string EdgeStatus = "not requested";

		internal bool EdgeApplied;

		internal long EdgeMilliseconds;

		internal long EdgeCompositeMilliseconds;

		internal int EdgeDepthPixels;

		internal int EdgeNormalPixels;

		internal int EdgeObjectReinforced;

		internal int EdgeSuppressedNoise;

		internal int EdgeSuppressedPlanarPairs;

		internal int EdgeSuppressedPlanarPixels;

		internal bool EdgePlanarTestAvailable;

		internal int EdgeMonsterProtected;

		internal int EdgeHaloProtected;

		internal int EdgeInvalidEnvironment;

		internal int EdgeTotalPixels;

		internal int RadarContourPixels;

		internal float EdgeFraction;

		internal byte[]? ScanEdgeDepthPng;

		internal byte[]? ScanEdgeNormalPng;

		internal byte[]? ScanEdgeMaskPng;

		internal byte[]? ScanEdgePlanarSuppressedPng;

		internal byte[]? ScanFinalPng;

		internal bool MonsterPixelationApplied;

		internal int MonsterPixelationPixels;

		internal int MonsterPixelationStrongPixels;

		internal int MonsterPixelationBlocks;

		internal double MonsterPixelationMilliseconds;

		internal string MonsterPixelationFailure = "";

		internal PhotoDeferredCpuRequest? DeferredCpu;

		internal byte[]? ScanRendererIdsPng;

		internal string ScanRendererIdsLegend = "";

		internal string ScanRendererIdsStatus = "not requested";

		internal int RendererIdsCalibrated;

		internal int RendererIdsDecodedPixels;

		internal int RendererIdsUnmatchedPixels;

		internal long RendererIdsMilliseconds;

		internal int AudioHelpersExcluded;

		internal int SingularReverbHelpersExcluded;

		internal int CollisionHelpersExcluded;

		internal int AmbiguousCollisionRenderers;

		internal int DisabledHallwayBlockersRejected;

		internal string SourceMaterialAuditText = "";

		internal byte[]? ScanHelpersIncludedRawPng;

		internal byte[]? ScanHelpersDifferencePng;

		internal int HelperCompareSources;

		internal int HelperCompareChangedPixels;

		internal string HelperCompareStatus = "not requested";

		internal bool HasScan => ScanGreenPng != null;
	}
	internal static class HDRPPhotoCapture
	{
		internal static bool TryCapture(EnemyAI enemy, int width, int height, bool saveRaw, PhotoSceneStyle style, int maxSceneMeshes, int maxSceneTriangles, ScanMaterialStyle scanMaterialStyle, float radarSpacing, float radarWidth, bool produceResearchDiagnostics, int diagnosticPixelStep, bool enablePerspectiveBase, int meshRasterTriangleBudget, bool deferCpu, bool silhouetteAwarePhysics, bool reuseSceneProxies, PhotoDistanceToneSettings toneSettings, PhotoRadarEdgeSettings edgeSettings, PhotoIsolationMode isolationMode, out CaptureResult? result, out string error, out string cameraPlacementAudit)
		{
			//IL_10d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_10f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_10fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_111f: Unknown result type (might be due to invalid IL or missing references)
			//IL_1125: Unknown result type (might be due to invalid IL or missing references)
			//IL_112b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1332: Unknown result type (might be due to invalid IL or missing references)
			//IL_1338: Unknown result type (might be due to invalid IL or missing references)
			//IL_1b1a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_1213: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_152f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Unknown result type (might be due to invalid IL or missing references)
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_15c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a6c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a6e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a74: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a76: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a9a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d1f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d24: Unknown result type (might be due to invalid IL or missing references)
			//IL_0593: Unknown result type (might be due to invalid IL or missing references)
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e33: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e38: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e73: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e78: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e7f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e84: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c9e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ca4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0658: Unknown result type (might be due to invalid IL or missing references)
			//IL_065d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0665: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Unknown result type (might be due to invalid IL or missing references)
			//IL_069f: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0717: Unknown result type (might be due to invalid IL or missing references)
			result = null;
			error = "";
			cameraPlacementAudit = "";
			bool flag;
			PhotoCameraPlan plan;
			using (PhotoCaptureProfiler.Measure("CameraPlacement"))
			{
				flag = CameraPlacement.TryPlan(enemy, (float)width / (float)height, out plan, out error);
			}
			if (!flag)
			{
				cameraPlacementAudit = plan.PlacementAudit.ToString();
				error = "camera placement: " + error;
				return false;
			}
			cameraPlacementAudit = plan.PlacementAudit.ToString();
			CaptureResult captureResult = new CaptureResult
			{
				EnemyMeshCount = plan.Meshes.Count,
				SilhouetteShaderName = "HDRP/Unlit (camera-only original renderer)",
				UsedCulledRenderers = plan.UsedCulledRenderers,
				CameraPosition = plan.Position,
				CameraNavFloor = plan.CameraNavFloor,
				CameraVisibleSamples = plan.VisibilitySamples,
				CameraPlacementScore = plan.PlacementScore,
				CameraPlacementAuditText = cameraPlacementAudit
			};
			if (isolationMode == PhotoIsolationMode.PlacementOnly)
			{
				PhotoCaptureProfiler.Event("isolation-placement-complete");
				PhotoFrameStallMonitor.Mark("isolation-placement-only-complete");
				result = captureResult;
				return true;
			}
			GameObject val = null;
			Camera val2 = null;
			bool flag2 = style != PhotoSceneStyle.Legacy && PhotoCaptureIsolation.UseFinalViewLegacyReference(isolationMode);
			RenderTexture val3 = null;
			RenderTexture active = RenderTexture.active;
			PhotoSceneSession result2 = null;
			PhotoMonsterPassSession result3 = null;
			try
			{
				PhotoFrameStallMonitor.Mark("hdrp-camera-setup-enter");
				using (PhotoCaptureProfiler.Measure("CameraSetup"))
				{
					val = new GameObject("ThreatPhoto_TemporaryHDRPCamera")
					{
						hideFlags = (HideFlags)61
					};
					PhotoFrameStallMonitor.Mark("i32-native-camera-object-created");
					val2 = val.AddComponent<Camera>();
					PhotoFrameStallMonitor.Mark("i32-native-camera-component-added");
					((Behaviour)val2).enabled = false;
					TryAttachHDRPCameraData(val);
					Camera main = Camera.main;
					if ((Object)(object)main != (Object)null && (Object)(object)main != (Object)(object)val2)
					{
						val2.CopyFrom(main);
					}
					PhotoFrameStallMonitor.Mark("i32-native-camera-configured");
					((Behaviour)val2).enabled = false;
					((Component)val2).transform.position = plan.Position;
					((Component)val2).transform.rotation = Quaternion.LookRotation(plan.LookAt - plan.Position, Vector3.up);
					val2.orthographic = false;
					val2.rect = new Rect(0f, 0f, 1f, 1f);
					val2.fieldOfView = 63f;
					val2.aspect = (float)width / (float)height;
					val2.nearClipPlane = 0.07f;
					val2.farClipPlane = 100f;
					val2.clearFlags = (CameraClearFlags)2;
					val2.backgroundColor = new Color(0.03f, 0.04f, 0.025f, 1f);
					val2.allowHDR = true;
					val2.allowMSAA = false;
					val2.allowDynamicResolution = false;
					val2.useOcclusionCulling = false;
					int num = 4210688;
					Camera obj = val2;
					obj.cullingMask &= ~num;
					if (!PhotoMonsterPassSession.TryCreate(val2, plan, out result3, out string failure) || result3 == null)
					{
						error = "Camera-only monster pass setup: " + failure;
						return false;
					}
					captureResult.CameraPassBridge = result3.BridgeDescription;
					val3 = RenderTexture.GetTemporary(width, height, 24, (RenderTextureFormat)0, (RenderTextureReadWrite)0);
					PhotoFrameStallMonitor.Mark("i32-native-render-target-allocated");
					((Texture)val3).filterMode = (FilterMode)1;
					val2.targetTexture = val3;
					string reason = "missing strict interior context";
					if (plan.InteriorContext == null || !PhotoInteriorValidator.Revalidate(enemy, plan.InteriorContext, plan.CameraNavFloor, plan.Position, plan.LookAt, val2.fieldOfView, val2.aspect, val2.nearClipPlane, out reason))
					{
						plan.PlacementAudit.Note("REJECT_CAMERA_BEFORE_FIRST_RENDER: " + reason);
						error = "camera placement: REJECT_CAMERA_BEFORE_FIRST_RENDER: " + reason;
						return false;
					}
					plan.PlacementAudit.Note("PASS_CAMERA_BEFORE_FIRST_RENDER: " + ((Vector3)(ref plan.Position)).ToString("F3"));
				}
				if (!flag2)
				{
					using (PhotoCaptureProfiler.Measure("LegacyReference"))
					{
						using (PhotoSnapshotStageTrace.Measure("LegacyReference.All"))
						{
							long ticks = DateTime.UtcNow.Ticks;
							result3.SetMode(MonsterOverrideMode.Disabled);
							Texture2D val4 = RenderReadback(val2, val3, result3, width, height, "Legacy");
							try
							{
								if (saveRaw)
								{
									captureResult.LegacyRawPng = ImageConversion.EncodeToPNG(val4);
								}
								PhotoColorGrade.ApplyGreenFacilityLook(val4);
								captureResult.LegacyGreenPng = ImageConversion.EncodeToPNG(val4);
							}
							finally
							{
								Object.Destroy((Object)(object)val4);
							}
							captureResult.LegacyRenderMilliseconds = ElapsedMs(ticks);
							captureResult.DiagnosticLegacyRenderCount++;
							captureResult.DiagnosticLegacyReferenceEye = ((Vector3)(ref plan.Position)).ToString("F3");
						}
					}
					PhotoFrameStallMonitor.Mark("hdrp-legacy-render-done");
				}
				else
				{
					PhotoCaptureProfiler.Event("i23-legacy-deferred-until-validated-view");
					PhotoFrameStallMonitor.Mark("i23-legacy-deferred");
				}
				if (isolationMode == PhotoIsolationMode.LegacyRenderOnly || (isolationMode == PhotoIsolationMode.SnapshotOnly && style == PhotoSceneStyle.Legacy))
				{
					PhotoCaptureProfiler.Event("isolation-legacy-render-complete");
					result = captureResult;
					return true;
				}
				if (style != PhotoSceneStyle.Legacy)
				{
					try
					{
						long ticks2 = DateTime.UtcNow.Ticks;
						StringBuilder stringBuilder = new StringBuilder();
						string error2 = "";
						Vector3 position = plan.Position;
						Vector3 cameraNavFloor = plan.CameraNavFloor;
						float cameraEyeHeight = plan.CameraEyeHeight;
						float placementScore = plan.PlacementScore;
						int visibilitySamples = plan.VisibilitySamples;
						bool flag3 = false;
						int num2 = 0;
						int num3 = 0;
						int num4 = Math.Min(plan.VerifiedOptions.Count, 12);
						int num5 = PhotoCaptureIsolation.MaxViewAttempts(isolationMode);
						captureResult.DiagnosticSingleSafeView = isolationMode != PhotoIsolationMode.Normal && num5 == 1;
						int num6 = 0;
						List<Vector3> list = new List<Vector3> { position };
						while (num2 < num5)
						{
							PhotoFrameStallMonitor.Mark("hdrp-scene-construction-enter");
							if (num2 > 0)
							{
								bool flag4 = false;
								while (num6 < num4)
								{
									PhotoVerifiedCameraOption photoVerifiedCameraOption = plan.VerifiedOptions[num6++];
									if (photoVerifiedCameraOption.Visible <= 0)
									{
										continue;
									}
									bool flag5 = false;
									foreach (Vector3 item in list)
									{
										if (Vector3.Distance(photoVerifiedCameraOption.Eye, item) < 0.25f)
										{
											flag5 = true;
											break;
										}
									}
									if (!flag5)
									{
										if (PhotoInteriorValidator.Revalidate(enemy, plan.InteriorContext, photoVerifiedCameraOption.Floor, photoVerifiedCameraOption.Eye, plan.LookAt, val2.fieldOfView, val2.aspect, val2.nearClipPlane, out string reason2))
										{
											plan.Position = photoVerifiedCameraOption.Eye;
											plan.CameraNavFloor = photoVerifiedCameraOption.Floor;
											plan.CameraEyeHeight = photoVerifiedCameraOption.EyeHeight;
											plan.VisibilitySamples = photoVerifiedCameraOption.Visible;
											plan.PlacementScore = photoVerifiedCameraOption.Score;
											((Component)val2).transform.position = photoVerifiedCameraOption.Eye;
											((Component)val2).transform.rotation = Quaternion.LookRotation(plan.LookAt - photoVerifiedCameraOption.Eye, Vector3.up);
											plan.PlacementAudit.Note("TRY_SCAN_ALTERNATE " + ((Vector3)(ref photoVerifiedCameraOption.Eye)).ToString("F3") + " score=" + photoVerifiedCameraOption.Score.ToString("F2"));
											num3++;
											list.Add(photoVerifiedCameraOption.Eye);
											flag4 = true;
											break;
										}
										PhotoCaptureProfiler.Event("i23-view-option-rejected:safety:" + SanitizeViewReason(reason2));
										plan.PlacementAudit.Note("REJECT_SCAN_ALTERNATE " + ((Vector3)(ref photoVerifiedCameraOption.Eye)).ToString("F3") + " " + reason2);
									}
								}
								if (!flag4)
								{
									break;
								}
							}
							num2++;
							PhotoCaptureProfiler.Event("i23-view-" + num2 + ":begin:" + ((num2 == 1) ? "initial" : "alternate") + ":eye=" + ((Vector3)(ref plan.Position)).ToString("F3"));
							PhotoFrameStallMonitor.Mark("i23-view-" + num2 + "-begin");
							bool flag6;
							string occlusionAudit;
							using (PhotoCaptureProfiler.Measure("SceneConstruction"))
							{
								using (PhotoSnapshotStageTrace.Measure("Scene.ConstructionTotal"))
								{
									flag6 = PhotoSceneSession.TryCreate(enemy, plan, val2, maxSceneMeshes, maxSceneTriangles, ScanMaterialStyle.PriorDistanceEdges, radarSpacing, radarWidth, reuseSceneProxies && !produceResearchDiagnostics, out result2, out error2, out occlusionAudit);
								}
							}
							PhotoFrameStallMonitor.Mark("hdrp-scene-construction-exit");
							stringBuilder.AppendLine("===== PHOTO VIEW " + num2 + " eye=" + ((Vector3)(ref plan.Position)).ToString("F3") + " =====");
							stringBuilder.AppendLine((occlusionAudit.Length > 0) ? occlusionAudit : ("No detailed occlusion report (collection/setup failed): " + error2));
							if (flag6 && result2 != null)
							{
								PhotoCaptureProfiler.Event("i23-view-" + num2 + ":accepted:meshes=" + result2.MeshCount + ":triangles=" + result2.TriangleCount);
								PhotoFrameStallMonitor.Mark("i23-view-" + num2 + "-accepted");
								flag3 = true;
								plan.PlacementAudit.Note("PASS_SCAN_GEOMETRY at " + ((Vector3)(ref plan.Position)).ToString("F3"));
								break;
							}
							PhotoCaptureProfiler.Event("i23-view-" + num2 + ":rejected:" + SanitizeViewReason(error2));
							PhotoFrameStallMonitor.Mark("i23-view-" + num2 + "-rejected");
							plan.PlacementAudit.Note("REJECT_SCAN_GEOMETRY at " + ((Vector3)(ref plan.Position)).ToString("F3") + " reason=" + error2);
							if (error2.IndexOf("occluder", StringComparison.OrdinalIgnoreCase) < 0 && error2.IndexOf("OCCLUSION", StringComparison.OrdinalIgnoreCase) < 0 && error2.IndexOf("LOD_", StringComparison.OrdinalIgnoreCase) < 0)
							{
								break;
							}
						}
						captureResult.ScanGeometryAttempts = num2;
						captureResult.ScanAlternateViewsUsed = num3;
						captureResult.ScanOcclusionAuditText = stringBuilder.ToString();
						captureResult.DiagnosticViewTrace = "viewAttempts=" + num2 + ";alternatives=" + num3 + ";selected=" + (flag3 ? ((Vector3)(ref plan.Position)).ToString("F3") : "none") + ";singleSafeView=" + captureResult.DiagnosticSingleSafeView;
						if (!flag3 || result2 == null)
						{
							plan.Position = position;
							plan.CameraNavFloor = cameraNavFloor;
							plan.CameraEyeHeight = cameraEyeHeight;
							plan.VisibilitySamples = visibilitySamples;
							plan.PlacementScore = placementScore;
							((Component)val2).transform.position = position;
							((Component)val2).transform.rotation = Quaternion.LookRotation(plan.LookAt - position, Vector3.up);
							if (flag2)
							{
								RenderPostSelectionLegacyReference(val2, val3, result3, captureResult, width, height, saveRaw, "FallbackFirstViewLegacy");
								captureResult.DiagnosticLegacyFallbackFirstView = true;
								plan.PlacementAudit.Note("i24 LEGACY_FALLBACK_AT_INITIAL_VIEW: no verified scan scene");
								PhotoCaptureProfiler.Event("i24-legacy-fallback:first-safe-view" + ((isolationMode == PhotoIsolationMode.Normal) ? ":normal" : ":diagnostic"));
							}
							captureResult.ScanFailure = error2;
							if (captureResult.DiagnosticSingleSafeView)
							{
								captureResult.ScanFailure = "Single-safe-view diagnostic rejected geometry: " + error2;
								PhotoCaptureProfiler.Event("i23-single-safe-view-fail-closed:" + SanitizeViewReason(error2));
								PhotoFrameStallMonitor.Mark("i23-single-safe-view-fail-closed");
							}
						}
						else
						{
							if (isolationMode == PhotoIsolationMode.SceneBuildOnly)
							{
								captureResult.SceneLayer = result2.Layer;
								captureResult.SceneMeshCount = result2.MeshCount;
								captureResult.SceneTriangleCount = result2.TriangleCount;
								captureResult.SceneExamined = result2.Inventory.Examined;
								captureResult.SceneRejected = result2.Inventory.Rejected;
								captureResult.SceneCulledCandidates = result2.Inventory.CulledWorldSources;
								captureResult.SceneOccluderHits = result2.Inventory.OccluderHitsChecked;
								captureResult.SceneBudgetSkipped = result2.Inventory.OverBudget;
								captureResult.ColliderScanSaturated = result2.Inventory.ColliderScanSaturated;
								captureResult.ScanLODGroups = result2.Inventory.LodGroupsFound;
								captureResult.ScanLODTiers = result2.Inventory.LodTiersChosen;
								captureResult.SceneShaderName = result2.ShaderName;
								PhotoCaptureProfiler.Event("isolation-scene-built");
								PhotoFrameStallMonitor.Mark("isolation-scene-build-only-complete");
								result = captureResult;
								return true;
							}
							if (flag2)
							{
								int cullingMask = val2.cullingMask;
								val2.cullingMask = cullingMask & ~(1 << result2.Layer);
								try
								{
									RenderPostSelectionLegacyReference(val2, val3, result3, captureResult, width, height, saveRaw, "FinalViewLegacy");
								}
								finally
								{
									val2.cullingMask = cullingMask;
								}
								captureResult.DiagnosticFinalViewLegacy = true;
								captureResult.DiagnosticLegacyAlignedToScan = Vector3.Distance(((Component)val2).transform.position, plan.Position) <= 0.025f;
								plan.PlacementAudit.Note("i24 LEGACY_REFERENCE_AT_FINAL_SAFE_VIEW: " + ((Vector3)(ref plan.Position)).ToString("F3") + "; one legacy HDRP render; aligned=" + captureResult.DiagnosticLegacyAlignedToScan);
								if (!captureResult.DiagnosticLegacyAlignedToScan)
								{
									throw new InvalidOperationException("Final-view legacy reference camera position mismatch");
								}
								PhotoCaptureProfiler.Event("i23-legacy-aligned:selected-safe-view");
								PhotoFrameStallMonitor.Mark("i23-final-view-legacy-done");
							}
							else if (Vector3.Distance(plan.Position, position) > 0.25f && PhotoCaptureIsolation.ShouldRenderAlternateLegacy(isolationMode))
							{
								int cullingMask2 = val2.cullingMask;
								val2.cullingMask = cullingMask2 & ~(1 << result2.Layer);
								result3.SetMode(MonsterOverrideMode.Disabled);
								long ticks3 = DateTime.UtcNow.Ticks;
								using (PhotoCaptureProfiler.Measure("AlternateLegacyRecapture"))
								{
									Texture2D val5 = RenderReadback(val2, val3, result3, width, height, "AlternateLegacy");
									try
									{
										if (saveRaw)
										{
											captureResult.LegacyRawPng = ImageConversion.EncodeToPNG(val5);
										}
										PhotoColorGrade.ApplyGreenFacilityLook(val5);
										captureResult.LegacyGreenPng = ImageConversion.EncodeToPNG(val5);
									}
									finally
									{
										Object.Destroy((Object)(object)val5);
									}
									captureResult.LegacyRenderMilliseconds += ElapsedMs(ticks3);
								}
								captureResult.DiagnosticLegacyRenderCount++;
								captureResult.DiagnosticLegacyReferenceEye = ((Vector3)(ref plan.Position)).ToString("F3");
								captureResult.DiagnosticAlternateLegacyRendered = true;
								PhotoCaptureProfiler.Event("i23-alternate-legacy:rendered");
								plan.PlacementAudit.Note("LEGACY_REFERENCE_RECAPTURED at safe alternate");
							}
							else if (Vector3.Distance(plan.Position, position) > 0.25f)
							{
								captureResult.DiagnosticAlternateLegacySkipped = true;
								PhotoCaptureProfiler.Event("i23-alternate-legacy:skipped-diagnostic");
								PhotoFrameStallMonitor.Mark("i23-alternate-legacy-skipped");
								plan.PlacementAudit.Note("DIAGNOSTIC: skipped alternate legacy recapture; first-view legacy reference is NOT comparable to alternate scan");
							}
							captureResult.CameraPosition = plan.Position;
							captureResult.CameraNavFloor = plan.CameraNavFloor;
							captureResult.CameraVisibleSamples = plan.VisibilitySamples;
							captureResult.CameraPlacementScore = plan.PlacementScore;
							captureResult.ScanLODGroups = result2.Inventory.LodGroupsFound;
							captureResult.ScanLODTiers = result2.Inventory.LodTiersChosen;
							captureResult.SceneLayer = result2.Layer;
							captureResult.SceneMeshCount = result2.MeshCount;
							captureResult.SceneTriangleCount = result2.TriangleCount;
							captureResult.SceneShaderName = result2.ShaderName;
							captureResult.ScanMaterialStyleName = result2.MaterialStyle.ToString();
							captureResult.RadarContourMeshes = result2.ContourMeshCount;
							captureResult.RadarObjectMeshes = result2.RadarObjectMeshCount;
							captureResult.RadarHeightMin = result2.ScanHeightMin;
							captureResult.RadarHeightMax = result2.ScanHeightMax;
							captureResult.RadarContourSpacing = result2.ContourSpacing;
							captureResult.RadarContourWidth = result2.ContourWidth;
							captureResult.SceneExamined = result2.Inventory.Examined;
							captureResult.SceneRejected = result2.Inventory.Rejected;
							captureResult.SceneCulledCandidates = result2.Inventory.CulledWorldSources;
							captureResult.AudioHelpersExcluded = result2.Inventory.AudioHelperRejected;
							captureResult.SingularReverbHelpersExcluded = result2.Inventory.SingularReverbHelperRejected;
							captureResult.CollisionHelpersExcluded = result2.Inventory.CollisionHelperRejected;
							captureResult.AmbiguousCollisionRenderers = result2.Inventory.CollisionHierarchyIncluded;
							captureResult.DisabledHallwayBlockersRejected = result2.Inventory.DisabledHallwayBlockersRejected;
							if (produceResearchDiagnostics)
							{
								try
								{
									using (PhotoCaptureProfiler.Measure("OptionalMaterialAudit"))
									{
										captureResult.SourceMaterialAuditText = PhotoSourceMaterialAudit.Build(result2);
									}
								}
								catch (Exception ex)
								{
									captureResult.SourceMaterialAuditText = "Material audit failed: " + ex.GetType().Name + ": " + ex.Message;
								}
							}
							captureResult.SceneOccluderHits = result2.Inventory.OccluderHitsChecked;
							captureResult.SceneMovableSurfaces = result2.Inventory.MovableArchitecturalSurfaces;
							captureResult.SceneTerrainComponents = result2.Inventory.NearbyTerrainComponents;
							captureResult.SceneBudgetSkipped = result2.Inventory.OverBudget;
							captureResult.ColliderScanSaturated = result2.Inventory.ColliderScanSaturated;
							captureResult.SetupMilliseconds = ElapsedMs(ticks2);
							val2.cullingMask = 1 << result2.Layer;
							val2.allowHDR = false;
							val2.backgroundColor = Color.black;
							captureResult.IsolatedHDRPVolumes = TryDisableVolumesForScan(val);
							using (PhotoSnapshotStageTrace.Measure("Scene.OpaqueMaterialBinding"))
							{
								result2.ApplyOpaqueGreenPreview(plan.Position, plan.LookAt);
							}
							if (!PhotoInteriorValidator.Revalidate(enemy, plan.InteriorContext, plan.CameraNavFloor, plan.Position, plan.LookAt, val2.fieldOfView, val2.aspect, val2.nearClipPlane, out string reason3))
							{
								throw new InvalidOperationException("REJECT_CAMERA_BEFORE_SCAN_RENDER: " + reason3);
							}
							plan.PlacementAudit.Note("PASS_CAMERA_BEFORE_SCAN_RENDER");
							captureResult.SceneShaderName = "HDRP/Unlit opaque green diagnostic (no contour)";
							captureResult.ScanMaterialStyleName = "OpaqueGreenCameraOnlyPreview";
							result3.SetMode(MonsterOverrideMode.Black);
							PhotoFrameStallMonitor.Mark("hdrp-scan-render-enter");
							using (PhotoCaptureProfiler.Measure("SyntheticScanProcessing"))
							{
								long ticks4 = DateTime.UtcNow.Ticks;
								Texture2D val6 = RenderReadback(val2, val3, result3, width, height, "ScanGreen");
								try
								{
									if (saveRaw)
									{
										captureResult.ScanRawPng = ImageConversion.EncodeToPNG(val6);
									}
									if (isolationMode == PhotoIsolationMode.ScanRenderOnly)
									{
										PhotoCaptureProfiler.Event("isolation-scan-render-complete");
										PhotoFrameStallMonitor.Mark("isolation-scan-render-only-complete");
										result = captureResult;
										return true;
									}
									using (PhotoCaptureProfiler.Measure("OptionalHelperComparison"))
									{
										if (produceResearchDiagnostics)
										{
											try
											{
												result2.PrepareExcludedBlockerComparison(plan.LookAt);
												captureResult.HelperCompareSources = result2.ComparisonBlockerCount;
												if (captureResult.HelperCompareSources == 0)
												{
													captureResult.HelperCompareStatus = "no in-frustum excluded connector blocks";
												}
												else
												{
													Color32[] pixels = val6.GetPixels32();
													result2.SetExcludedBlockerComparisonVisible(visible: true);
													Texture2D val7 = null;
													try
													{
														val7 = RenderReadback(val2, val3, result3, width, height, "HelpersIncluded");
														captureResult.ScanHelpersIncludedRawPng = ImageConversion.EncodeToPNG(val7);
														captureResult.ScanHelpersDifferencePng = PhotoHelperComparison.CreateDifferencePng(pixels, val7.GetPixels32(), width, height, out var changedPixels);
														captureResult.HelperCompareChangedPixels = changedPixels;
														captureResult.HelperCompareStatus = "diagnostic A/B capture complete";
													}
													finally
													{
														result2.SetExcludedBlockerComparisonVisible(visible: false);
														if ((Object)(object)val7 != (Object)null)
														{
															Object.Destroy((Object)(object)val7);
														}
													}
												}
											}
											catch (Exception ex2)
											{
												result2.SetExcludedBlockerComparisonVisible(visible: false);
												captureResult.HelperCompareStatus = "nonfatal helper comparison error: " + ex2.GetType().Name + ": " + ex2.Message;
											}
										}
									}
									PhotoGeometryDiagnosticResult photoGeometryDiagnosticResult = null;
									PhotoMeshBuffers mesh = null;
									PhotoFrameStallMonitor.Mark("hdrp-mask-physics-enter");
									using (PhotoCaptureProfiler.Measure("GpuMasksAndPhysics"))
									{
										using (PhotoSnapshotStageTrace.Measure("Masks.AndOptionalPhysicsTotal"))
										{
											photoGeometryDiagnosticResult = PhotoGeometryDiagnostics.Capture(val2, val3, result3, result2, plan.LookAt, plan.TargetBounds, width, height, diagnosticPixelStep, PhotoCaptureIsolation.IncludePhysicsReference(isolationMode), produceResearchDiagnostics, silhouetteAwarePhysics, PhotoCaptureIsolation.MaskCutoff(isolationMode));
										}
									}
									PhotoFrameStallMonitor.Mark("hdrp-mask-physics-exit");
									captureResult.Diagnostics = photoGeometryDiagnosticResult;
									captureResult.DiagnosticPassTrace = "class=" + photoGeometryDiagnosticResult.ClassMaskCompleted + ";visible=" + photoGeometryDiagnosticResult.VisibleMaskCompleted + ";physics=" + photoGeometryDiagnosticResult.PhysicsReferenceCompleted + ";maskCutoff=" + PhotoCaptureIsolation.MaskCutoff(isolationMode);
									PhotoCaptureProfiler.Event("i23-mask-outcome:" + captureResult.DiagnosticPassTrace);
									if (!string.IsNullOrEmpty(photoGeometryDiagnosticResult.Failure))
									{
										captureResult.PerspectiveStatus = "GPU reference unavailable: " + photoGeometryDiagnosticResult.Failure;
										captureResult.ScanFailure = "Geometry safety pass failed: " + photoGeometryDiagnosticResult.Failure;
									}
									if (photoGeometryDiagnosticResult.SuspectedSilhouetteLeaks >= 3 * diagnosticPixelStep * diagnosticPixelStep)
									{
										captureResult.ScanFailure = "Physics-versus-visible-silhouette reference suggests " + photoGeometryDiagnosticResult.SuspectedSilhouetteLeaks + " possibly exposed enemy pixels through foreground geometry. Declining synthetic scan to prevent x-ray (debug mask optional).";
									}
									if (isolationMode == PhotoIsolationMode.SnapshotOnly || isolationMode == PhotoIsolationMode.GpuMasksOnly || isolationMode == PhotoIsolationMode.ClassMaskOnly || isolationMode == PhotoIsolationMode.VisibleMaskOnly)
									{
										PhotoCaptureProfiler.Event("isolation-" + isolationMode.ToString() + "-complete");
										PhotoFrameStallMonitor.Mark("isolation-" + isolationMode.ToString() + "-complete");
										result = captureResult;
										return true;
									}
									if (deferCpu && enablePerspectiveBase && !produceResearchDiagnostics && photoGeometryDiagnosticResult != null && string.IsNullOrEmpty(photoGeometryDiagnosticResult.Failure) && string.IsNullOrEmpty(captureResult.ScanFailure))
									{
										PhotoFrameStallMonitor.Mark("cpu-snapshot-freeze-enter");
										using (PhotoCaptureProfiler.Measure("CpuGeometrySnapshot"))
										{
											PhotoMeshBuffers.MeshSnapshot scene = PhotoMeshBuffers.CaptureSnapshot(result2, val2, plan.LookAt, width, height, meshRasterTriangleBudget);
											captureResult.DeferredCpu = new PhotoDeferredCpuRequest(scene, val6.GetPixels32(), photoGeometryDiagnosticResult, toneSettings, edgeSettings);
										}
										PhotoFrameStallMonitor.Mark("cpu-snapshot-freeze-exit");
									}
									if (captureResult.DeferredCpu == null && enablePerspectiveBase && photoGeometryDiagnosticResult != null && string.IsNullOrEmpty(photoGeometryDiagnosticResult.Failure) && (!deferCpu || string.IsNullOrEmpty(captureResult.ScanFailure)))
									{
										try
										{
											PhotoMeshBuffers photoMeshBuffers;
											using (PhotoCaptureProfiler.Measure("CpuMeshRaster"))
											{
												photoMeshBuffers = PhotoMeshBuffers.Create(result2, val2, plan.LookAt, width, height, meshRasterTriangleBudget);
											}
											mesh = photoMeshBuffers;
											captureResult.PerspectiveRasterMilliseconds = photoMeshBuffers.Milliseconds;
											captureResult.PerspectiveReadableTriangles = photoMeshBuffers.RasterizedTriangles;
											captureResult.PerspectiveUnreadableMeshes = photoMeshBuffers.UnreadableMeshes;
											using (PhotoCaptureProfiler.Measure("OptionalMeshDiagnosticPngs"))
											{
												if (produceResearchDiagnostics)
												{
													captureResult.ScanDepthMeshPng = photoMeshBuffers.EncodeDepthPng(photoGeometryDiagnosticResult.ClassPixels);
													captureResult.ScanNormalsMeshPng = photoMeshBuffers.EncodeNormalsPng(photoGeometryDiagnosticResult.ClassPixels);
												}
											}
											PhotoPerspectiveBaseResult photoPerspectiveBaseResult;
											using (PhotoCaptureProfiler.Measure("PerspectiveCompose"))
											{
												photoPerspectiveBaseResult = PhotoPerspectiveBase.Apply(val6, photoMeshBuffers, photoGeometryDiagnosticResult, produceResearchDiagnostics, toneSettings);
											}
											captureResult.PerspectiveStatus = photoPerspectiveBaseResult.Status;
											captureResult.PerspectiveApplied = photoPerspectiveBaseResult.Applied;
											if (photoPerspectiveBaseResult.Applied)
											{
												captureResult.ScanMaterialStyleName = "PerspectiveMeshBase / HDRP-Unlit opaque GPU proxies";
											}
											captureResult.PerspectiveCoverage = photoPerspectiveBaseResult.CoverageAgreement;
											captureResult.PerspectiveGpuOnlyPixels = photoPerspectiveBaseResult.GpuOnlyPixels;
											captureResult.PerspectiveMeshOnlyPixels = photoPerspectiveBaseResult.MeshOnlyPixels;
											captureResult.PerspectiveCompositeMilliseconds = photoPerspectiveBaseResult.CompositeMilliseconds;
											captureResult.ScanBasePng = photoPerspectiveBaseResult.BasePng;
											captureResult.ScanBasePreviousPng = photoPerspectiveBaseResult.PreviousBasePng;
											captureResult.ScanBaseDistanceOnlyPng = photoPerspectiveBaseResult.DistanceOnlyBasePng;
											captureResult.SilhouetteContrast = photoPerspectiveBaseResult.SilhouetteContrast;
											captureResult.ToneNearestDepth = photoPerspectiveBaseResult.NearestEnvironmentDepth;
											captureResult.ToneFarthestDepth = photoPerspectiveBaseResult.FarthestEnvironmentDepth;
											captureResult.ToneBlackEnvironmentPixels = photoPerspectiveBaseResult.BlackEnvironmentPixels;
											captureResult.ToneNearEnvironmentPixels = photoPerspectiveBaseResult.NearEnvironmentPixels;
											captureResult.ToneMiddleEnvironmentPixels = photoPerspectiveBaseResult.MiddleEnvironmentPixels;
											captureResult.ToneFarEnvironmentPixels = photoPerspectiveBaseResult.FarEnvironmentPixels;
											captureResult.ScanMeshCoveragePng = photoPerspectiveBaseResult.CoverageDifferencePng;
											if (!edgeSettings.Enabled)
											{
												captureResult.EdgeStatus = "disabled by configuration; 11a base retained";
											}
											else if (!photoPerspectiveBaseResult.Applied || photoPerspectiveBaseResult.CoverageAgreement < 0.85f)
											{
												captureResult.EdgeStatus = "edge fallback to 11a/opaque base: " + photoPerspectiveBaseResult.Status;
											}
											else
											{
												PhotoStructuralEdgeResult photoStructuralEdgeResult;
												using (PhotoCaptureProfiler.Measure("StructuralEdgeDetection"))
												{
													photoStructuralEdgeResult = PhotoStructuralEdges.Compute(photoMeshBuffers, photoGeometryDiagnosticResult, edgeSettings);
												}
												captureResult.EdgeStatus = photoStructuralEdgeResult.Status;
												captureResult.EdgeMilliseconds = photoStructuralEdgeResult.ProcessingMilliseconds;
												captureResult.EdgeDepthPixels = photoStructuralEdgeResult.DepthEdgePixels;
												captureResult.EdgeNormalPixels = photoStructuralEdgeResult.NormalEdgePixels;
												captureResult.EdgeObjectReinforced = photoStructuralEdgeResult.ObjectReinforcedPixels;
												captureResult.EdgeSuppressedNoise = photoStructuralEdgeResult.SuppressedNoisePixels;
												captureResult.EdgeSuppressedPlanarPairs = photoStructuralEdgeResult.SuppressedPlanarPairs;
												captureResult.EdgeSuppressedPlanarPixels = photoStructuralEdgeResult.SuppressedPlanarPixels;
												captureResult.EdgePlanarTestAvailable = photoStructuralEdgeResult.PlanarTestAvailable;
												captureResult.EdgeMonsterProtected = photoStructuralEdgeResult.ProtectedMonsterPixels;
												captureResult.EdgeHaloProtected = photoStructuralEdgeResult.ProtectedHaloPixels;
												captureResult.EdgeInvalidEnvironment = photoStructuralEdgeResult.InvalidEnvironmentPixels;
												captureResult.EdgeTotalPixels = photoStructuralEdgeResult.CombinedEdgePixels;
												captureResult.EdgeFraction = photoStructuralEdgeResult.EdgeFraction;
												using (PhotoCaptureProfiler.Measure("OptionalEdgeMaskPngs"))
												{
													if (edgeSettings.SaveEdgeMasks && photoStructuralEdgeResult.Depth.Length == width * height && photoStructuralEdgeResult.Normal.Length == width * height && photoStructuralEdgeResult.Combined.Length == width * height && photoStructuralEdgeResult.SuppressedPlanar.Length == width * height)
													{
														try
														{
															captureResult.ScanEdgeDepthPng = PhotoStructuralEdges.EncodeMask(photoMeshBuffers, photoStructuralEdgeResult.Depth);
															captureResult.ScanEdgeNormalPng = PhotoStructuralEdges.EncodeMask(photoMeshBuffers, photoStructuralEdgeResult.Normal);
															captureResult.ScanEdgeMaskPng = PhotoStructuralEdges.EncodeMask(photoMeshBuffers, photoStructuralEdgeResult.Combined);
															captureResult.ScanEdgePlanarSuppressedPng = PhotoStructuralEdges.EncodeMask(photoMeshBuffers, photoStructuralEdgeResult.SuppressedPlanar);
														}
														catch (Exception ex3)
														{
															captureResult.EdgeStatus = captureResult.EdgeStatus + "; PNG diagnostics skipped: " + ex3.GetType().Name;
														}
													}
												}
												if (photoStructuralEdgeResult.Accepted)
												{
													Color32[] pixels2 = val6.GetPixels32();
													long ticks5 = DateTime.UtcNow.Ticks;
													try
													{
														Color32[] pixels3;
														int contourPixels;
														using (PhotoCaptureProfiler.Measure("RadarEdgeComposite"))
														{
															pixels3 = PhotoRadarComposite.Compose(pixels2, photoMeshBuffers, photoGeometryDiagnosticResult, photoStructuralEdgeResult, edgeSettings, out contourPixels);
														}
														val6.SetPixels32(pixels3);
														val6.Apply(false, false);
														captureResult.EdgeApplied = true;
														captureResult.RadarContourPixels = contourPixels;
														captureResult.ScanMaterialStyleName = "PerspectiveMeshBase + StructuralRadarEdges (CPU mesh/GPU masks)";
													}
													catch (Exception ex4)
													{
														val6.SetPixels32(pixels2);
														val6.Apply(false, false);
														captureResult.EdgeStatus = "edge composite failed; 11a base retained: " + ex4.GetType().Name + ": " + ex4.Message;
													}
													finally
													{
														captureResult.EdgeCompositeMilliseconds = ElapsedMs(ticks5);
													}
												}
											}
										}
										catch (Exception ex5)
										{
											captureResult.PerspectiveStatus = "opaque preview fallback: mesh raster exception " + ex5.GetType().Name + ": " + ex5.Message;
										}
									}
									else if (!enablePerspectiveBase)
									{
										captureResult.PerspectiveStatus = "disabled by configuration: opaque GPU preview unchanged";
										captureResult.EdgeStatus = "edge fallback: perspective mesh base disabled";
									}
									else if (string.IsNullOrEmpty(captureResult.EdgeStatus) || captureResult.EdgeStatus == "not requested")
									{
										captureResult.EdgeStatus = "edge fallback: GPU reference unavailable";
									}
									if (produceResearchDiagnostics && photoGeometryDiagnosticResult != null && photoGeometryDiagnosticResult.ClassPixels != null && photoGeometryDiagnosticResult.VisibleMaskPixels != null && string.IsNullOrEmpty(photoGeometryDiagnosticResult.Failure))
									{
										try
										{
											PhotoRendererIdResult photoRendererIdResult;
											using (PhotoCaptureProfiler.Measure("OptionalRendererIdentity"))
											{
												photoRendererIdResult = PhotoRendererIdDiagnostics.Capture(val2, val3, result3, result2, photoGeometryDiagnosticResult, mesh, width, height, plan.LookAt);
											}
											captureResult.ScanRendererIdsPng = photoRendererIdResult.ImagePng;
											captureResult.ScanRendererIdsLegend = photoRendererIdResult.Legend;
											captureResult.ScanRendererIdsStatus = photoRendererIdResult.Status;
											captureResult.RendererIdsCalibrated = photoRendererIdResult.CalibratedSources;
											captureResult.RendererIdsDecodedPixels = photoRendererIdResult.MatchedPixels;
											captureResult.RendererIdsUnmatchedPixels = photoRendererIdResult.UnmatchedPixels;
											captureResult.RendererIdsMilliseconds = photoRendererIdResult.RenderMilliseconds;
										}
										catch (Exception ex6)
										{
											captureResult.ScanRendererIdsStatus = "nonfatal identity diagnostics: " + ex6.GetType().Name + ": " + ex6.Message;
										}
									}
									else if (produceResearchDiagnostics)
									{
										captureResult.ScanRendererIdsStatus = "not available: missing HDRP class/silhouette masks";
									}
									if (captureResult.DeferredCpu == null)
									{
										using (PhotoCaptureProfiler.Measure("FinalRadarGrade"))
										{
											captureResult.ScanVisibleFraction = PhotoRadarGrade.Apply(val6);
										}
										using (PhotoCaptureProfiler.Measure("FinalImagePngEncode"))
										{
											captureResult.ScanGreenPng = ImageConversion.EncodeToPNG(val6);
										}
										captureResult.ScanFinalPng = captureResult.ScanGreenPng;
									}
								}
								finally
								{
									Object.Destroy((Object)(object)val6);
								}
								captureResult.ScanRenderMilliseconds = ElapsedMs(ticks4);
							}
							if (captureResult.DeferredCpu == null && captureResult.ScanVisibleFraction < 0.001f && !captureResult.PerspectiveApplied)
							{
								captureResult.ScanFailure = "Scan contains almost no green terrain pixels; check camera / HDRP shader compatibility";
							}
						}
					}
					catch (Exception ex7)
					{
						if (ex7.Message.StartsWith("REJECT_CAMERA_BEFORE_SCAN_RENDER", StringComparison.Ordinal))
						{
							throw;
						}
						captureResult.ScanFailure = "Synthetic scan failed: " + ex7.GetType().Name + ": " + ex7.Message;
					}
				}
				if (produceResearchDiagnostics)
				{
					try
					{
						using (PhotoCaptureProfiler.Measure("OptionalRendererAudit"))
						{
							captureResult.RendererAuditText = PhotoRendererAudit.Build(enemy, plan, result3, result2);
						}
					}
					catch (Exception ex8)
					{
						captureResult.RendererAuditText = "Renderer audit failed: " + ex8.GetType().Name + ": " + ex8.Message;
					}
				}
				if (result3 != null)
				{
					captureResult.CameraPassExecutions = result3.ExecuteCount;
					captureResult.CameraPassBlackExecutions = result3.BlackExecutions;
					captureResult.CameraPassWhiteExecutions = result3.WhiteExecutions;
					captureResult.CameraPassDrawCalls = result3.DrawSubmeshCalls;
					captureResult.SourceIntegrity = (result3.VerifySources(out string issue) ? "PASS: original renderer materials, transform and flags unchanged" : ("FAIL: " + issue));
					if (!string.IsNullOrEmpty(result3.Failure))
					{
						captureResult.ScanFailure = "Camera-only custom pass failure: " + result3.Failure;
					}
					if (!captureResult.SourceIntegrity.StartsWith("PASS", StringComparison.Ordinal))
					{
						captureResult.ScanFailure = "Original renderer integrity failure: " + captureResult.SourceIntegrity;
					}
				}
				if (result3 != null)
				{
					captureResult.HDRPBufferAvailability = result3.BufferAvailability;
				}
				if (flag2 && isolationMode == PhotoIsolationMode.Normal)
				{
					if ((captureResult.DeferredCpu != null || captureResult.ScanFinalPng != null) && string.IsNullOrEmpty(captureResult.ScanFailure))
					{
						PhotoGeometryDiagnosticResult diagnostics = captureResult.Diagnostics;
						if (!captureResult.DiagnosticLegacyAlignedToScan || captureResult.DiagnosticLegacyRenderCount != 1 || captureResult.LegacyGreenPng == null || diagnostics == null || !diagnostics.ClassMaskCompleted || !diagnostics.VisibleMaskCompleted || !diagnostics.PhysicsReferenceCompleted || !string.IsNullOrEmpty(diagnostics.Failure))
						{
							captureResult.ScanFailure = "Experimental final-view safety gate rejected incomplete or unaligned legacy/GPU/physics capture";
							captureResult.DeferredCpu = null;
							captureResult.ScanFinalPng = null;
							captureResult.ScanGreenPng = null;
							PhotoCaptureProfiler.Event("i24-production-final-view:fail-closed-safety-gate");
						}
					}
					PhotoCaptureProfiler.Event("i24-production-final-view:legacyCount=" + captureResult.DiagnosticLegacyRenderCount + ":aligned=" + captureResult.DiagnosticLegacyAlignedToScan + ":fallbackInitial=" + captureResult.DiagnosticLegacyFallbackFirstView + ":scanFailure=" + (string.IsNullOrEmpty(captureResult.ScanFailure) ? "none" : "present"));
				}
				captureResult.CameraPlacementAuditText = plan.PlacementAudit.ToString();
				result = captureResult;
				return true;
			}
			catch (Exception ex9)
			{
				error = (ex9.Message.StartsWith("REJECT_CAMERA", StringComparison.Ordinal) ? "camera placement: " : "HDRP camera render/readback: ") + ex9.GetType().Name + ": " + ex9.Message;
				return false;
			}
			finally
			{
				cameraPlacementAudit = plan.PlacementAudit.ToString();
				RenderTexture.active = active;
				if ((Object)(object)val2 != (Object)null)
				{
					((Behaviour)val2).enabled = false;
					val2.targetTexture = null;
				}
				PhotoFrameStallMonitor.Mark("native-cleanup-enter");
				using (PhotoCaptureProfiler.Measure("CaptureResourceCleanup"))
				{
					using (PhotoSnapshotStageTrace.Measure("Cleanup.ReturnSceneProxiesAndMaterials"))
					{
						result2?.Dispose();
					}
					if ((Object)(object)val != (Object)null && PhotoCaptureIsolation.CleanupMode != PhotoNativeCleanupMode.Immediate)
					{
						bool flag7 = PhotoCaptureIsolation.CleanupMode == PhotoNativeCleanupMode.DelayCameraPassAndTarget;
						RenderTexture target = (flag7 ? val3 : null);
						if (PhotoNativeCleanupQueue.TryHold(val, result3, target, PhotoCaptureIsolation.CleanupDelayFrames))
						{
							val = null;
							result3 = null;
							if (flag7)
							{
								val3 = null;
							}
						}
					}
					using (PhotoSnapshotStageTrace.Measure("Cleanup.ReleaseTemporaryRenderTarget"))
					{
						if ((Object)(object)val3 != (Object)null)
						{
							PhotoFrameStallMonitor.Mark("i32-native-rt-release-requested");
							RenderTexture.ReleaseTemporary(val3);
						}
					}
					using (PhotoSnapshotStageTrace.Measure("Cleanup.DestroyCameraObject"))
					{
						if ((Object)(object)val != (Object)null)
						{
							PhotoFrameStallMonitor.Mark("i32-native-camera-destroy-queued");
							Object.Destroy((Object)(object)val);
						}
					}
					using (PhotoSnapshotStageTrace.Measure("Cleanup.CustomPassDispose"))
					{
						result3?.Dispose();
					}
				}
				PhotoFrameStallMonitor.Mark("native-cleanup-exit");
			}
		}

		internal static void FinishDeferred(CaptureResult output, PhotoDeferredCpuResult data)
		{
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Expected O, but got Unknown
			if (output.DeferredCpu == null)
			{
				throw new InvalidOperationException("Missing deferred capture context");
			}
			PhotoDeferredCpuRequest deferredCpu = output.DeferredCpu;
			if (data.Pixels.Length != deferredCpu.Scene.Width * deferredCpu.Scene.Height)
			{
				throw new InvalidOperationException("Deferred capture returned invalid image dimensions");
			}
			output.PerspectiveRasterMilliseconds = (long)data.RasterMs;
			output.PerspectiveReadableTriangles = data.Mesh.RasterizedTriangles;
			output.PerspectiveUnreadableMeshes = data.Mesh.UnreadableMeshes;
			PhotoPerspectiveBaseResult grade = data.Grade;
			output.PerspectiveStatus = grade.Status;
			output.PerspectiveApplied = grade.Applied;
			output.PerspectiveCoverage = grade.CoverageAgreement;
			output.PerspectiveGpuOnlyPixels = grade.GpuOnlyPixels;
			output.PerspectiveMeshOnlyPixels = grade.MeshOnlyPixels;
			output.PerspectiveCompositeMilliseconds = grade.CompositeMilliseconds;
			output.SilhouetteContrast = grade.SilhouetteContrast;
			output.ToneNearestDepth = grade.NearestEnvironmentDepth;
			output.ToneFarthestDepth = grade.FarthestEnvironmentDepth;
			output.ToneBlackEnvironmentPixels = grade.BlackEnvironmentPixels;
			output.ToneNearEnvironmentPixels = grade.NearEnvironmentPixels;
			output.ToneMiddleEnvironmentPixels = grade.MiddleEnvironmentPixels;
			output.ToneFarEnvironmentPixels = grade.FarEnvironmentPixels;
			if (grade.Applied)
			{
				output.ScanMaterialStyleName = "PerspectiveMeshBase / HDRP-Unlit opaque GPU proxies";
			}
			if (!deferredCpu.Edges.Enabled)
			{
				output.EdgeStatus = "disabled by configuration; 11a base retained";
			}
			else if (!grade.Applied || grade.CoverageAgreement < 0.85f)
			{
				output.EdgeStatus = "edge fallback to 11a/opaque base: " + grade.Status;
			}
			else if (data.EdgeResult != null)
			{
				PhotoStructuralEdgeResult edgeResult = data.EdgeResult;
				output.EdgeStatus = edgeResult.Status;
				output.EdgeMilliseconds = edgeResult.ProcessingMilliseconds;
				output.EdgeDepthPixels = edgeResult.DepthEdgePixels;
				output.EdgeNormalPixels = edgeResult.NormalEdgePixels;
				output.EdgeObjectReinforced = edgeResult.ObjectReinforcedPixels;
				output.EdgeSuppressedNoise = edgeResult.SuppressedNoisePixels;
				output.EdgeSuppressedPlanarPairs = edgeResult.SuppressedPlanarPairs;
				output.EdgeSuppressedPlanarPixels = edgeResult.SuppressedPlanarPixels;
				output.EdgePlanarTestAvailable = edgeResult.PlanarTestAvailable;
				output.EdgeMonsterProtected = edgeResult.ProtectedMonsterPixels;
				output.EdgeHaloProtected = edgeResult.ProtectedHaloPixels;
				output.EdgeInvalidEnvironment = edgeResult.InvalidEnvironmentPixels;
				output.EdgeTotalPixels = edgeResult.CombinedEdgePixels;
				output.EdgeFraction = edgeResult.EdgeFraction;
				if (data.EdgeApplied)
				{
					output.EdgeApplied = true;
					output.RadarContourPixels = data.ContourPixels;
					output.ScanMaterialStyleName = "PerspectiveMeshBase + StructuralRadarEdges (CPU mesh/GPU masks)";
				}
				if (data.EdgeCompositeError.Length > 0)
				{
					output.EdgeStatus = "edge composite failed; 11a base retained: " + data.EdgeCompositeError;
				}
				output.EdgeCompositeMilliseconds = (long)data.EdgeCompositeMs;
			}
			output.MonsterPixelationApplied = data.PixelationApplied;
			output.MonsterPixelationPixels = data.PixelationPixels;
			output.MonsterPixelationStrongPixels = data.PixelationStrongPixels;
			output.MonsterPixelationBlocks = data.PixelationBlocks;
			output.MonsterPixelationMilliseconds = data.PixelationMs;
			output.MonsterPixelationFailure = data.PixelationFailure;
			Texture2D val = new Texture2D(deferredCpu.Scene.Width, deferredCpu.Scene.Height, (TextureFormat)3, false)
			{
				name = "ThreatPhoto_DeferredFinal",
				filterMode = (FilterMode)0
			};
			try
			{
				val.SetPixels32(data.Pixels);
				val.Apply(false, false);
				using (PhotoCaptureProfiler.Measure("FinalRadarGrade"))
				{
					output.ScanVisibleFraction = PhotoRadarGrade.Apply(val);
				}
				using (PhotoCaptureProfiler.Measure("FinalImagePngEncode"))
				{
					output.ScanGreenPng = ImageConversion.EncodeToPNG(val);
				}
				output.ScanFinalPng = output.ScanGreenPng;
				if (output.ScanVisibleFraction < 0.001f && !output.PerspectiveApplied)
				{
					output.ScanFailure = "Scan contains almost no green terrain pixels; check camera / HDRP shader compatibility";
				}
			}
			finally
			{
				Object.Destroy((Object)(object)val);
				output.DeferredCpu = null;
			}
			output.ScanRenderMilliseconds += (long)data.TotalMs;
		}

		private static void RenderPostSelectionLegacyReference(Camera camera, RenderTexture target, PhotoMonsterPassSession monster, CaptureResult output, int width, int height, bool saveRaw, string stageLabel)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)camera).transform.position;
			PhotoCaptureProfiler.Event("i23-legacy-reference-start:" + stageLabel + ":eye=" + ((Vector3)(ref position)).ToString("F3"));
			PhotoFrameStallMonitor.Mark("i23-legacy-reference-enter:" + stageLabel);
			using (PhotoCaptureProfiler.Measure("LegacyReference"))
			{
				using (PhotoSnapshotStageTrace.Measure("LegacyReference.PostValidatedView"))
				{
					long ticks = DateTime.UtcNow.Ticks;
					monster.SetMode(MonsterOverrideMode.Disabled);
					Texture2D val = RenderReadback(camera, target, monster, width, height, stageLabel);
					try
					{
						if (saveRaw)
						{
							output.LegacyRawPng = ImageConversion.EncodeToPNG(val);
						}
						PhotoColorGrade.ApplyGreenFacilityLook(val);
						output.LegacyGreenPng = ImageConversion.EncodeToPNG(val);
					}
					finally
					{
						Object.Destroy((Object)(object)val);
					}
					output.LegacyRenderMilliseconds += ElapsedMs(ticks);
					output.DiagnosticLegacyRenderCount++;
					position = ((Component)camera).transform.position;
					output.DiagnosticLegacyReferenceEye = ((Vector3)(ref position)).ToString("F3");
				}
			}
			PhotoCaptureProfiler.Event("i23-legacy-reference-complete:" + stageLabel + ":count=" + output.DiagnosticLegacyRenderCount + ":eye=" + output.DiagnosticLegacyReferenceEye);
			PhotoFrameStallMonitor.Mark("i23-legacy-reference-exit:" + stageLabel);
		}

		internal static Texture2D RenderReadback(Camera camera, RenderTexture target, PhotoMonsterPassSession monster, int width, int height, string passLabel = "Unlabeled")
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			PhotoCaptureProfiler.Event("i23-gpu-pass-start:" + passLabel);
			using (PhotoSnapshotStageTrace.Measure("GPU." + passLabel + ".ClearTarget"))
			{
				RenderTexture active = RenderTexture.active;
				try
				{
					RenderTexture.active = target;
					GL.Clear(true, true, camera.backgroundColor);
				}
				finally
				{
					RenderTexture.active = active;
				}
			}
			int executeCount = monster.ExecuteCount;
			using (PhotoCaptureProfiler.Measure("HDRP.CameraRender"))
			{
				using (PhotoSnapshotStageTrace.Measure("GPU." + passLabel + ".CameraRender"))
				{
					camera.Render();
				}
			}
			if (monster.Mode != MonsterOverrideMode.Disabled && monster.ExecuteCount == executeCount)
			{
				throw new InvalidOperationException("CustomPassUnavailable: no CustomPass.Execute for the photo camera (HDRP frame setting disabled?)");
			}
			if (monster.Mode != MonsterOverrideMode.Disabled && !string.IsNullOrEmpty(monster.Failure))
			{
				throw new InvalidOperationException(monster.Failure);
			}
			Texture2D val = null;
			RenderTexture active2 = RenderTexture.active;
			try
			{
				using (PhotoSnapshotStageTrace.Measure("GPU." + passLabel + ".TextureCreate"))
				{
					val = new Texture2D(width, height, (TextureFormat)3, false)
					{
						name = "ThreatPhoto_StillFrame",
						filterMode = (FilterMode)0
					};
				}
				RenderTexture.active = target;
				using (PhotoCaptureProfiler.Measure("HDRP.ReadPixels"))
				{
					using (PhotoSnapshotStageTrace.Measure("GPU." + passLabel + ".ReadPixels"))
					{
						val.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0, false);
					}
				}
				using (PhotoCaptureProfiler.Measure("HDRP.ReadbackApply"))
				{
					using (PhotoSnapshotStageTrace.Measure("GPU." + passLabel + ".Apply"))
					{
						val.Apply(false, false);
					}
				}
				Texture2D result = val;
				val = null;
				PhotoCaptureProfiler.Event("i23-gpu-pass-complete:" + passLabel);
				return result;
			}
			finally
			{
				RenderTexture.active = active2;
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}

		private static string SanitizeViewReason(string reason)
		{
			string text = (reason ?? "unknown").Replace(',', ';').Replace('\r', ' ').Replace('\n', ' ');
			if (text.Length > 180)
			{
				return text.Substring(0, 180);
			}
			return text;
		}

		private static long ElapsedMs(long startTicks)
		{
			return (DateTime.UtcNow.Ticks - startTicks) / 10000;
		}

		private static bool TryDisableVolumesForScan(GameObject cameraObject)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			Component[] components = cameraObject.GetComponents<Component>();
			foreach (Component val in components)
			{
				if ((Object)(object)val == (Object)null || ((object)val).GetType().FullName != "UnityEngine.Rendering.HighDefinition.HDAdditionalCameraData")
				{
					continue;
				}
				try
				{
					PropertyInfo property = ((object)val).GetType().GetProperty("volumeLayerMask", BindingFlags.Instance | BindingFlags.Public);
					if (property == null || !property.CanWrite)
					{
						return false;
					}
					property.SetValue(val, LayerMask.op_Implicit(0));
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}
			return false;
		}

		private static void TryAttachHDRPCameraData(GameObject cameraObject)
		{
			Type type = null;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				string name = assembly.GetName().Name;
				if (name != null && name.StartsWith("Unity.RenderPipelines.HighDefinition", StringComparison.Ordinal))
				{
					type = assembly.GetType("UnityEngine.Rendering.HighDefinition.HDAdditionalCameraData", throwOnError: false);
					if (type != null)
					{
						break;
					}
				}
			}
			if (type != null && typeof(Component).IsAssignableFrom(type) && (Object)(object)cameraObject.GetComponent(type) == (Object)null)
			{
				cameraObject.AddComponent(type);
			}
		}

		internal static IEnumerator TryCaptureStagedSteps(EnemyAI enemy, int width, int height, bool saveRaw, PhotoSceneStyle style, int maxSceneMeshes, int maxSceneTriangles, ScanMaterialStyle scanMaterialStyle, float radarSpacing, float radarWidth, bool produceResearchDiagnostics, int diagnosticPixelStep, bool enablePerspectiveBase, int meshRasterTriangleBudget, bool deferCpu, bool silhouetteAwarePhysics, bool reuseSceneProxies, PhotoDistanceToneSettings toneSettings, PhotoRadarEdgeSettings edgeSettings, PhotoIsolationMode isolationMode, PhotoStagedCaptureOutcome outcome, float frameBudgetMs, IReadOnlyList<Vector3>? rejectedVisibleEyes = null, bool requestOneShotZeroVisibleTest = false)
		{
			bool result = null;
			string error = "";
			Vector3 targetStartPosition = ((Component)enemy).transform.position;
			PhotoCameraPlan plan;
			RenderTexture flag;
			using (PhotoCaptureProfiler.Measure("CameraPlacement"))
			{
				flag = CameraPlacement.TryPlan(enemy, (float)width / (float)height, out plan, out error);
			}
			string cameraPlacementAudit;
			if (!flag)
			{
				cameraPlacementAudit = plan.PlacementAudit.ToString();
				error = "camera placement: " + error;
				outcome.Finish(success: false, result, error, cameraPlacementAudit);
				yield break;
			}
			if (rejectedVisibleEyes != null && rejectedVisibleEyes.Count > 0)
			{
				bool flag2 = false;
				foreach (PhotoVerifiedCameraOption verifiedOption in plan.VerifiedOptions)
				{
					if (verifiedOption.Visible <= 0)
					{
						continue;
					}
					bool flag3 = false;
					foreach (Vector3 rejectedVisibleEye in rejectedVisibleEyes)
					{
						if (Vector3.Distance(verifiedOption.Eye, rejectedVisibleEye) < 0.25f)
						{
							flag3 = true;
							break;
						}
					}
					if (!flag3 && plan.InteriorContext != null && PhotoInteriorValidator.Revalidate(enemy, plan.InteriorContext, verifiedOption.Floor, verifiedOption.Eye, plan.LookAt, 63f, (float)width / (float)height, 0.07f, out string _))
					{
						plan.Position = verifiedOption.Eye;
						plan.CameraNavFloor = verifiedOption.Floor;
						plan.CameraEyeHeight = verifiedOption.EyeHeight;
						plan.VisibilitySamples = verifiedOption.Visible;
						plan.PlacementScore = verifiedOption.Score;
						plan.PlacementAudit.Note("i36 STRICT_ALTERNATE_AFTER_EMPTY: eye=" + ((Vector3)(ref verifiedOption.Eye)).ToString("F3") + " excluded=" + rejectedVisibleEyes.Count);
						PhotoCaptureProfiler.Event("i36-empty-retry-new-eye:" + ((Vector3)(ref verifiedOption.Eye)).ToString("F3"));
						flag2 = true;
						break;
					}
				}
				if (!flag2)
				{
					error = "i36 no untried strictly validated viewpoint after zero-visible silhouette";
					plan.PlacementAudit.Note(error);
					outcome.Finish(success: false, null, error, plan.PlacementAudit.ToString());
					yield break;
				}
			}
			cameraPlacementAudit = plan.PlacementAudit.ToString();
			CaptureResult output = new CaptureResult
			{
				EnemyMeshCount = plan.Meshes.Count,
				SilhouetteShaderName = "HDRP/Unlit (camera-only original renderer)",
				UsedCulledRenderers = plan.UsedCulledRenderers,
				CameraPosition = plan.Position,
				CameraNavFloor = plan.CameraNavFloor,
				CameraVisibleSamples = plan.VisibilitySamples,
				CameraPlacementScore = plan.PlacementScore,
				CameraPlacementAuditText = cameraPlacementAudit
			};
			if (isolationMode == PhotoIsolationMode.PlacementOnly)
			{
				PhotoCaptureProfiler.Event("isolation-placement-complete");
				PhotoFrameStallMonitor.Mark("isolation-placement-only-complete");
				outcome.Finish(success: true, output, error, cameraPlacementAudit);
				yield break;
			}
			GameObject cameraObject = null;
			Camera camera = null;
			bool finalViewLegacy = style != PhotoSceneStyle.Legacy && PhotoCaptureIsolation.UseFinalViewLegacyReference(isolationMode);
			RenderTexture renderTarget = null;
			RenderTexture priorActive = null;
			bool renderTargetAcquired = false;
			PhotoSceneSession scene = null;
			PhotoMonsterPassSession monster = null;
			try
			{
				PhotoFrameStallMonitor.Mark("hdrp-camera-setup-enter");
				using (PhotoCaptureProfiler.Measure("CameraSetup"))
				{
					cameraObject = new GameObject("ThreatPhoto_TemporaryHDRPCamera")
					{
						hideFlags = (HideFlags)61
					};
					PhotoFrameStallMonitor.Mark("i32-native-camera-object-created");
					camera = cameraObject.AddComponent<Camera>();
					PhotoFrameStallMonitor.Mark("i32-native-camera-component-added");
					((Behaviour)camera).enabled = false;
					TryAttachHDRPCameraData(cameraObject);
					Camera main = Camera.main;
					if ((Object)(object)main != (Object)null && (Object)(object)main != (Object)(object)camera)
					{
						camera.CopyFrom(main);
					}
					PhotoFrameStallMonitor.Mark("i32-native-camera-configured");
					((Behaviour)camera).enabled = false;
					((Component)camera).transform.position = plan.Position;
					((Component)camera).transform.rotation = Quaternion.LookRotation(plan.LookAt - plan.Position, Vector3.up);
					camera.orthographic = false;
					camera.rect = new Rect(0f, 0f, 1f, 1f);
					camera.fieldOfView = 63f;
					camera.aspect = (float)width / (float)height;
					camera.nearClipPlane = 0.07f;
					camera.farClipPlane = 100f;
					camera.clearFlags = (CameraClearFlags)2;
					camera.backgroundColor = new Color(0.03f, 0.04f, 0.025f, 1f);
					camera.allowHDR = true;
					camera.allowMSAA = false;
					camera.allowDynamicResolution = false;
					camera.useOcclusionCulling = false;
					int num = 4210688;
					Camera obj = camera;
					obj.cullingMask &= ~num;
					string reason2 = "missing strict interior context";
					if (plan.InteriorContext == null || !PhotoInteriorValidator.Revalidate(enemy, plan.InteriorContext, plan.CameraNavFloor, plan.Position, plan.LookAt, camera.fieldOfView, camera.aspect, camera.nearClipPlane, out reason2))
					{
						plan.PlacementAudit.Note("REJECT_CAMERA_BEFORE_FIRST_RENDER: " + reason2);
						error = "camera placement: REJECT_CAMERA_BEFORE_FIRST_RENDER: " + reason2;
						outcome.Finish(success: false, result, error, cameraPlacementAudit);
						yield break;
					}
					plan.PlacementAudit.Note("PASS_CAMERA_BEFORE_FIRST_RENDER: " + ((Vector3)(ref plan.Position)).ToString("F3"));
				}
				if (!finalViewLegacy || style == PhotoSceneStyle.Legacy || isolationMode != PhotoIsolationMode.Normal)
				{
					error = "i34 staging requires Normal synthetic scan with final-view legacy enabled";
					outcome.Finish(success: false, null, error, cameraPlacementAudit);
					yield break;
				}
				PhotoCaptureProfiler.Event("i34-legacy-deferred-until-validated-view");
				PhotoFrameStallMonitor.Mark("i34-legacy-deferred");
				if (style != PhotoSceneStyle.Legacy)
				{
					long start = DateTime.UtcNow.Ticks;
					StringBuilder occlusionReports = new StringBuilder();
					string scanError = "";
					Vector3 firstEye = plan.Position;
					Vector3 firstFloor = plan.CameraNavFloor;
					float firstEyeHeight = plan.CameraEyeHeight;
					float firstScore = plan.PlacementScore;
					int firstVisible = plan.VisibilitySamples;
					bool foundScene = false;
					int viewAttempts = 0;
					int totalViewAttempts = 0;
					int motionReplans = 0;
					int alternativesTried = 0;
					int maxOptions = Math.Min(plan.VerifiedOptions.Count, 12);
					int maxViewAttempts = PhotoCaptureIsolation.MaxViewAttempts(isolationMode);
					output.DiagnosticSingleSafeView = isolationMode != PhotoIsolationMode.Normal && maxViewAttempts == 1;
					int optionIndex = 0;
					List<Vector3> triedEyes = new List<Vector3> { firstEye };
					if (rejectedVisibleEyes != null)
					{
						foreach (Vector3 rejectedVisibleEye2 in rejectedVisibleEyes)
						{
							triedEyes.Add(rejectedVisibleEye2);
						}
					}
					while (viewAttempts < maxViewAttempts && totalViewAttempts < PhotoStagedRetryPolicy.MaximumTotalViewAttempts(maxViewAttempts))
					{
						PhotoFrameStallMonitor.Mark("hdrp-scene-construction-enter");
						if (viewAttempts > 0)
						{
							bool flag4 = false;
							while (optionIndex < maxOptions)
							{
								PhotoVerifiedCameraOption photoVerifiedCameraOption = plan.VerifiedOptions[optionIndex++];
								if (photoVerifiedCameraOption.Visible <= 0)
								{
									continue;
								}
								bool flag5 = false;
								foreach (Vector3 item in triedEyes)
								{
									if (Vector3.Distance(photoVerifiedCameraOption.Eye, item) < 0.25f)
									{
										flag5 = true;
										break;
									}
								}
								if (!flag5)
								{
									if (PhotoInteriorValidator.Revalidate(enemy, plan.InteriorContext, photoVerifiedCameraOption.Floor, photoVerifiedCameraOption.Eye, plan.LookAt, camera.fieldOfView, camera.aspect, camera.nearClipPlane, out string reason3))
									{
										plan.Position = photoVerifiedCameraOption.Eye;
										plan.CameraNavFloor = photoVerifiedCameraOption.Floor;
										plan.CameraEyeHeight = photoVerifiedCameraOption.EyeHeight;
										plan.VisibilitySamples = photoVerifiedCameraOption.Visible;
										plan.PlacementScore = photoVerifiedCameraOption.Score;
										((Component)camera).transform.position = photoVerifiedCameraOption.Eye;
										((Component)camera).transform.rotation = Quaternion.LookRotation(plan.LookAt - photoVerifiedCameraOption.Eye, Vector3.up);
										plan.PlacementAudit.Note("TRY_SCAN_ALTERNATE " + ((Vector3)(ref photoVerifiedCameraOption.Eye)).ToString("F3") + " score=" + photoVerifiedCameraOption.Score.ToString("F2"));
										alternativesTried++;
										triedEyes.Add(photoVerifiedCameraOption.Eye);
										flag4 = true;
										break;
									}
									PhotoCaptureProfiler.Event("i23-view-option-rejected:safety:" + SanitizeViewReason(reason3));
									plan.PlacementAudit.Note("REJECT_SCAN_ALTERNATE " + ((Vector3)(ref photoVerifiedCameraOption.Eye)).ToString("F3") + " " + reason3);
								}
							}
							if (!flag4)
							{
								break;
							}
						}
						viewAttempts++;
						totalViewAttempts++;
						PhotoCaptureProfiler.Event("i23-view-" + totalViewAttempts + ":begin:" + ((viewAttempts == 1) ? "initial" : "alternate") + ":eye=" + ((Vector3)(ref plan.Position)).ToString("F3"));
						PhotoFrameStallMonitor.Mark("i23-view-" + viewAttempts + "-begin");
						PhotoSceneGeometryCollector.StagedInventoryResult stagedInventory = new PhotoSceneGeometryCollector.StagedInventoryResult();
						IEnumerator collect = PhotoSceneGeometryCollector.CollectStaged(plan, camera, enemy, maxSceneMeshes, maxSceneTriangles, frameBudgetMs, stagedInventory);
						using (collect as IDisposable)
						{
							while (collect.MoveNext())
							{
								PhotoFrameStallMonitor.Mark("i34-scene-collection-yield");
								yield return null;
							}
						}
						PhotoCaptureProfiler.Event("i35-inventory-complete:yields=" + stagedInventory.YieldedFrames);
						yield return null;
						bool flag6 = false;
						int reservedLayer = -1;
						string audit;
						string reason4;
						if (stagedInventory.Value == null || !stagedInventory.Complete)
						{
							scanError = "i35 incomplete staged geometry inventory";
							audit = scanError;
						}
						else if (!string.IsNullOrEmpty(stagedInventory.Value.Failure))
						{
							scanError = stagedInventory.Value.Failure;
							audit = stagedInventory.Value.OcclusionAudit;
						}
						else if ((Object)(object)enemy == (Object)null || Vector3.Distance(((Component)enemy).transform.position, targetStartPosition) > 1.5f)
						{
							scanError = "i35 target moved during staged preparation";
							audit = scanError;
						}
						else if (!IsResumedCameraSafe(enemy, plan, camera, out reason4))
						{
							scanError = "REJECT_CAMERA_BEFORE_LAYER_PREP: " + reason4;
							audit = scanError;
						}
						else
						{
							using (PhotoSnapshotStageTrace.Measure("i35.PrivateLayerDiscovery"))
							{
								flag6 = PhotoSceneSession.TryPrepareUnusedLayer(out reservedLayer);
							}
							if (!flag6)
							{
								scanError = "i35 no unoccupied camera-only layer";
								audit = scanError;
							}
							else
							{
								PhotoCaptureProfiler.Event("i35-layer-prepared:" + reservedLayer);
								yield return null;
								string reason5;
								if ((Object)(object)enemy == (Object)null || Vector3.Distance(((Component)enemy).transform.position, targetStartPosition) > 1.5f)
								{
									flag6 = false;
									scanError = "i35 target moved during staged layer preparation";
									audit = scanError;
								}
								else if (!IsResumedCameraSafe(enemy, plan, camera, out reason5))
								{
									flag6 = false;
									scanError = "REJECT_CAMERA_BEFORE_PROXY_PREP: " + reason5;
									audit = scanError;
								}
								else
								{
									using (PhotoSnapshotStageTrace.Measure("i35.PreBindOcclusion"))
									{
										scanError = PhotoOcclusionAudit.Check(plan, enemy, stagedInventory.Value);
									}
									if (!string.IsNullOrEmpty(scanError))
									{
										flag6 = false;
										audit = stagedInventory.Value.OcclusionAudit;
									}
									else
									{
										using (PhotoCaptureProfiler.Measure("SceneConstruction"))
										{
											using (PhotoSnapshotStageTrace.Measure("i35.InactiveSceneConstruction"))
											{
												flag6 = PhotoSceneSession.TryCreateFromInventory(enemy, plan, camera, maxSceneMeshes, maxSceneTriangles, ScanMaterialStyle.PriorDistanceEdges, radarSpacing, radarWidth, reuseSceneProxies && !produceResearchDiagnostics, stagedInventory.Value, out scene, out scanError, out audit, reservedLayer, prepareInactive: true);
											}
										}
									}
								}
								if (flag6 && scene != null)
								{
									PhotoCaptureProfiler.Event("i35-inactive-proxies-prepared:" + scene.MeshCount);
									yield return null;
									string reason6;
									if ((Object)(object)enemy == (Object)null || Vector3.Distance(((Component)enemy).transform.position, targetStartPosition) > 1.5f)
									{
										flag6 = false;
										scanError = "i35 target moved during inactive proxy preparation";
									}
									else if (!IsResumedCameraSafe(enemy, plan, camera, out reason6))
									{
										flag6 = false;
										scanError = "REJECT_CAMERA_BEFORE_SCAN_RENDER: " + reason6;
									}
									else
									{
										using (PhotoSnapshotStageTrace.Measure("i35.FinalOcclusionRevalidation"))
										{
											scanError = PhotoOcclusionAudit.Check(plan, enemy, stagedInventory.Value);
										}
										if (string.IsNullOrEmpty(scanError))
										{
											using (PhotoSnapshotStageTrace.Measure("i35.ActivatePreparedProxies"))
											{
												flag6 = scene.TryActivatePreparedView(out scanError);
											}
										}
										else
										{
											flag6 = false;
										}
									}
									if (!flag6)
									{
										audit = stagedInventory.Value.OcclusionAudit + "\n" + scanError;
										scene.Dispose();
										scene = null;
									}
								}
							}
						}
						PhotoFrameStallMonitor.Mark("hdrp-scene-construction-exit");
						occlusionReports.AppendLi