Decompiled source of BonelabCinematicCamera v1.0.1

Mods\BonelabCinematicCamera.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BoneLib;
using BoneLib.BoneMenu;
using BoneLib.Notifications;
using BonelabCinematicCamera.Audio;
using BonelabCinematicCamera.Camera;
using BonelabCinematicCamera.Camera.Presets;
using BonelabCinematicCamera.Core;
using BonelabCinematicCamera.Fusion;
using BonelabCinematicCamera.Gallery;
using BonelabCinematicCamera.Input;
using BonelabCinematicCamera.Menu;
using BonelabCinematicCamera.Quest;
using BonelabCinematicCamera.Recording;
using BonelabCinematicCamera.Recording.Recovery;
using BonelabCinematicCamera.Recording.Replay;
using BonelabCinematicCamera.Rendering;
using BonelabCinematicCamera.UI;
using BonelabCinematicCamera.Util;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.Data;
using Il2CppSLZ.Marrow.Interaction;
using Il2CppSLZ.Marrow.Pool;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(ModEntry), "Cinematic Camera", "1.15.2", "BonelabCamMod", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: MelonPlatform(/*Could not decode attribute arguments.*/)]
[assembly: MelonColor(255, 90, 190, 255)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BonelabCinematicCamera.Util
{
	public static class FreeLayerPicker
	{
		public const int TotalLayers = 32;

		public static int Pick(IReadOnlyList<string> namesByIndex)
		{
			if (namesByIndex == null)
			{
				return -1;
			}
			int num = Math.Min(namesByIndex.Count, 32);
			for (int i = 8; i < num; i++)
			{
				if (IsFree(namesByIndex[i]))
				{
					return i;
				}
			}
			for (int j = 0; j < Math.Min(8, num); j++)
			{
				if (IsFree(namesByIndex[j]))
				{
					return j;
				}
			}
			return -1;
		}

		private static bool IsFree(string name)
		{
			return string.IsNullOrWhiteSpace(name);
		}
	}
	public static class ModLayers
	{
		private const int UiLayerIndex = 5;

		private const int TotalLayers = 32;

		private static int _hudLayer = -1;

		public static int HudBit => 1 << HudLayer();

		public static int HudLayer()
		{
			if (_hudLayer >= 0)
			{
				return _hudLayer;
			}
			int num = ResolveUiLayerIndex();
			if (num >= 0)
			{
				_hudLayer = num;
				ModLog.Info($"Recording badge layer resolved to the UI layer, index {num}. " + "Lenses have always excluded it, and the player's cameras draw it.");
				return _hudLayer;
			}
			int num2 = FreeLayerPicker.Pick(ReadLayerNames());
			if (num2 < 0)
			{
				num2 = 5;
				ModLog.Warn("Neither the UI layer nor a free layer could be resolved; the recording badge falls back to layer 5.");
			}
			else
			{
				ModLog.Warn($"The UI layer could not be resolved, so the recording badge falls back to free layer {num2}. Its visibility is forced onto the " + "player's cameras either way.");
			}
			_hudLayer = num2;
			return _hudLayer;
		}

		public static void Reset()
		{
			_hudLayer = -1;
		}

		private static int ResolveUiLayerIndex()
		{
			int num;
			try
			{
				num = 32;
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "GameLayers.UI unavailable: " + ModLog.Describe(ex3));
				return 5;
			}
			for (int num2 = 0; num2 < 32; num2++)
			{
				if (num == 1 << num2)
				{
					return num2;
				}
			}
			return -1;
		}

		private static string[] ReadLayerNames()
		{
			string[] array = new string[32];
			for (int i = 0; i < 32; i++)
			{
				try
				{
					array[i] = LayerMask.LayerToName(i);
				}
				catch
				{
					array[i] = null;
				}
			}
			return array;
		}
	}
	public sealed class LoadedModel
	{
		public Mesh Mesh;

		public Bounds LocalBounds;

		public int TriangleCount;

		public int VertexCount;
	}
	public static class ObjMeshLoader
	{
		public static LoadedModel Parse(string objText, string meshName, bool recentreOnBounds)
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Expected O, but got Unknown
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(objText))
			{
				throw new ArgumentException("Empty OBJ text", "objText");
			}
			List<Vector3> list = new List<Vector3>(1024);
			List<Vector2> list2 = new List<Vector2>(1024);
			List<Vector3> list3 = new List<Vector3>(1024);
			Dictionary<long, int> lookup = new Dictionary<long, int>(2048);
			List<Vector3> list4 = new List<Vector3>(2048);
			List<Vector2> list5 = new List<Vector2>(2048);
			List<Vector3> list6 = new List<Vector3>(2048);
			List<int> list7 = new List<int>(4096);
			bool flag = false;
			List<int> list8 = new List<int>(8);
			using (StringReader stringReader = new StringReader(objText))
			{
				string text;
				while ((text = stringReader.ReadLine()) != null)
				{
					if (text.Length < 2)
					{
						continue;
					}
					char c = text[0];
					if (c == '#')
					{
						continue;
					}
					if (c == 'v' && text[1] == ' ')
					{
						ParseVector3(text, 2, out var x, out var y, out var z);
						list.Add(new Vector3(0f - x, y, z));
					}
					else if (c == 'v' && text[1] == 't')
					{
						ParseVector2(text, 3, out var x2, out var y2);
						list2.Add(new Vector2(x2, y2));
					}
					else if (c == 'v' && text[1] == 'n')
					{
						ParseVector3(text, 3, out var x3, out var y3, out var z2);
						list3.Add(new Vector3(0f - x3, y3, z2));
						flag = true;
					}
					else if (c == 'f' && text[1] == ' ')
					{
						list8.Clear();
						ParseFace(text, list.Count, list2.Count, list3.Count, lookup, list, list2, list3, list4, list5, list6, list8);
						for (int i = 1; i + 1 < list8.Count; i++)
						{
							list7.Add(list8[0]);
							list7.Add(list8[i + 1]);
							list7.Add(list8[i]);
						}
					}
				}
			}
			if (list4.Count == 0 || list7.Count == 0)
			{
				throw new InvalidDataException("OBJ contained no drawable geometry");
			}
			if (recentreOnBounds)
			{
				Vector3 val = list4[0];
				Vector3 val2 = list4[0];
				for (int j = 1; j < list4.Count; j++)
				{
					val = Vector3.Min(val, list4[j]);
					val2 = Vector3.Max(val2, list4[j]);
				}
				Vector3 val3 = (val + val2) * 0.5f;
				for (int k = 0; k < list4.Count; k++)
				{
					List<Vector3> list9 = list4;
					int index = k;
					list9[index] -= val3;
				}
			}
			Mesh val4 = new Mesh
			{
				name = meshName,
				hideFlags = (HideFlags)61
			};
			val4.indexFormat = (IndexFormat)1;
			val4.SetVertices(ToIl2CppList(list4));
			if (list5.Count == list4.Count)
			{
				val4.SetUVs(0, ToIl2CppList(list5));
			}
			if (flag && list6.Count == list4.Count)
			{
				val4.SetNormals(ToIl2CppList(list6));
			}
			val4.SetTriangles(ToIl2CppList(list7), 0);
			if (!flag)
			{
				val4.RecalculateNormals();
			}
			val4.RecalculateBounds();
			val4.RecalculateTangents();
			val4.UploadMeshData(false);
			return new LoadedModel
			{
				Mesh = val4,
				LocalBounds = val4.bounds,
				TriangleCount = list7.Count / 3,
				VertexCount = list4.Count
			};
		}

		private static List<T> ToIl2CppList<T>(List<T> source)
		{
			List<T> val = new List<T>(source.Count);
			for (int i = 0; i < source.Count; i++)
			{
				val.Add(source[i]);
			}
			return val;
		}

		private static void ParseFace(string line, int positionCount, int uvCount, int normalCount, Dictionary<long, int> lookup, List<Vector3> positions, List<Vector2> uvs, List<Vector3> normals, List<Vector3> outPositions, List<Vector2> outUvs, List<Vector3> outNormals, List<int> faceIndices)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			int i = 2;
			while (i < line.Length)
			{
				for (; i < line.Length && line[i] == ' '; i++)
				{
				}
				if (i >= line.Length)
				{
					break;
				}
				int num = i;
				for (; i < line.Length && line[i] != ' '; i++)
				{
				}
				int num2 = i - num;
				if (num2 <= 0)
				{
					continue;
				}
				ParseFaceVertex(line, num, num2, positionCount, uvCount, normalCount, out var positionIndex, out var uvIndex, out var normalIndex);
				if (positionIndex >= 0 && positionIndex < positions.Count)
				{
					long key = ((long)(positionIndex + 1) << 42) | ((long)(uvIndex + 1) << 21) | (uint)(normalIndex + 1);
					if (!lookup.TryGetValue(key, out var value))
					{
						value = (lookup[key] = outPositions.Count);
						outPositions.Add(positions[positionIndex]);
						outUvs.Add((uvIndex >= 0 && uvIndex < uvs.Count) ? uvs[uvIndex] : Vector2.zero);
						outNormals.Add((normalIndex >= 0 && normalIndex < normals.Count) ? normals[normalIndex] : Vector3.zero);
					}
					faceIndices.Add(value);
				}
			}
		}

		private static void ParseFaceVertex(string line, int start, int length, int positionCount, int uvCount, int normalCount, out int positionIndex, out int uvIndex, out int normalIndex)
		{
			positionIndex = (uvIndex = (normalIndex = -1));
			int num = 0;
			int i = start;
			int num2 = start + length;
			while (i <= num2 && num < 3)
			{
				int num3 = i;
				for (; i < num2 && line[i] != '/'; i++)
				{
				}
				int num4 = i - num3;
				if (num4 > 0 && int.TryParse(line.Substring(num3, num4), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
				{
					int num5 = num switch
					{
						1 => uvCount, 
						0 => positionCount, 
						_ => normalCount, 
					};
					int num6 = ((result > 0) ? (result - 1) : (num5 + result));
					switch (num)
					{
					case 0:
						positionIndex = num6;
						break;
					case 1:
						uvIndex = num6;
						break;
					default:
						normalIndex = num6;
						break;
					}
				}
				i++;
				num++;
			}
		}

		private static void ParseVector3(string line, int offset, out float x, out float y, out float z)
		{
			x = ReadFloat(line, ref offset);
			y = ReadFloat(line, ref offset);
			z = ReadFloat(line, ref offset);
		}

		private static void ParseVector2(string line, int offset, out float x, out float y)
		{
			x = ReadFloat(line, ref offset);
			y = ReadFloat(line, ref offset);
		}

		private static float ReadFloat(string line, ref int offset)
		{
			while (offset < line.Length && (line[offset] == ' ' || line[offset] == '\t'))
			{
				offset++;
			}
			int num = offset;
			while (offset < line.Length && line[offset] != ' ' && line[offset] != '\t')
			{
				offset++;
			}
			if (offset <= num)
			{
				return 0f;
			}
			if (!float.TryParse(line.Substring(num, offset - num), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return 0f;
			}
			return result;
		}

		public static string ReadEmbeddedText(string resourceName)
		{
			byte[] array = ReadEmbeddedBytes(resourceName);
			if (array != null)
			{
				return Encoding.UTF8.GetString(array);
			}
			return null;
		}

		public static byte[] ReadEmbeddedBytes(string resourceName)
		{
			using Stream stream = typeof(ObjMeshLoader).Assembly.GetManifestResourceStream(resourceName);
			if (stream == null)
			{
				ModLog.Error("Embedded resource '" + resourceName + "' is missing from the build.");
				return null;
			}
			byte[] array = new byte[stream.Length];
			int num;
			for (int i = 0; i < array.Length; i += num)
			{
				num = stream.Read(array, i, array.Length - i);
				if (num <= 0)
				{
					break;
				}
			}
			return array;
		}
	}
	public static class PrimitiveMeshes
	{
		private static Mesh _screenQuad;

		public static Mesh ScreenQuad()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_screenQuad != (Object)null)
			{
				return _screenQuad;
			}
			Mesh val = new Mesh
			{
				name = "CinematicCameraScreenQuad",
				hideFlags = (HideFlags)61
			};
			List<Vector3> val2 = new List<Vector3>(4);
			val2.Add(new Vector3(-0.5f, -0.5f, 0f));
			val2.Add(new Vector3(0.5f, -0.5f, 0f));
			val2.Add(new Vector3(0.5f, 0.5f, 0f));
			val2.Add(new Vector3(-0.5f, 0.5f, 0f));
			List<Vector2> val3 = new List<Vector2>(4);
			val3.Add(new Vector2(0f, 0f));
			val3.Add(new Vector2(1f, 0f));
			val3.Add(new Vector2(1f, 1f));
			val3.Add(new Vector2(0f, 1f));
			List<Vector3> val4 = new List<Vector3>(4);
			for (int i = 0; i < 4; i++)
			{
				val4.Add(new Vector3(0f, 0f, -1f));
			}
			List<int> val5 = new List<int>(6);
			val5.Add(0);
			val5.Add(2);
			val5.Add(1);
			val5.Add(0);
			val5.Add(3);
			val5.Add(2);
			val.SetVertices(val2);
			val.SetUVs(0, val3);
			val.SetNormals(val4);
			val.SetTriangles(val5, 0);
			val.RecalculateBounds();
			val.UploadMeshData(false);
			_screenQuad = val;
			return _screenQuad;
		}

		public static void Release()
		{
			if (!((Object)(object)_screenQuad == (Object)null))
			{
				Object.Destroy((Object)(object)_screenQuad);
				_screenQuad = null;
			}
		}
	}
}
namespace BonelabCinematicCamera.UI
{
	public static class BitmapFont
	{
		public const int GlyphWidth = 5;

		public const int GlyphHeight = 7;

		public const int Advance = 6;

		private const char FirstChar = ' ';

		private const char LastChar = '_';

		private static readonly byte[] Glyphs = new byte[320]
		{
			0, 0, 0, 0, 0, 0, 0, 95, 0, 0,
			0, 7, 0, 7, 0, 20, 127, 20, 127, 20,
			36, 42, 127, 42, 18, 35, 19, 8, 100, 98,
			54, 73, 85, 34, 80, 0, 5, 3, 0, 0,
			0, 28, 34, 65, 0, 0, 65, 34, 28, 0,
			20, 8, 62, 8, 20, 8, 8, 62, 8, 8,
			0, 80, 48, 0, 0, 8, 8, 8, 8, 8,
			0, 96, 96, 0, 0, 32, 16, 8, 4, 2,
			62, 81, 73, 69, 62, 0, 66, 127, 64, 0,
			66, 97, 81, 73, 70, 33, 65, 69, 75, 49,
			24, 20, 18, 127, 16, 39, 69, 69, 69, 57,
			60, 74, 73, 73, 48, 1, 113, 9, 5, 3,
			54, 73, 73, 73, 54, 6, 73, 73, 41, 30,
			0, 54, 54, 0, 0, 0, 86, 54, 0, 0,
			8, 20, 34, 65, 0, 20, 20, 20, 20, 20,
			0, 65, 34, 20, 8, 2, 1, 81, 9, 6,
			50, 73, 121, 65, 62, 126, 17, 17, 17, 126,
			127, 73, 73, 73, 54, 62, 65, 65, 65, 34,
			127, 65, 65, 34, 28, 127, 73, 73, 73, 65,
			127, 9, 9, 9, 1, 62, 65, 73, 73, 122,
			127, 8, 8, 8, 127, 0, 65, 127, 65, 0,
			32, 64, 65, 63, 1, 127, 8, 20, 34, 65,
			127, 64, 64, 64, 64, 127, 2, 12, 2, 127,
			127, 4, 8, 16, 127, 62, 65, 65, 65, 62,
			127, 9, 9, 9, 6, 62, 65, 81, 33, 94,
			127, 9, 25, 41, 70, 70, 73, 73, 73, 49,
			1, 1, 127, 1, 1, 63, 64, 64, 64, 63,
			31, 32, 64, 32, 31, 63, 64, 56, 64, 63,
			99, 20, 8, 20, 99, 7, 8, 112, 8, 7,
			97, 81, 73, 69, 67, 0, 127, 65, 65, 0,
			2, 4, 8, 16, 32, 0, 65, 65, 127, 0,
			4, 2, 1, 2, 4, 64, 64, 64, 64, 64
		};

		public static byte Column(char c, int column)
		{
			if (column < 0 || column >= 5)
			{
				return 0;
			}
			if (c >= 'a' && c <= 'z')
			{
				c = (char)(c - 32);
			}
			if (c < ' ' || c > '_')
			{
				c = '?';
			}
			int num = (c - 32) * 5 + column;
			if (num < 0 || num >= Glyphs.Length)
			{
				return 0;
			}
			return Glyphs[num];
		}

		public static int MeasureWidth(string text, int scale)
		{
			if (string.IsNullOrEmpty(text) || scale <= 0)
			{
				return 0;
			}
			return (text.Length * 6 - 1) * scale;
		}

		public static int LineHeight(int scale)
		{
			return 7 * scale;
		}
	}
	public struct ReadoutModel
	{
		public RecordingState State;

		public bool IsFrozen;

		public bool IsHeld;

		public CameraPreset Preset;

		public AudioMode AudioMode;

		public bool MicrophoneLive;

		public int Width;

		public int Height;

		public int FrameRate;

		public TimeSpan Elapsed;

		public TimeSpan Remaining;

		public int CountdownSeconds;

		public bool StorageWarning;

		public string StorageText;

		public string StatusMessage;

		public string ErrorMessage;

		public float EncoderPressure;

		public long DroppedFrames;

		public bool ShowDebug;

		public bool PreciseTimer;

		public float SaveProgress;
	}
	public sealed class CameraReadout : IDisposable
	{
		private static readonly Color32 Background = new Color32((byte)6, (byte)8, (byte)12, (byte)214);

		private static readonly Color32 Foreground = new Color32((byte)245, (byte)250, byte.MaxValue, byte.MaxValue);

		private static readonly Color32 Dim = new Color32((byte)150, (byte)170, (byte)190, byte.MaxValue);

		private static readonly Color32 Accent = new Color32((byte)0, (byte)215, byte.MaxValue, byte.MaxValue);

		private static readonly Color32 RecordRed = new Color32(byte.MaxValue, (byte)50, (byte)50, byte.MaxValue);

		private static readonly Color32 RecordGlow = new Color32(byte.MaxValue, (byte)120, (byte)120, byte.MaxValue);

		private static readonly Color32 WarnAmber = new Color32(byte.MaxValue, (byte)185, (byte)25, byte.MaxValue);

		private static readonly Color32 FrozenCyan = new Color32((byte)80, (byte)220, byte.MaxValue, byte.MaxValue);

		private static readonly Color32 BracketDim = new Color32((byte)0, (byte)180, (byte)220, (byte)140);

		private readonly HudCanvas _canvas;

		private bool _blinkOn = true;

		private float _blinkTimer;

		private float _animTime;

		public Texture2D Texture => _canvas.Texture;

		public CameraReadout(int width, int height)
		{
			_canvas = new HudCanvas(width, height, "CinematicCameraReadout");
		}

		public void AdvanceBlink(float deltaTime)
		{
			_animTime += deltaTime;
			_blinkTimer += deltaTime;
			if (!(_blinkTimer < 0.5f))
			{
				_blinkTimer = 0f;
				_blinkOn = !_blinkOn;
			}
		}

		public void Draw(in ReadoutModel model)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			_canvas.Clear(Background);
			int width = _canvas.Width;
			int height = _canvas.Height;
			int num = Mathf.Max(6, width / 32);
			int armLength = Mathf.Clamp(width / 14, 10, 26);
			_canvas.DrawFramingCorners(num - 2, num - 2, width - num * 2 + 4, height - num * 2 + 4, armLength, 1, BracketDim);
			if (model.State == RecordingState.Idle || model.State == RecordingState.Recording)
			{
				_canvas.DrawCrosshair(width / 2, height / 2, 6, new Color32((byte)0, (byte)215, byte.MaxValue, (byte)80));
			}
			DrawTopRow(in model, num, num, width);
			int num2 = num + 22;
			_canvas.DrawText(num, num2, PresetLabel(model.Preset), Accent, 2);
			string text = $"{model.Height}P {model.FrameRate}FPS";
			_canvas.DrawTextRight(width - num, num2 + 3, text, Dim);
			int y = num + 46;
			DrawContextRow(in model, num, y, width);
			DrawFooterRow(in model, num, width, height);
			_canvas.Apply();
		}

		private void DrawTopRow(in ReadoutModel model, int margin, int y, int width)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: 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_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			bool flag = model.State == RecordingState.Recording;
			if (model.State == RecordingState.Countdown)
			{
				_canvas.DrawText(margin, y, "COUNTDOWN", WarnAmber, 2);
				int centreX = width - margin - 14;
				int centreY = y + 7;
				float num = 0.5f + 0.5f * Mathf.Sin(_animTime * 12f);
				int radius = (int)(9f + num * 3f);
				_canvas.DrawCircleOutline(centreX, centreY, radius, 1, WarnAmber);
				_canvas.DrawTextRight(width - margin - 6, y, model.CountdownSeconds.ToString(), WarnAmber, 2);
				return;
			}
			int x = margin;
			if (flag)
			{
				int num2 = 4;
				_canvas.DrawCircleOutline(margin + num2 + 1, y + num2 + 3, num2 + 2, 1, RecordGlow);
				if (_blinkOn)
				{
					_canvas.FillCircle(margin + num2 + 1, y + num2 + 3, num2, RecordRed);
				}
				x = margin + 16;
				x = _canvas.DrawText(x, y, "REC", RecordRed, 2);
				_canvas.DrawText(x + 4, y, "[" + PresetLabel(model.Preset) + "]", Accent, 2);
			}
			else
			{
				string text = RecordingStateMachine.ShortLabel(model.State);
				Color32 colour = ((model.State == RecordingState.Failed) ? WarnAmber : Foreground);
				_canvas.DrawText(x, y, text, colour, 2);
			}
			if (flag || model.State == RecordingState.Stopping || model.State == RecordingState.Encoding)
			{
				string text2 = (model.PreciseTimer ? RecordingClock.FormatPrecise(model.Elapsed) : RecordingClock.FormatShort(model.Elapsed));
				_canvas.DrawTextRight(width - margin, y, text2, Foreground, 2);
			}
		}

		private void DrawContextRow(in ReadoutModel model, int margin, int y, int width)
		{
			//IL_00fb: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			if (model.State == RecordingState.Recording)
			{
				int num = 28;
				bool active = model.MicrophoneLive || model.AudioMode != AudioMode.NoAudio;
				_canvas.DrawAudioVisualizer(margin, y, num, 10, 4, _animTime, Accent, active);
				_canvas.DrawText(margin + num + 6, y + 1, AudioLabel(model.AudioMode), model.MicrophoneLive ? WarnAmber : Dim);
				bool flag = model.Remaining <= TimeSpan.FromSeconds(10.0);
				string text = RecordingClock.FormatShort(model.Remaining) + " LEFT";
				_canvas.DrawTextRight(width - margin, y + 1, text, flag ? WarnAmber : Dim);
			}
			else if (model.State == RecordingState.Saving || model.State == RecordingState.Encoding)
			{
				int width2 = width - margin * 2;
				int height = 10;
				_canvas.DrawProgressBar(margin, y, width2, height, model.SaveProgress, Background, Accent, Foreground);
			}
			else
			{
				_canvas.DrawText(margin, y, "[TRIG] RECORD", Dim);
				string text2 = (model.IsFrozen ? "[A] UNFREEZE" : "[A] FREEZE");
				_canvas.DrawText(margin + 92, y, text2, model.IsFrozen ? FrozenCyan : Dim);
				_canvas.DrawTextRight(width - margin, y, "[B] PRESET", Dim);
			}
		}

		private void DrawFooterRow(in ReadoutModel model, int margin, int width, int height)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: 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)
			int y = height - margin - 7;
			if (!string.IsNullOrEmpty(model.ErrorMessage))
			{
				_canvas.DrawText(margin, y, Trim(model.ErrorMessage, AvailableChars(width, margin, 1)), WarnAmber);
				return;
			}
			if (!string.IsNullOrEmpty(model.StatusMessage))
			{
				_canvas.DrawText(margin, y, Trim(model.StatusMessage, AvailableChars(width, margin, 1)), Accent);
				return;
			}
			if (model.IsFrozen)
			{
				_canvas.DrawText(margin, y, "FROZEN IN PLACE", FrozenCyan);
			}
			else if (model.IsHeld)
			{
				_canvas.DrawText(margin, y, "HELD IN HAND", Dim);
			}
			if (model.StorageWarning)
			{
				_canvas.DrawTextRight(width - margin, y, "LOW " + (model.StorageText ?? "STORAGE"), WarnAmber);
			}
			else if (model.ShowDebug)
			{
				_canvas.DrawTextRight(width - margin, y, $"Q{Mathf.RoundToInt(model.EncoderPressure * 100f)}% D{model.DroppedFrames}", Dim);
			}
		}

		private static int AvailableChars(int width, int margin, int scale)
		{
			int num = width - margin * 2;
			return Mathf.Max(4, num / (6 * scale));
		}

		private static string Trim(string value, int maxChars)
		{
			if (string.IsNullOrEmpty(value))
			{
				return string.Empty;
			}
			if (value.Length > maxChars)
			{
				return value.Substring(0, maxChars);
			}
			return value;
		}

		private static string PresetLabel(CameraPreset preset)
		{
			return PresetCycle.DisplayName(preset);
		}

		private static string AudioLabel(AudioMode mode)
		{
			return mode switch
			{
				AudioMode.NoAudio => "SILENT", 
				AudioMode.GameAudio => "GAME", 
				AudioMode.Microphone => "MIC", 
				AudioMode.GameAudioAndMicrophone => "MIC+GAME", 
				_ => "AUDIO", 
			};
		}

		public void Dispose()
		{
			_canvas?.Dispose();
		}
	}
	public sealed class HudCanvas : IDisposable
	{
		private readonly Color32[] _pixels;

		private Texture2D _texture;

		private bool _dirty;

		private bool _disposed;

		public int Width { get; }

		public int Height { get; }

		public Texture2D Texture => _texture;

		public HudCanvas(int width, int height, string name)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			Width = Mathf.Clamp(width, 32, 1024);
			Height = Mathf.Clamp(height, 16, 1024);
			_pixels = (Color32[])(object)new Color32[Width * Height];
			_texture = new Texture2D(Width, Height, (TextureFormat)4, false)
			{
				name = name,
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)1,
				hideFlags = (HideFlags)61
			};
			Clear(new Color32((byte)0, (byte)0, (byte)0, (byte)0));
			Apply();
		}

		public void Clear(Color32 colour)
		{
			//IL_000b: 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)
			for (int i = 0; i < _pixels.Length; i++)
			{
				_pixels[i] = colour;
			}
			_dirty = true;
		}

		public void Apply()
		{
			if (_disposed || !_dirty || (Object)(object)_texture == (Object)null)
			{
				return;
			}
			try
			{
				_texture.SetPixels32(Il2CppStructArray<Color32>.op_Implicit(_pixels));
				_texture.Apply(false, false);
				_dirty = false;
			}
			catch (Exception ex)
			{
				ModLog.Warn("HUD texture upload failed: " + ModLog.Describe(ex));
			}
		}

		public void SetPixel(int x, int y, Color32 colour)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (x >= 0 && y >= 0 && x < Width && y < Height)
			{
				_pixels[(Height - 1 - y) * Width + x] = colour;
				_dirty = true;
			}
		}

		public void FillRect(int x, int y, int width, int height, Color32 colour)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.Max(0, x);
			int num2 = Mathf.Max(0, y);
			int num3 = Mathf.Min(Width, x + width);
			int num4 = Mathf.Min(Height, y + height);
			if (num3 <= num || num4 <= num2)
			{
				return;
			}
			for (int i = num2; i < num4; i++)
			{
				int num5 = (Height - 1 - i) * Width;
				for (int j = num; j < num3; j++)
				{
					_pixels[num5 + j] = colour;
				}
			}
			_dirty = true;
		}

		public void DrawRectOutline(int x, int y, int width, int height, int thickness, Color32 colour)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (width > 0 && height > 0 && thickness > 0)
			{
				FillRect(x, y, width, thickness, colour);
				FillRect(x, y + height - thickness, width, thickness, colour);
				FillRect(x, y, thickness, height, colour);
				FillRect(x + width - thickness, y, thickness, height, colour);
			}
		}

		public void FillCircle(int centreX, int centreY, int radius, Color32 colour)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (radius <= 0)
			{
				return;
			}
			int num = radius * radius;
			for (int i = -radius; i <= radius; i++)
			{
				int num2 = centreY + i;
				if (num2 >= 0 && num2 < Height)
				{
					int num3 = (int)Mathf.Sqrt((float)Mathf.Max(0, num - i * i));
					for (int j = -num3; j <= num3; j++)
					{
						SetPixel(centreX + j, num2, colour);
					}
				}
			}
		}

		public void DrawCircleOutline(int centreX, int centreY, int radius, int thickness, Color32 colour)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (radius <= 0 || thickness <= 0)
			{
				return;
			}
			int num = radius * radius;
			int num2 = Mathf.Max(0, radius - thickness);
			int num3 = num2 * num2;
			for (int i = -radius; i <= radius; i++)
			{
				int num4 = centreY + i;
				if (num4 < 0 || num4 >= Height)
				{
					continue;
				}
				int num5 = i * i;
				int num6 = (int)Mathf.Sqrt((float)Mathf.Max(0, num - num5));
				int num7 = ((num5 < num3) ? ((int)Mathf.Sqrt((float)(num3 - num5))) : (-1));
				for (int j = -num6; j <= num6; j++)
				{
					if (num7 < 0 || j <= -num7 || j >= num7)
					{
						SetPixel(centreX + j, num4, colour);
					}
				}
			}
		}

		public void DrawLine(int x0, int y0, int x1, int y1, Color32 colour, int thickness = 1)
		{
			//IL_004d: 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)
			int num = Math.Abs(x1 - x0);
			int num2 = Math.Abs(y1 - y0);
			int num3 = ((x0 < x1) ? 1 : (-1));
			int num4 = ((y0 < y1) ? 1 : (-1));
			int num5 = num - num2;
			while (true)
			{
				if (thickness <= 1)
				{
					SetPixel(x0, y0, colour);
				}
				else
				{
					FillRect(x0 - thickness / 2, y0 - thickness / 2, thickness, thickness, colour);
				}
				if (x0 != x1 || y0 != y1)
				{
					int num6 = 2 * num5;
					if (num6 > -num2)
					{
						num5 -= num2;
						x0 += num3;
					}
					if (num6 < num)
					{
						num5 += num;
						y0 += num4;
					}
					continue;
				}
				break;
			}
		}

		public void DrawFramingCorners(int x, int y, int width, int height, int armLength, int thickness, Color32 colour)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			if (width > 0 && height > 0 && armLength > 0)
			{
				int num = Math.Min(armLength, width / 3);
				int num2 = Math.Min(armLength, height / 3);
				FillRect(x, y, num, thickness, colour);
				FillRect(x, y, thickness, num2, colour);
				FillRect(x + width - num, y, num, thickness, colour);
				FillRect(x + width - thickness, y, thickness, num2, colour);
				FillRect(x, y + height - thickness, num, thickness, colour);
				FillRect(x, y + height - num2, thickness, num2, colour);
				FillRect(x + width - num, y + height - thickness, num, thickness, colour);
				FillRect(x + width - thickness, y + height - num2, thickness, num2, colour);
			}
		}

		public void DrawCrosshair(int centreX, int centreY, int size, Color32 colour)
		{
			//IL_000e: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (size > 0)
			{
				DrawLine(centreX - size, centreY, centreX - 3, centreY, colour);
				DrawLine(centreX + 3, centreY, centreX + size, centreY, colour);
				DrawLine(centreX, centreY - size, centreX, centreY - 3, colour);
				DrawLine(centreX, centreY + 3, centreX, centreY + size, colour);
				SetPixel(centreX, centreY, colour);
			}
		}

		public void DrawAudioVisualizer(int x, int y, int width, int height, int barCount, float animTime, Color32 colour, bool active)
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if (width <= 0 || height <= 0 || barCount <= 0)
			{
				return;
			}
			int num = Math.Max(2, width / barCount - 2);
			for (int i = 0; i < barCount; i++)
			{
				float num2 = 0.15f;
				if (active)
				{
					float num3 = Mathf.Sin(animTime * 10f + (float)i * 1.7f);
					float num4 = Mathf.Cos(animTime * 6f - (float)i * 0.9f);
					float num5 = Mathf.Sin(animTime * 14f + (float)i * 2.3f);
					num2 = Mathf.Clamp01(0.25f + (Mathf.Abs(num3 * 0.45f) + Mathf.Abs(num4 * 0.35f) + Mathf.Abs(num5 * 0.2f)) * 0.5f);
				}
				int num6 = Mathf.Clamp(Mathf.RoundToInt((float)height * num2), 2, height);
				int x2 = x + i * (num + 2);
				int y2 = y + height - num6;
				Color32 colour2 = colour;
				if (active && num2 > 0.8f)
				{
					((Color32)(ref colour2))..ctor(byte.MaxValue, (byte)100, (byte)100, colour.a);
				}
				else if (active && num2 > 0.55f)
				{
					((Color32)(ref colour2))..ctor(byte.MaxValue, (byte)200, (byte)50, colour.a);
				}
				FillRect(x2, y2, num, num6, colour2);
			}
		}

		public void DrawProgressBar(int x, int y, int width, int height, float progress, Color32 bg, Color32 fill, Color32 glow)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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)
			if (width > 0 && height > 0)
			{
				FillRect(x, y, width, height, bg);
				DrawRectOutline(x, y, width, height, 1, new Color32(bg.r, bg.g, bg.b, byte.MaxValue));
				float num = Mathf.Clamp01(progress);
				int num2 = Mathf.Max(0, (int)((float)width * num));
				if (num2 > 0)
				{
					FillRect(x + 1, y + 1, num2 - 2, height - 2, fill);
					int x2 = Mathf.Clamp(x + num2 - 2, x, x + width - 3);
					FillRect(x2, y, 3, height, glow);
				}
			}
		}

		public int DrawText(int x, int y, string text, Color32 colour, int scale = 1)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(text) || scale <= 0)
			{
				return x;
			}
			int num = x;
			foreach (char c in text)
			{
				if (c == '\n')
				{
					break;
				}
				for (int j = 0; j < 5; j++)
				{
					byte b = BitmapFont.Column(c, j);
					if (b == 0)
					{
						continue;
					}
					for (int k = 0; k < 7; k++)
					{
						if ((b & (1 << k)) != 0)
						{
							if (scale == 1)
							{
								SetPixel(num + j, y + k, colour);
							}
							else
							{
								FillRect(num + j * scale, y + k * scale, scale, scale, colour);
							}
						}
					}
				}
				num += 6 * scale;
			}
			return num;
		}

		public void DrawTextRight(int rightEdge, int y, string text, Color32 colour, int scale = 1)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			int num = BitmapFont.MeasureWidth(text, scale);
			DrawText(rightEdge - num, y, text, colour, scale);
		}

		public void Dispose()
		{
			if (!_disposed)
			{
				_disposed = true;
				if ((Object)(object)_texture != (Object)null)
				{
					Object.Destroy((Object)(object)_texture);
					_texture = null;
				}
			}
		}
	}
	public sealed class RecordingHudOverlay : IDisposable
	{
		private const int CanvasWidth = 440;

		private const int CanvasHeight = 64;

		private const float WorldWidth = 0.28f;

		private const float CameraSweepInterval = 1f;

		private static readonly Color32 RecRed = new Color32(byte.MaxValue, (byte)35, (byte)35, byte.MaxValue);

		private static readonly Color32 RecGlow = new Color32(byte.MaxValue, (byte)110, (byte)110, (byte)240);

		private static readonly Color32 RecWhite = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		private static readonly Color32 RecCyan = new Color32((byte)0, (byte)240, byte.MaxValue, byte.MaxValue);

		private static readonly Color32 StbyAmber = new Color32(byte.MaxValue, (byte)190, (byte)25, byte.MaxValue);

		private static readonly Color32 StbyGold = new Color32(byte.MaxValue, (byte)215, (byte)55, byte.MaxValue);

		private static readonly Color32 StbyGreen = new Color32((byte)50, byte.MaxValue, (byte)175, byte.MaxValue);

		private static readonly Color32 StbyClock = new Color32((byte)245, (byte)220, (byte)160, byte.MaxValue);

		private static readonly Color32 CountOrange = new Color32(byte.MaxValue, (byte)130, (byte)20, byte.MaxValue);

		private static readonly Color32 CountGlow = new Color32(byte.MaxValue, (byte)175, (byte)70, (byte)240);

		private static readonly Color32 ShadowBlack = new Color32((byte)0, (byte)0, (byte)0, (byte)220);

		private readonly PlayerReference _player;

		private readonly CameraAssets _assets;

		private readonly ModSettings _settings;

		private HudCanvas _canvas;

		private DisplaySurface _surface;

		private bool _disposed;

		private float _cameraSweepTimer = -1f;

		private bool _loggedCameraSweep;

		private Camera _playerCamera;

		private bool _visible;

		private bool _lastBlink;

		private int _lastSecond = -1;

		private string _lastMode;

		private CameraPreset _lastPreset;

		private float _lastHeightOffset = float.NaN;

		public RecordingHudOverlay(PlayerReference player, CameraAssets assets, ModSettings settings = null)
		{
			_player = player ?? throw new ArgumentNullException("player");
			_assets = assets ?? throw new ArgumentNullException("assets");
			_settings = settings;
		}

		public void Tick(float deltaTime, bool shouldShow, bool recording, bool standby, TimeSpan elapsed, CameraPreset preset)
		{
			if (_disposed)
			{
				return;
			}
			_cameraSweepTimer -= deltaTime;
			if (_cameraSweepTimer <= 0f)
			{
				_cameraSweepTimer = 1f;
				EnsurePlayerCamerasRenderBadge();
			}
			if (!shouldShow)
			{
				if (_visible)
				{
					SetVisible(visible: false);
				}
				return;
			}
			EnsureSurface();
			if (_surface != null && !((Object)(object)_surface.GameObject == (Object)null))
			{
				float heightOffset = ((_settings != null) ? _settings.HudVerticalOffset : 0.14f);
				PlaceBadge(heightOffset);
				bool flag = recording && Time.time % 1.2f < 0.72f;
				int num = (recording ? ((int)elapsed.TotalSeconds) : (-1));
				string text = (recording ? "REC" : (standby ? "COUNTDOWN" : "STAND-BY"));
				if (!_visible || flag != _lastBlink || num != _lastSecond || !string.Equals(text, _lastMode, StringComparison.Ordinal) || preset != _lastPreset)
				{
					Draw(text, flag, recording, standby, elapsed, preset);
					_lastBlink = flag;
					_lastSecond = num;
					_lastMode = text;
					_lastPreset = preset;
				}
				if (!_visible)
				{
					SetVisible(visible: true);
				}
			}
		}

		public void Tick(float deltaTime, bool recording, bool standby, TimeSpan elapsed, CameraPreset preset)
		{
			Tick(deltaTime, recording || standby, recording, standby, elapsed, preset);
		}

		public void Tick(float deltaTime, bool recording, bool standby, TimeSpan elapsed)
		{
			Tick(deltaTime, recording || standby, recording, standby, elapsed, CameraPreset.FreeCamera);
		}

		private void PlaceBadge(float heightOffset)
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = _surface.Transform;
			if ((Object)(object)transform == (Object)null)
			{
				return;
			}
			int num = ModLayers.HudLayer();
			if ((Object)(object)_surface.GameObject != (Object)null && _surface.GameObject.layer != num)
			{
				_surface.GameObject.layer = num;
			}
			Camera playerCamera = _playerCamera;
			if ((Object)(object)playerCamera != (Object)null && (Object)(object)((Component)playerCamera).transform != (Object)null)
			{
				if ((Object)(object)transform.parent != (Object)(object)((Component)playerCamera).transform)
				{
					transform.SetParent(((Component)playerCamera).transform, false);
				}
				transform.localPosition = new Vector3(0f, heightOffset, 0.42f);
				transform.localRotation = Quaternion.identity;
				return;
			}
			if ((Object)(object)transform.parent != (Object)null)
			{
				transform.SetParent((Transform)null, false);
			}
			Quaternion headRotation = _player.HeadRotation;
			transform.position = _player.HeadPosition + headRotation * new Vector3(0f, heightOffset, 0.42f);
			transform.rotation = headRotation;
		}

		private void EnsureSurface()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			if (_surface == null || !((Object)(object)_surface.GameObject != (Object)null))
			{
				if (_canvas == null)
				{
					_canvas = new HudCanvas(440, 64, "RecordingHudCanvas");
				}
				float num = 0.040727273f;
				_surface = new DisplaySurface(null, "RecordingHud", Vector3.zero, Quaternion.identity, new Vector2(0.28f, num), _assets.CreateOverlayMaterial("RecordingHudMat"));
				_surface.SetTexture((Texture)(object)_canvas.Texture);
				if ((Object)(object)_surface.GameObject != (Object)null)
				{
					_surface.GameObject.layer = ModLayers.HudLayer();
					ModLog.Info($"Recording badge placed on layer {ModLayers.HudLayer()}; " + "lenses exclude it from every clip and photo.");
				}
				SetVisible(visible: false);
				EnsurePlayerCamerasRenderBadge();
			}
		}

		private void EnsurePlayerCamerasRenderBadge()
		{
			int hudBit = ModLayers.HudBit;
			bool flag = false;
			Camera val = null;
			try
			{
				Camera[] array = Il2CppArrayBase<Camera>.op_Implicit((Il2CppArrayBase<Camera>)(object)Camera.allCameras);
				foreach (Camera camera in array)
				{
					if ((Object)(object)camera == (Object)null || LensRig.BelongsToMod(camera) || (Object)(object)camera.targetTexture != (Object)null)
					{
						continue;
					}
					if ((Object)(object)val == (Object)null || camera.depth > val.depth)
					{
						val = camera;
					}
					try
					{
						if ((camera.cullingMask & hudBit) == 0)
						{
							Camera obj = camera;
							obj.cullingMask |= hudBit;
							flag = true;
							ModLog.Info("Recording badge layer added to camera '" + ((Object)camera).name + "'.");
						}
					}
					catch (Exception ex)
					{
						Exception ex2 = ex;
						ModLog.Debug(() => "Could not patch camera '" + ((Object)camera).name + "': " + ModLog.Describe(ex2));
					}
				}
			}
			catch (Exception ex3)
			{
				Exception ex4 = ex3;
				Exception ex5 = ex4;
				ModLog.Debug(() => "Camera sweep failed: " + ModLog.Describe(ex5));
			}
			if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)_playerCamera)
			{
				_playerCamera = val;
				ModLog.Info("Recording badge now rides the player's view camera '" + ((Object)val).name + "'.");
			}
			else if ((Object)(object)val == (Object)null)
			{
				_playerCamera = null;
			}
			if (flag && !_loggedCameraSweep)
			{
				_loggedCameraSweep = true;
				ModLog.Info("The operator's view now renders the recording badge layer.");
			}
		}

		private int DrawTextWithShadow(int x, int y, string text, Color32 colour, int scale = 2)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			_canvas.DrawText(x + 1, y + 1, text, ShadowBlack, scale);
			return _canvas.DrawText(x, y, text, colour, scale);
		}

		private void DrawTextRightWithShadow(int rightEdge, int y, string text, Color32 colour, int scale = 2)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			_canvas.DrawTextRight(rightEdge + 1, y + 1, text, ShadowBlack, scale);
			_canvas.DrawTextRight(rightEdge, y, text, colour, scale);
		}

		private void Draw(string mode, bool blink, bool recording, bool standby, TimeSpan elapsed, CameraPreset preset)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: 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_0144: Unknown result type (might be due to invalid IL or missing references)
			_canvas.Clear(new Color32((byte)0, (byte)0, (byte)0, (byte)0));
			int num = 32;
			int num2 = 22;
			int y = num - 7;
			string text = "[" + PresetCycle.DisplayName(preset).ToUpperInvariant() + "]";
			if (recording)
			{
				_canvas.DrawCircleOutline(num2 + 1, num + 1, 9, 2, ShadowBlack);
				_canvas.DrawCircleOutline(num2, num, 9, 2, RecGlow);
				if (blink)
				{
					_canvas.FillCircle(num2 + 1, num + 1, 6, ShadowBlack);
					_canvas.FillCircle(num2, num, 6, RecRed);
				}
				int x = num2 + 18;
				x = DrawTextWithShadow(x, y, "REC", RecRed);
				DrawTextWithShadow(x + 8, y, text, RecCyan);
				string text2 = FormatElapsed(elapsed);
				DrawTextRightWithShadow(430, y, text2, RecWhite);
			}
			else if (standby)
			{
				_canvas.DrawCircleOutline(num2 + 1, num + 1, 9, 2, ShadowBlack);
				_canvas.DrawCircleOutline(num2, num, 9, 2, CountGlow);
				if (blink)
				{
					_canvas.FillCircle(num2 + 1, num + 1, 6, ShadowBlack);
					_canvas.FillCircle(num2, num, 6, CountOrange);
				}
				int x2 = num2 + 18;
				x2 = DrawTextWithShadow(x2, y, "COUNTDOWN", CountOrange);
				DrawTextWithShadow(x2 + 8, y, text, RecCyan);
			}
			else
			{
				_canvas.DrawCircleOutline(num2 + 1, num + 1, 8, 2, ShadowBlack);
				_canvas.DrawCircleOutline(num2, num, 8, 2, StbyAmber);
				_canvas.FillCircle(num2 + 1, num + 1, 5, ShadowBlack);
				_canvas.FillCircle(num2, num, 5, StbyGold);
				int x3 = num2 + 18;
				x3 = DrawTextWithShadow(x3, y, "STAND-BY", StbyGold);
				DrawTextWithShadow(x3 + 8, y, text, StbyGreen);
				DrawTextRightWithShadow(430, y, "0:00", StbyClock);
			}
			_canvas.Apply();
			_surface?.SetTexture((Texture)(object)_canvas.Texture);
		}

		private static string FormatElapsed(TimeSpan elapsed)
		{
			int num = (int)elapsed.TotalSeconds;
			int value = num / 60;
			int value2 = num % 60;
			return $"{value:0}:{value2:00}";
		}

		private void SetVisible(bool visible)
		{
			_visible = visible;
			if (_surface != null)
			{
				_surface.Visible = visible;
			}
		}

		public void Dispose()
		{
			if (!_disposed)
			{
				_disposed = true;
				_surface?.Dispose();
				_surface = null;
				_canvas?.Dispose();
				_canvas = null;
			}
		}
	}
	public static class RecordingIndicatorPolicy
	{
		public static bool ShouldShow(RecordingIndicatorMode mode, bool recording, bool standby, bool cameraHidden)
		{
			if (!recording && !standby)
			{
				return false;
			}
			if (mode == RecordingIndicatorMode.Off)
			{
				return false;
			}
			if (cameraHidden)
			{
				return true;
			}
			return mode switch
			{
				RecordingIndicatorMode.HiddenCamerasOnly => false, 
				RecordingIndicatorMode.WhileRecording => recording, 
				_ => true, 
			};
		}

		public static bool IsCameraHidden(bool hasCamera, CameraPreset preset, bool isHeld, bool modelSuppressed)
		{
			if (!hasCamera)
			{
				return true;
			}
			if (isHeld)
			{
				return false;
			}
			if (!modelSuppressed)
			{
				return CameraVisibilityPolicy.IsBodyMounted(preset);
			}
			return true;
		}
	}
}
namespace BonelabCinematicCamera.Rendering
{
	public sealed class DisplaySurface : IDisposable
	{
		private readonly GameObject _owner;

		private readonly MeshRenderer _renderer;

		private Material _material;

		private bool _disposed;

		public GameObject GameObject => _owner;

		public Transform Transform
		{
			get
			{
				if (!((Object)(object)_owner != (Object)null))
				{
					return null;
				}
				return _owner.transform;
			}
		}

		public bool Visible
		{
			get
			{
				if ((Object)(object)_renderer != (Object)null)
				{
					return ((Renderer)_renderer).enabled;
				}
				return false;
			}
			set
			{
				if ((Object)(object)_renderer != (Object)null)
				{
					((Renderer)_renderer).enabled = value;
				}
			}
		}

		public DisplaySurface(Transform parent, string name, Vector3 localPosition, Quaternion localRotation, Vector2 size, Material material)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			_owner = new GameObject(name);
			_owner.transform.SetParent(parent, false);
			_owner.transform.localPosition = localPosition;
			_owner.transform.localRotation = localRotation;
			_owner.transform.localScale = new Vector3(size.x, size.y, 1f);
			_owner.layer = (((Object)(object)parent != (Object)null) ? ((Component)parent).gameObject.layer : 0);
			_owner.AddComponent<MeshFilter>().sharedMesh = PrimitiveMeshes.ScreenQuad();
			_renderer = _owner.AddComponent<MeshRenderer>();
			_material = material;
			((Renderer)_renderer).sharedMaterial = _material;
			((Renderer)_renderer).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)_renderer).receiveShadows = false;
			((Renderer)_renderer).lightProbeUsage = (LightProbeUsage)0;
			((Renderer)_renderer).reflectionProbeUsage = (ReflectionProbeUsage)0;
			((Renderer)_renderer).motionVectorGenerationMode = (MotionVectorGenerationMode)2;
			((Renderer)_renderer).allowOcclusionWhenDynamic = false;
		}

		public void SetTexture(Texture texture, bool mirrored = false)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_material == (Object)null))
			{
				ShaderLibrary.SetMainTexture(_material, texture);
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(mirrored ? (-1f) : 1f, 1f);
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor(mirrored ? 1f : 0f, 0f);
				if (_material.HasProperty(ShaderLibrary.BaseMapId))
				{
					_material.SetTextureScale(ShaderLibrary.BaseMapId, val);
					_material.SetTextureOffset(ShaderLibrary.BaseMapId, val2);
				}
				if (_material.HasProperty(ShaderLibrary.MainTexId))
				{
					_material.SetTextureScale(ShaderLibrary.MainTexId, val);
					_material.SetTextureOffset(ShaderLibrary.MainTexId, val2);
				}
			}
		}

		public void SetTint(Color colour)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_material == (Object)null))
			{
				ShaderLibrary.SetColor(_material, colour);
			}
		}

		public void SetLocalScale(Vector2 size)
		{
			//IL_001a: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_owner == (Object)null))
			{
				_owner.transform.localScale = new Vector3(size.x, size.y, 1f);
			}
		}

		public void Dispose()
		{
			if (_disposed)
			{
				return;
			}
			_disposed = true;
			if ((Object)(object)_material != (Object)null)
			{
				try
				{
					Object.Destroy((Object)(object)_material);
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception ex3 = ex2;
					ModLog.Debug(() => "Material destroy failed: " + ModLog.Describe(ex3));
				}
				_material = null;
			}
			if (!((Object)(object)_owner != (Object)null))
			{
				return;
			}
			try
			{
				Object.Destroy((Object)(object)_owner);
			}
			catch (Exception ex4)
			{
				Exception ex2 = ex4;
				Exception ex5 = ex2;
				ModLog.Debug(() => "Display destroy failed: " + ModLog.Describe(ex5));
			}
		}
	}
	public static class FisheyeMapping
	{
		public const float MinimumStrength = 0.01f;

		public const float MaximumStrength = 2f;

		public const float MaximumRenderedFieldOfView = 150f;

		public static bool IsActive(float strength)
		{
			return strength >= 0.01f;
		}

		public static float ClampStrength(float strength)
		{
			if (!(strength < 0f))
			{
				if (!(strength > 2f))
				{
					return strength;
				}
				return 2f;
			}
			return 0f;
		}

		public static float RenderedFieldOfView(float requestedFieldOfView, float strength)
		{
			if (!IsActive(strength) || requestedFieldOfView >= 150f)
			{
				return requestedFieldOfView;
			}
			float num = ClampStrength(strength) / 2f;
			return requestedFieldOfView + (150f - requestedFieldOfView) * num;
		}

		public static void SourceFor(double outputX, double outputY, double aspect, double verticalFieldOfView, double strength, out double sourceX, out double sourceY)
		{
			if (aspect <= 0.0)
			{
				aspect = 1.0;
			}
			double num = (outputX - 0.5) * 2.0 * aspect;
			double num2 = (outputY - 0.5) * 2.0;
			double num3 = RadialScale(Math.Sqrt(num * num + num2 * num2), aspect, verticalFieldOfView, strength);
			sourceX = num * num3 / (2.0 * aspect) + 0.5;
			sourceY = num2 * num3 / 2.0 + 0.5;
		}

		public static double RadialScale(double radius, double aspect, double verticalFieldOfView, double strength)
		{
			double num = Clamp01((float)strength);
			if (num <= 0.0 || radius <= 1E-09)
			{
				if (!(num <= 0.0))
				{
					return CentreScale(aspect, verticalFieldOfView, num);
				}
				return 1.0;
			}
			double num2 = Math.Tan(DegreesToRadians(Clamp(verticalFieldOfView, 1.0, 179.0)) * 0.5);
			double num3 = Math.Sqrt(aspect * aspect + 1.0);
			double num4 = Math.Atan(num3 * num2);
			double num5 = Math.Tan(Math.Min(radius, num3) / num3 * num4) / num2;
			return (radius + (num5 - radius) * num) / radius;
		}

		private static double CentreScale(double aspect, double verticalFieldOfView, double s)
		{
			double num = Math.Tan(DegreesToRadians(Clamp(verticalFieldOfView, 1.0, 179.0)) * 0.5);
			double num2 = Math.Sqrt(aspect * aspect + 1.0);
			double num3 = Math.Atan(num2 * num) / (num2 * num);
			return 1.0 + (num3 - 1.0) * s;
		}

		private static double DegreesToRadians(double degrees)
		{
			return degrees * Math.PI / 180.0;
		}

		private static double Clamp(double value, double min, double max)
		{
			if (!(value < min))
			{
				if (!(value > max))
				{
					return value;
				}
				return max;
			}
			return min;
		}

		private static float Clamp01(float value)
		{
			if (!(value < 0f))
			{
				if (!(value > 1f))
				{
					return value;
				}
				return 1f;
			}
			return 0f;
		}
	}
	public sealed class FisheyeStage : IDisposable
	{
		private const int Columns = 40;

		private const int Rows = 24;

		private const float FieldOfViewTolerance = 0.5f;

		private static readonly int CullId = Shader.PropertyToID("_Cull");

		private static readonly string[] FogKeywords = new string[3] { "FOG_LINEAR", "FOG_EXP", "FOG_EXP2" };

		private readonly bool[] _fogWasOn = new bool[3];

		private readonly Mesh _mesh;

		private readonly Material _material;

		private readonly Il2CppStructArray<Vector2> _uvs;

		private float _builtFieldOfView = -1f;

		private float _builtAspect = -1f;

		private float _builtStrength = -1f;

		private bool _disposed;

		private bool _drawFailureLogged;

		private bool _markedFirstDraw;

		public FisheyeStage(string name, Material material)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			_material = material;
			Breadcrumbs.Mark("fisheye: building stage " + name);
			if ((Object)(object)_material != (Object)null && _material.HasProperty(CullId))
			{
				_material.SetFloat(CullId, 0f);
			}
			_mesh = new Mesh
			{
				name = name + "_Grid",
				hideFlags = (HideFlags)61
			};
			_mesh.MarkDynamic();
			int num = 1025;
			_uvs = new Il2CppStructArray<Vector2>((long)num);
			BuildGrid(num);
		}

		public bool Draw(Texture source, RenderTexture destination, float fieldOfView, float strength)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			if (_disposed || (Object)(object)_material == (Object)null || (Object)(object)source == (Object)null || (Object)(object)destination == (Object)null)
			{
				return false;
			}
			float num = ((((Texture)destination).height > 0) ? ((float)((Texture)destination).width / (float)((Texture)destination).height) : 1f);
			if (Mathf.Abs(num - _builtAspect) > 0.001f || Mathf.Abs(fieldOfView - _builtFieldOfView) > 0.5f || Mathf.Abs(strength - _builtStrength) > 0.001f)
			{
				BuildUvs(num, fieldOfView, strength);
			}
			ShaderLibrary.SetMainTexture(_material, source);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.SetRenderTarget(destination);
				GL.Clear(false, true, Color.black);
				GL.PushMatrix();
				GL.LoadOrtho();
				SuspendFog();
				try
				{
					if (_material.SetPass(0))
					{
						Graphics.DrawMeshNow(_mesh, Matrix4x4.identity);
					}
				}
				finally
				{
					RestoreFog();
					GL.PopMatrix();
				}
				if (!_markedFirstDraw)
				{
					_markedFirstDraw = true;
					Breadcrumbs.Mark($"fisheye: first draw {((Texture)destination).width}x{((Texture)destination).height}");
				}
				return true;
			}
			catch (Exception ex)
			{
				if (!_drawFailureLogged)
				{
					_drawFailureLogged = true;
					ModLog.Warn("The fisheye could not be drawn; the lens shows its plain picture: " + ModLog.Describe(ex));
				}
				return false;
			}
			finally
			{
				RenderTexture.active = active;
			}
		}

		private void SuspendFog()
		{
			for (int i = 0; i < FogKeywords.Length; i++)
			{
				_fogWasOn[i] = Shader.IsKeywordEnabled(FogKeywords[i]);
				if (_fogWasOn[i])
				{
					Shader.DisableKeyword(FogKeywords[i]);
				}
			}
		}

		private void RestoreFog()
		{
			for (int i = 0; i < FogKeywords.Length; i++)
			{
				if (_fogWasOn[i])
				{
					Shader.EnableKeyword(FogKeywords[i]);
				}
				_fogWasOn[i] = false;
			}
		}

		private void BuildGrid(int vertexCount)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: 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_0141: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[vertexCount];
			int num = 0;
			for (int i = 0; i <= 24; i++)
			{
				float num2 = (float)i / 24f;
				for (int j = 0; j <= 40; j++)
				{
					array[num++] = new Vector3((float)j / 40f, num2, 0f);
				}
			}
			int[] array2 = new int[5760];
			int num3 = 0;
			int num4 = 41;
			for (int k = 0; k < 24; k++)
			{
				for (int l = 0; l < 40; l++)
				{
					int num5 = k * num4 + l;
					int num6 = num5 + 1;
					int num7 = num5 + num4;
					int num8 = num7 + 1;
					array2[num3++] = num5;
					array2[num3++] = num8;
					array2[num3++] = num6;
					array2[num3++] = num5;
					array2[num3++] = num7;
					array2[num3++] = num8;
				}
			}
			_mesh.vertices = Il2CppStructArray<Vector3>.op_Implicit(array);
			BuildUvs(1f, 60f, 0f);
			_mesh.triangles = Il2CppStructArray<int>.op_Implicit(array2);
			_mesh.bounds = new Bounds(new Vector3(0.5f, 0.5f, 0f), new Vector3(1f, 1f, 1f));
		}

		private void BuildUvs(float aspect, float fieldOfView, float strength)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			for (int i = 0; i <= 24; i++)
			{
				double outputY = (double)i / 24.0;
				for (int j = 0; j <= 40; j++)
				{
					FisheyeMapping.SourceFor((double)j / 40.0, outputY, aspect, fieldOfView, strength, out var sourceX, out var sourceY);
					((Il2CppArrayBase<Vector2>)(object)_uvs)[num++] = new Vector2((float)sourceX, (float)sourceY);
				}
			}
			_mesh.SetUVs(0, _uvs);
			_builtAspect = aspect;
			_builtFieldOfView = fieldOfView;
			_builtStrength = strength;
		}

		public void Dispose()
		{
			if (_disposed)
			{
				return;
			}
			_disposed = true;
			try
			{
				if ((Object)(object)_mesh != (Object)null)
				{
					Object.Destroy((Object)(object)_mesh);
				}
				if ((Object)(object)_material != (Object)null)
				{
					Object.Destroy((Object)(object)_material);
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Fisheye stage cleanup failed: " + ModLog.Describe(ex3));
			}
		}
	}
	public static class FootageCloak
	{
		private sealed class Entry
		{
			public GameObject Root;

			public Renderer[] Renderers = Array.Empty<Renderer>();

			public float NextRefresh;
		}

		private const float RendererRefreshSeconds = 2f;

		private static readonly List<Entry> Entries = new List<Entry>();

		private static readonly List<Camera> Lenses = new List<Camera>();

		private static readonly List<Renderer> Hidden = new List<Renderer>();

		private static int _depth;

		private static bool _hooked;

		private static bool _hookFailed;

		private static Action<ScriptableRenderContext, Camera> _begin;

		private static Action<ScriptableRenderContext, Camera> _end;

		public static bool Enabled { get; set; } = true;

		public static void RegisterLens(Camera camera)
		{
			if (!((Object)(object)camera == (Object)null) && !Lenses.Contains(camera))
			{
				Lenses.Add(camera);
				EnsureHooked();
			}
		}

		public static void UnregisterLens(Camera camera)
		{
			if ((Object)(object)camera != (Object)null)
			{
				Lenses.Remove(camera);
			}
		}

		public static void Register(GameObject root)
		{
			if ((Object)(object)root == (Object)null)
			{
				return;
			}
			for (int i = 0; i < Entries.Count; i++)
			{
				if ((Object)(object)Entries[i].Root == (Object)(object)root)
				{
					return;
				}
			}
			Entries.Add(new Entry
			{
				Root = root
			});
		}

		public static void Unregister(GameObject root)
		{
			for (int num = Entries.Count - 1; num >= 0; num--)
			{
				GameObject root2 = Entries[num].Root;
				if ((Object)(object)root2 == (Object)null || (Object)(object)root2 == (Object)(object)root)
				{
					Entries.RemoveAt(num);
				}
			}
		}

		public static void Conceal()
		{
			if (++_depth != 1 || !Enabled || Entries.Count == 0)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			for (int num = Entries.Count - 1; num >= 0; num--)
			{
				Entry entry = Entries[num];
				if ((Object)(object)entry.Root == (Object)null)
				{
					Entries.RemoveAt(num);
				}
				else
				{
					if (unscaledTime >= entry.NextRefresh)
					{
						entry.NextRefresh = unscaledTime + 2f;
						try
						{
							entry.Renderers = Il2CppArrayBase<Renderer>.op_Implicit(entry.Root.GetComponentsInChildren<Renderer>(true));
						}
						catch
						{
							entry.Renderers = Array.Empty<Renderer>();
						}
					}
					Renderer[] renderers = entry.Renderers;
					foreach (Renderer val in renderers)
					{
						if (!((Object)(object)val == (Object)null) && !val.forceRenderingOff)
						{
							val.forceRenderingOff = true;
							Hidden.Add(val);
						}
					}
				}
			}
		}

		public static void Reveal()
		{
			if (_depth <= 0)
			{
				_depth = 0;
			}
			else
			{
				if (--_depth != 0)
				{
					return;
				}
				for (int i = 0; i < Hidden.Count; i++)
				{
					Renderer val = Hidden[i];
					try
					{
						if ((Object)(object)val != (Object)null)
						{
							val.forceRenderingOff = false;
						}
					}
					catch
					{
					}
				}
				Hidden.Clear();
			}
		}

		private static bool IsLens(Camera camera)
		{
			for (int i = 0; i < Lenses.Count; i++)
			{
				if ((Object)(object)Lenses[i] == (Object)(object)camera)
				{
					return true;
				}
			}
			return false;
		}

		private static void OnBeginCamera(ScriptableRenderContext context, Camera camera)
		{
			try
			{
				if (IsLens(camera))
				{
					Conceal();
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Hiding props from a lens failed: " + ModLog.Describe(ex3));
			}
		}

		private static void OnEndCamera(ScriptableRenderContext context, Camera camera)
		{
			try
			{
				if (IsLens(camera))
				{
					Reveal();
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Restoring props after a lens failed: " + ModLog.Describe(ex3));
			}
		}

		private static void EnsureHooked()
		{
			if (_hooked || _hookFailed)
			{
				return;
			}
			Breadcrumbs.Mark("cloak: hooking the render pipeline");
			try
			{
				_begin = DelegateSupport.ConvertDelegate<Action<ScriptableRenderContext, Camera>>((Delegate)new Action<ScriptableRenderContext, Camera>(OnBeginCamera));
				_end = DelegateSupport.ConvertDelegate<Action<ScriptableRenderContext, Camera>>((Delegate)new Action<ScriptableRenderContext, Camera>(OnEndCamera));
				RenderPipelineManager.beginCameraRendering += _begin;
				RenderPipelineManager.endCameraRendering += _end;
				_hooked = true;
				ModLog.Info("Camera props are hidden from lenses while they draw.");
			}
			catch (Exception ex)
			{
				_hookFailed = true;
				ModLog.Warn("Could not follow the render pipeline, so cameras may appear in recordings; the viewfinder still hides them: " + ModLog.Describe(ex));
			}
		}

		public static void Shutdown()
		{
			while (_depth > 0)
			{
				Reveal();
			}
			if (_hooked)
			{
				try
				{
					RenderPipelineManager.beginCameraRendering -= _begin;
					RenderPipelineManager.endCameraRendering -= _end;
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception ex3 = ex2;
					ModLog.Debug(() => "Unhooking the render pipeline failed: " + ModLog.Describe(ex3));
				}
				_hooked = false;
			}
			Entries.Clear();
			Lenses.Clear();
		}
	}
	public sealed class LensRig : IDisposable
	{
		private readonly GameObject _owner;

		private Camera _camera;

		private RenderTexture _target;

		private bool _disposed;

		private bool _useExplicitRender = true;

		private int _autoRenderFramesRemaining;

		private static readonly List<Camera> LiveCameras = new List<Camera>();

		private const int RecordingTargetCount = 4;

		private RenderTexture[] _targets;

		private int _targetIndex;

		private RenderTexture _photoTarget;

		private bool _pipelineArmed;

		private FisheyeStage _fisheye;

		private float _fisheyeStrength;

		private float _requestedFieldOfView = 60f;

		private RenderTexture[] _warpTargets;

		private RenderTexture _warpSingle;

		private RenderTexture _warpPhoto;

		private bool _fisheyeUnavailable;

		private RenderTexture _fisheyePending;

		private int _fisheyePendingFrame = -1;

		public Camera Camera => _camera;

		public RenderTexture Target => OutputFor(_target);

		public Transform Transform
		{
			get
			{
				if (!((Object)(object)_owner != (Object)null))
				{
					return null;
				}
				return _owner.transform;
			}
		}

		public int Width
		{
			get
			{
				if (!((Object)(object)_target != (Object)null))
				{
					return 0;
				}
				return ((Texture)_target).width;
			}
		}

		public int Height
		{
			get
			{
				if (!((Object)(object)_target != (Object)null))
				{
					return 0;
				}
				return ((Texture)_target).height;
			}
		}

		public float FieldOfView
		{
			get
			{
				return _requestedFieldOfView;
			}
			set
			{
				_requestedFieldOfView = Mathf.Clamp(value, 20f, 120f);
				ApplyFieldOfView();
			}
		}

		public Func<string, Material> WarpMaterialFactory { get; set; }

		private bool FisheyeActive
		{
			get
			{
				if (_fisheye != null)
				{
					return FisheyeMapping.IsActive(_fisheyeStrength);
				}
				return false;
			}
		}

		public float FisheyeStrength
		{
			get
			{
				return _fisheyeStrength;
			}
			set
			{
				float num = FisheyeMapping.ClampStrength(value);
				if (!(Mathf.Abs(num - _fisheyeStrength) < 0.0005f))
				{
					_fisheyeStrength = num;
					if (FisheyeMapping.IsActive(num))
					{
						EnsureFisheyeStage();
					}
					ApplyFieldOfView();
				}
			}
		}

		public LensRig(Transform parent, Vector3 localPosition, string name, int cullingMaskOverride)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0048: 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)
			_owner = new GameObject(name);
			_owner.transform.SetParent(parent, false);
			_owner.transform.localPosition = localPosition;
			_owner.transform.localRotation = Quaternion.identity;
			_camera = _owner.AddComponent<Camera>();
			((Behaviour)_camera).enabled = false;
			_camera.clearFlags = (CameraClearFlags)1;
			_camera.nearClipPlane = 0.03f;
			_camera.farClipPlane = 250f;
			_camera.allowHDR = false;
			_camera.allowMSAA = false;
			_camera.useOcclusionCulling = true;
			_camera.cullingMask = ((cullingMaskOverride != 0) ? cullingMaskOverride : DefaultCullingMask());
			LiveCameras.Add(_camera);
			FootageCloak.RegisterLens(_camera);
			ConfigureUniversalPipeline(_camera);
		}

		internal static void RegisterModCamera(Camera camera)
		{
			if ((Object)(object)camera != (Object)null && !LiveCameras.Contains(camera))
			{
				LiveCameras.Add(camera);
			}
		}

		internal static void UnregisterModCamera(Camera camera)
		{
			if ((Object)(object)camera != (Object)null)
			{
				LiveCameras.Remove(camera);
			}
		}

		public static bool BelongsToMod(Camera camera)
		{
			if ((Object)(object)camera == (Object)null)
			{
				return false;
			}
			for (int i = 0; i < LiveCameras.Count; i++)
			{
				if (LiveCameras[i] == camera)
				{
					return true;
				}
			}
			return false;
		}

		internal static void ConfigureUniversalPipeline(Camera camera)
		{
			try
			{
				UniversalAdditionalCameraData val = ((Component)camera).GetComponent<UniversalAdditionalCameraData>();
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)camera).gameObject.AddComponent<UniversalAdditionalCameraData>();
				}
				val.renderType = (CameraRenderType)0;
				val.renderPostProcessing = false;
				val.antialiasing = (AntialiasingMode)0;
				val.renderShadows = false;
				val.requiresColorOption = (CameraOverrideOption)0;
				val.requiresDepthOption = (CameraOverrideOption)0;
				val.allowXRRendering = false;
			}
			catch (Exception ex)
			{
				ModLog.Warn("Could not configure URP camera data: " + ModLog.Describe(ex));
			}
		}

		private void ApplyFieldOfView()
		{
			if (!((Object)(object)_camera == (Object)null))
			{
				float strength = (FisheyeActive ? _fisheyeStrength : 0f);
				_camera.fieldOfView = Mathf.Clamp(FisheyeMapping.RenderedFieldOfView(_requestedFieldOfView, strength), 20f, 150f);
			}
		}

		private void EnsureFisheyeStage()
		{
			if (_fisheye != null || _fisheyeUnavailable || _disposed)
			{
				return;
			}
			try
			{
				string text = (((Object)(object)_owner != (Object)null) ? ((Object)_owner).name : "Lens") + "_Fisheye";
				Material val = ShaderLibrary.CreateCopyMaterial(text);
				if ((Object)(object)val == (Object)null)
				{
					val = ((WarpMaterialFactory != null) ? WarpMaterialFactory(text) : ShaderLibrary.CreateUnlitMaterial(text));
					ModLog.Warn("No plain copy shader was found; the fisheye falls back to the screens' unlit material, which the level's fog can grey out.");
				}
				ModLog.Info("Fisheye draws with '" + (((Object)(object)val != (Object)null && (Object)(object)val.shader != (Object)null) ? ((Object)val.shader).name : "nothing") + "'.");
				if ((Object)(object)val == (Object)null)
				{
					_fisheyeUnavailable = true;
					ModLog.Warn("No unlit material is available, so the fisheye cannot be drawn.");
				}
				else
				{
					_fisheye = new FisheyeStage(text, val);
				}
			}
			catch (Exception ex)
			{
				_fisheyeUnavailable = true;
				ModLog.Warn("The fisheye stage could not be built; the lens stays rectilinear: " + ModLog.Describe(ex));
			}
		}

		private RenderTexture OutputFor(RenderTexture source)
		{
			if ((Object)(object)source == (Object)null || !FisheyeActive)
			{
				return source;
			}
			if (_targets != null && _warpTargets != null)
			{
				for (int i = 0; i < _targets.Length; i++)
				{
					if (_targets[i] == source)
					{
						if (!((Object)(object)_warpTargets[i] != (Object)null))
						{
							return source;
						}
						return _warpTargets[i];
					}
				}
			}
			if (source == _photoTarget)
			{
				if (!((Object)(object)_warpPhoto != (Object)null))
				{
					return source;
				}
				return _warpPhoto;
			}
			if (!((Object)(object)_warpSingle != (Object)null))
			{
				return source;
			}
			return _warpSingle;
		}

		private RenderTexture WarpTargetFor(RenderTexture source)
		{
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			if (_targets != null)
			{
				for (int i = 0; i < _targets.Length; i++)
				{
					if (_targets[i] == source)
					{
						if (_warpTargets == null || _warpTargets.Length != _targets.Length)
						{
							DestroyAll(_warpTargets);
							_warpTargets = (RenderTexture[])(object)new RenderTexture[_targets.Length];
						}
						return EnsureMatching(ref _warpTargets[i], source, "_Fisheye" + i);
					}
				}
			}
			if (source == _photoTarget)
			{
				return EnsureMatching(ref _warpPhoto, source, "_FisheyePhoto");
			}
			return EnsureMatching(ref _warpSingle, source, "_Fisheye");
		}

		private static RenderTexture EnsureMatching(ref RenderTexture output, RenderTexture source, string suffix)
		{
			if ((Object)(object)output != (Object)null && output.IsCreated() && ((Texture)output).width == ((Texture)source).width && ((Texture)output).height == ((Texture)source).height)
			{
				return output;
			}
			DestroyTarget(output);
			output = CreateTarget(((Texture)source).width, ((Texture)source).height, ((Object)source).name + suffix, 0);
			return output;
		}

		private void ArmFisheye(RenderTexture source)
		{
			if (FisheyeActive && !((Object)(object)_camera == (Object)null) && !((Object)(object)source == (Object)null) && !((Object)(object)WarpTargetFor(source) == (Object)null))
			{
				_fisheyePending = source;
				_fisheyePendingFrame = Time.frameCount;
			}
		}

		private void FlushFisheye()
		{
			RenderTexture fisheyePending = _fisheyePending;
			if ((Object)(object)fisheyePending == (Object)null || Time.frameCount <= _fisheyePendingFrame)
			{
				return;
			}
			_fisheyePending = null;
			if (FisheyeActive && !((Object)(object)_camera == (Object)null) && fisheyePending.IsCreated())
			{
				RenderTexture val = WarpTargetFor(fisheyePending);
				if ((Object)(object)val != (Object)null)
				{
					_fisheye.Draw((Texture)(object)fisheyePending, val, _camera.fieldOfView, _fisheyeStrength);
				}
			}
		}

		private void RenderFisheyeNow(RenderTexture source)
		{
			if (FisheyeActive && !((Object)(object)_camera == (Object)null))
			{
				RenderTexture val = WarpTargetFor(source);
				if ((Object)(object)val != (Object)null)
				{
					_fisheye.Draw((Texture)(object)source, val, _camera.fieldOfView, _fisheyeStrength);
				}
			}
		}

		private static void DestroyAll(RenderTexture[] textures)
		{
			if (textures != null)
			{
				for (int i = 0; i < textures.Length; i++)
				{
					DestroyTarget(textures[i]);
				}
			}
		}

		public void LookAt(Vector3 worldPoint, Vector3 up)
		{
			//IL_000f: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_owner == (Object)null))
			{
				Vector3 val = worldPoint - _owner.transform.position;
				if (!(((Vector3)(ref val)).sqrMagnitude < 1E-06f))
				{
					_owner.transform.rotation = Quaternion.LookRotation(val, up);
				}
			}
		}

		public bool EnsureRecordingTargets(int width, int height, string name)
		{
			if (_disposed)
			{
				return false;
			}
			if (_targets != null && _targets.Length == 4 && (Object)(object)_targets[0] != (Object)null && ((Texture)_targets[0]).width == width && ((Texture)_targets[0]).height == height && _targets[0].IsCreated())
			{
				return true;
			}
			ReleaseTarget();
			_targets = (RenderTexture[])(object)new RenderTexture[4];
			for (int i = 0; i < 4; i++)
			{
				RenderTexture val = CreateTarget(width, height, $"{name}_{i}");
				if ((Object)(object)val == (Object)null)
				{
					ReleaseTarget();
					return false;
				}
				_targets[i] = val;
			}
			_targetIndex = 0;
			_target = _targets[0];
			if ((Object)(object)_camera != (Object)null)
			{
				_camera.targetTexture = _target;
			}
			return true;
		}

		public void AdvanceRecordingTarget()
		{
			if (_targets != null && _targets.Length != 0)
			{
				_targetIndex = (_targetIndex + 1) % _targets.Length;
				_target = _targets[_targetIndex];
				if ((Object)(object)_camera != (Object)null)
				{
					_camera.targetTexture = _target;
				}
			}
		}

		public void ReleaseRecordingTargets()
		{
			if (_targets != null)
			{
				ReleaseTarget();
			}
		}

		public bool BeginPhotoRender(int width, int height)
		{
			return BeginPhotoRender(width, height, preClear: true);
		}

		public bool BeginPhotoRender(int width, int height, bool preClear)
		{
			if (_disposed || (Object)(object)_camera == (Object)null)
			{
				return false;
			}
			if ((Object)(object)_photoTarget == (Object)null || !_photoTarget.IsCreated() || ((Texture)_photoTarget).width != width || ((Texture)_photoTarget).height != height)
			{
				DestroyTarget(_photoTarget);
				_photoTarget = CreateTarget(width, height, "CinematicCameraPhoto");
				if ((Object)(object)_photoTarget == (Object)null)
				{
					return false;
				}
			}
			else if (preClear)
			{
				ClearTarget(_photoTarget);
			}
			_camera.targetTexture = _photoTarget;
			_pipelineArmed = true;
			ExcludeOperatorBadge();
			((Behaviour)_camera).enabled = true;
			ArmFisheye(_photoTarget);
			return true;
		}

		public bool TryRequestPhotoReadback(out AsyncGPUReadbackRequest request)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			request = default(AsyncGPUReadbackRequest);
			if (_disposed || (Object)(object)_photoTarget == (Object)null || !_photoTarget.IsCreated())
			{
				return false;
			}
			try
			{
				FlushFisheye();
				request = AsyncGPUReadback.Request((Texture)(object)OutputFor(_photoTarget), 0, (Action<AsyncGPUReadbackRequest>)null);
				return true;
			}
			catch (Exception ex)
			{
				ModLog.Error("Async photo readback request failed.", ex);
				return false;
			}
		}

		public RenderTexture EndPhotoRender(bool disarmCamera)
		{
			if ((Object)(object)_camera != (Object)null)
			{
				_camera.targetTexture = _target;
				if (disarmCamera && ((Behaviour)_camera).enabled)
				{
					((Behaviour)_camera).enabled = false;
				}
			}
			if (disarmCamera)
			{
				_pipelineArmed = false;
			}
			FlushFisheye();
			return OutputFor(_photoTarget);
		}

		public void ReleasePhotoTarget()
		{
			DestroyTarget(_photoTarget);
			_photoTarget = null;
			DestroyTarget(_warpPhoto);
			_warpPhoto = null;
		}

		public bool EnsureTarget(int width, int height, string name)
		{
			if (_disposed)
			{
				return false;
			}
			if (_targets == null && (Object)(object)_target != (Object)null && ((Texture)_target).width == width && ((Texture)_target).height == height && _target.IsCreated())
			{
				return true;
			}
			ReleaseTarget();
			_target = CreateTarget(width, height, name);
			if ((Object)(object)_target == (Object)null)
			{
				return false;
			}
			if ((Object)(object)_camera != (Object)null)
			{
				_camera.targetTexture = _target;
			}
			return true;
		}

		private static RenderTexture CreateTarget(int width, int height, string name, int depthBits = 24)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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_003c: Expected O, but got Unknown
			try
			{
				RenderTexture val = new RenderTexture(width, height, depthBits, (RenderTextureFormat)0)
				{
					name = name,
					antiAliasing = 1,
					useMipMap = false,
					autoGenerateMips = false,
					filterMode = (FilterMode)1,
					wrapMode = (TextureWrapMode)1,
					hideFlags = (HideFlags)61
				};
				if (val.Create())
				{
					return val;
				}
				ModLog.Error($"Failed to create a {width}x{height} render texture for the lens.");
				Object.Destroy((Object)(object)val);
				return null;
			}
			catch (Exception ex)
			{
				ModLog.Error($"Render texture creation threw for {width}x{height}.", ex);
				return null;
			}
		}

		private static int DefaultCullingMask()
		{
			return -33 & ~ModLayers.HudBit;
		}

		public bool RenderOnce()
		{
			if (_disposed || (Object)(object)_camera == (Object)null || (Object)(object)_target == (Object)null)
			{
				return false;
			}
			if (_pipelineArmed)
			{
				return false;
			}
			ExcludeOperatorBadge();
			if (_useExplicitRender)
			{
				try
				{
					FootageCloak.Conceal();
					try
					{
						_camera.Render();
					}
					finally
					{
						FootageCloak.Reveal();
					}
					RenderFisheyeNow(_target);
					return true;
				}
				catch (Exception ex)
				{
					_useExplicitRender = false;
					ModLog.Warn("Explicit camera rendering is unavailable on this build; falling back to single-frame enabling. " + ModLog.Describe(ex));
				}
			}
			((Behaviour)_camera).enabled = true;
			ArmFisheye(_target);
			_autoRenderFramesRemaining = 1;
			return true;
		}

		public void ArmPipelineRender()
		{
			if (!_disposed && !((Object)(object)_camera == (Object)null) && !((Object)(object)_target == (Object)null))
			{
				_pipelineArmed = true;
				ExcludeOperatorBadge();
				((Behaviour)_camera).enabled = true;
				ArmFisheye(_target);
			}
		}

		private void ExcludeOperatorBadge()
		{
			if (!((Object)(object)_camera == (Object)null))
			{
				int hudBit = ModLayers.HudBit;
				if ((_camera.cullingMask & hudBit) != 0)
				{
					Camera camera = _camera;
					camera.cullingMask &= ~hudBit;
					GameObject owner = _owner;
					ModLog.Warn("The operator's badge layer had been added to lens '" + ((owner != null) ? ((Object)owner).name : null) + "'; removed it before capture.");
				}
			}
		}

		public void DisarmPipelineRender()
		{
			if (!_disposed && !((Object)(object)_camera == (Object)null))
			{
				_pipelineArmed = false;
				if (((Behaviour)_camera).enabled)
				{
					((Behaviour)_camera).enabled = false;
				}
				FlushFisheye();
				_fisheyePending = null;
			}
		}

		public void EndFrame()
		{
			if (!_disposed && !((Object)(object)_camera == (Object)null) && !_useExplicitRender)
			{
				FlushFisheye();
				if (_autoRenderFramesRemaining > 0)
				{
					_autoRenderFramesRemaining--;
				}
				else if (((Behaviour)_camera).enabled)
				{
					((Behaviour)_camera).enabled = false;
				}
			}
		}

		public void SetActive(bool active)
		{
			if ((Object)(object)_owner != (Object)null)
			{
				_owner.SetActive(active);
			}
		}

		private void ReleaseTarget()
		{
			try
			{
				if ((Object)(object)_camera != (Object)null)
				{
					_camera.targetTexture = null;
				}
				_fisheyePending = null;
				DestroyAll(_warpTargets);
				_warpTargets = null;
				DestroyTarget(_warpSingle);
				_warpSingle = null;
				if (_targets != null)
				{
					for (int i = 0; i < _targets.Length; i++)
					{
						DestroyTarget(_targets[i]);
					}
					_targets = null;
					_targetIndex = 0;
					_target = null;
				}
				else
				{
					DestroyTarget(_target);
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Render texture release failed: " + ModLog.Describe(ex3));
			}
			finally
			{
				_target = null;
			}
		}

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

		private static void ClearTarget(RenderTexture texture)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				RenderTexture active = RenderTexture.active;
				try
				{
					RenderTexture.active = texture;
					GL.Clear(false, true, new Color(0f, 0f, 0f, 1f));
				}
				finally
				{
					RenderTexture.active = active;
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Could not clear the photo target: " + ModLog.Describe(ex3));
			}
		}

		public void Dispose()
		{
			if (_disposed)
			{
				return;
			}
			_disposed = true;
			LiveCameras.Remove(_camera);
			FootageCloak.UnregisterLens(_camera);
			ReleaseTarget();
			ReleasePhotoTarget();
			_fisheye?.Dispose();
			_fisheye = null;
			_camera = null;
			if (!((Object)(object)_owner != (Object)null))
			{
				return;
			}
			try
			{
				Object.Destroy((Object)(object)_owner);
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Lens object destroy failed: " + ModLog.Describe(ex3));
			}
		}
	}
	public sealed class LookPreview : IDisposable
	{
		private const int ProcessHeight = 360;

		private const int Idle = 0;

		private const int Reading = 1;

		private const int Processing = 2;

		private const int Ready = 3;

		private readonly string _name;

		private RenderTexture _scaled;

		private Texture2D _texture;

		private byte[] _rgba = Array.Empty<byte>();

		private byte[] _yuv = Array.Empty<byte>();

		private byte[] _output = Array.Empty<byte>();

		private int _state;

		private AsyncGPUReadbackRequest _request;

		private int _width;

		private int _height;

		private BakedVisualLook _look;

		private float _intensity;

		private long _timestampMicros;

		private float _nextSubmitAt;

		private bool _hasFrame;

		private bool _markedFirstFrame;

		private bool _failed;

		private volatile bool _disposed;

		public Texture Texture
		{
			get
			{
				if (!_hasFrame)
				{
					return null;
				}
				return (Texture)(object)_texture;
			}
		}

		public LookPreview(string name)
		{
			_name = name;
		}

		public void Tick(RenderTexture source, BakedVisualLook look, float intensity, long timestampMicros, float interval)
		{
			if (_disposed || _failed)
			{
				return;
			}
			try
			{
				if (Volatile.Read(in _state) == 3)
				{
					Upload();
				}
				if (_state == 1)
				{
					Collect();
				}
				if (_state == 0 && !((Object)(object)source == (Object)null) && source.IsCreated() && !(Time.unscaledTime < _nextSubmitAt))
				{
					_nextSubmitAt = Time.unscaledTime + Mathf.Max(0.05f, interval);
					_look = look;
					_intensity = intensity;
					_timestampMicros = timestampMicros;
					Submit(source);
				}
			}
			catch (Exception ex)
			{
				_failed = true;
				ModLog.Warn("The viewfinder look preview stopped; clips are unaffected: " + ModLog.Describe(ex));
			}
		}

		public void Invalidate()
		{
			_hasFrame = false;
		}

		private void Submit(RenderTexture source)
		{
			//IL_004f: 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_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)
			int num = Math.Min(360, ((Texture)source).height) & -2;
			int num2 = Mathf.RoundToInt((float)num * ((float)((Texture)source).width / (float)((Texture)source).height)) & -2;
			if (num2 >= 16 && num >= 16)
			{
				EnsureBuffers(num2, num);
				RenderTexture active = RenderTexture.active;
				try
				{
					Graphics.Blit((Texture)(object)source, _scaled, Vector2.one, Vector2.zero);
				}
				finally
				{
					RenderTexture.active = active;
				}
				_request = AsyncGPUReadback.Request((Texture)(object)_scaled, 0, (Action<AsyncGPUReadbackRequest>)null);
				_state = 1;
				if (!_markedFirstFrame)
				{
					_markedFirstFrame = true;
					Breadcrumbs.Mark($"look preview {_name}: first frame {_width}x{_height}");
				}
			}
		}

		private void Collect()
		{
			if (!((AsyncGPUReadbackRequest)(ref _request)).done)
			{
				return;
			}
			if (((AsyncGPUReadbackRequest)(ref _request)).hasError)
			{
				_state = 0;
				return;
			}
			IntPtr dataRaw = ((AsyncGPUReadbackRequest)(ref _request)).GetDataRaw(0);
			int layerDataSize = ((AsyncGPUReadbackRequest)(ref _request)).layerDataSize;
			int num = _width * _height * 4;
			if (dataRaw == IntPtr.Zero || layerDataSize < num)
			{
				_state = 0;
				return;
			}
			Marshal.Copy(dataRaw, _rgba, 0, num);
			_state = 2;
			ThreadPool.QueueUserWorkItem(Process);
		}

		private void Process(object unused)
		{
			try
			{
				if (!_disposed)
				{
					ColorConverter.ConvertRgbaToYuv420(_rgba, _yuv, _width, _height, YuvLayout.Nv12, flipVertical: true);
					BakedLookProcessor.Apply(_yuv, _width, _height, _width, _height, YuvLayout.Nv12, _look, _intensity, _timestampMicros, 1);
					ColorConverter.ConvertYuv420ToRgba(_yuv, _output, _width, _height, YuvLayout.Nv12, flipVertical: true);
					Volatile.Write(ref _state, 3);
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception ex3 = ex2;
				ModLog.Debug(() => "Look preview frame failed: " + ModLog.Describe(ex3));
				Volatile.Write(ref _state, 0);
			}
		}

		private unsafe void Upload()
		{
			fixed (byte* output = _output)
			{
				_texture.LoadRawTextureData((IntPtr)output, _width * _height * 4);
			}
			_texture.Apply(false, false);
			_hasFrame = true;
			_state = 0;
		}

		private void EnsureBuffers(int width, int height)
		{
			//IL_005c: 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_0077: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0