Decompiled source of UltrakillTAS v1.1.1

plugins/UltrakillTAS.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Unity.Collections;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.LowLevel;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ULTRAKILL TAS")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("MIT")]
[assembly: AssemblyDescription("Deterministic tick-based TAS tool for ULTRAKILL (BepInEx 5 / HarmonyX).")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("ULTRAKILL TAS Tool")]
[assembly: AssemblyTitle("UltrakillTAS")]
[assembly: AssemblyVersion("1.1.0.0")]
namespace UltrakillTAS;

public enum BakeBlockMode
{
	None,
	Record,
	Live,
	Enforced,
	Verify
}
public struct BakeProjectile
{
	public const byte FlagShot = 1;

	public const byte FlagSplittable = 2;

	public int Key;

	public int Type;

	public Vector3 Position;

	public Quaternion Rotation;

	public Vector3 Velocity;

	public Vector3 AngularVelocity;

	public float Timer;

	public int Hits;

	public byte Flags;
}
public struct BakeEnemy
{
	public const byte FlagDead = 1;

	public const byte FlagAgent = 2;

	public const byte FlagAnimator = 4;

	public int Key;

	public int Type;

	public Vector3 Position;

	public Quaternion Rotation;

	public Vector3 Velocity;

	public float Health;

	public byte Flags;

	public Vector3 NavDestination;

	public Vector3 NavVelocity;

	public int StateHash;

	public float NormalizedTime;
}
public struct TickBakeFrame
{
	public const byte MoveGrounded = 1;

	public const byte MoveSliding = 2;

	public const byte MoveJumping = 4;

	public const byte MoveDashing = 8;

	public int Tick;

	public double Time;

	public int Rng0;

	public int Rng1;

	public int Rng2;

	public int Rng3;

	public bool HasSystemSeedStream;

	public int SystemSeedStream;

	public bool HasPlayer;

	public Vector3 PlayerPosition;

	public Vector3 PlayerVelocity;

	public float Pitch;

	public float Yaw;

	public float Health;

	public float HardDamage;

	public float Stamina;

	public byte MoveFlags;

	public int WeaponSlot;

	public int WeaponVariation;

	public int ChargeStart;

	public int ChargeCount;

	public int ProjectileStart;

	public int ProjectileCount;

	public int ProjectileChangeMask;

	public int EnemyStart;

	public int EnemyCount;

	public int DoorStart;

	public int DoorCount;

	public int RoomStart;

	public int RoomCount;
}
public sealed class BakeBlockData
{
	public string Path = string.Empty;

	public string Name = string.Empty;

	public string Hash = string.Empty;

	public int StartTick;

	public int TickCount;

	public int Version = 2;

	public List<SystemRandomSnapshot>[] SystemRandoms;

	public int[] Offsets = new int[0];

	public byte[] Data = new byte[0];

	public int DataLength;

	public bool Decoded;

	public TickBakeFrame[] Frames = new TickBakeFrame[0];

	public float[] Charges = new float[0];

	public BakeProjectile[] Projectiles = new BakeProjectile[0];

	public BakeEnemy[] Enemies = new BakeEnemy[0];

	public byte[] DoorFlags = new byte[0];

	public byte[] RoomBits = new byte[0];
}
public sealed class BakeManager
{
	[StructLayout(LayoutKind.Explicit)]
	private struct RandomStateBits
	{
		[FieldOffset(0)]
		public State State;

		[FieldOffset(0)]
		public int S0;

		[FieldOffset(4)]
		public int S1;

		[FieldOffset(8)]
		public int S2;

		[FieldOffset(12)]
		public int S3;
	}

	private struct PendingProjectile
	{
		public Component Component;

		public int Type;

		public int Id;

		public Vector3 Position;
	}

	private sealed class PendingProjectileComparer : IComparer<PendingProjectile>
	{
		public int Compare(PendingProjectile a, PendingProjectile b)
		{
			return ComparePending(a, b);
		}
	}

	private sealed class FieldAccess
	{
		private static readonly Dictionary<FieldInfo, FieldAccess> s_cache = new Dictionary<FieldInfo, FieldAccess>();

		private readonly FieldInfo _field;

		private readonly Type _type;

		private bool _compiled;

		private Func<object, float> _getFloat;

		private Func<object, int> _getInt;

		private Func<object, bool> _getBool;

		private Action<object, float> _setFloat;

		private Action<object, bool> _setBool;

		private FieldAccess(FieldInfo field)
		{
			_field = field;
			_type = field.FieldType;
			try
			{
				_compiled = Compile();
			}
			catch
			{
				_compiled = false;
			}
		}

		public static FieldAccess For(FieldInfo field)
		{
			if (field == null)
			{
				return null;
			}
			if (!s_cache.TryGetValue(field, out var value))
			{
				value = new FieldAccess(field);
				s_cache[field] = value;
			}
			return value;
		}

		public object GetValue(object target)
		{
			return _field.GetValue(target);
		}

		public float GetFloat(object target)
		{
			if (_compiled)
			{
				try
				{
					return _getFloat(target);
				}
				catch
				{
					_compiled = false;
				}
			}
			object value = _field.GetValue(target);
			if (value is float)
			{
				return (float)value;
			}
			if (value is int)
			{
				return (int)value;
			}
			if (value is double)
			{
				return (float)(double)value;
			}
			return 0f;
		}

		public int GetInt(object target)
		{
			if (_compiled)
			{
				try
				{
					return _getInt(target);
				}
				catch
				{
					_compiled = false;
				}
			}
			object value = _field.GetValue(target);
			if (value is int)
			{
				return (int)value;
			}
			if (value is float)
			{
				return (int)(float)value;
			}
			if (value is Enum)
			{
				return Convert.ToInt32(value, CultureInfo.InvariantCulture);
			}
			return 0;
		}

		public bool GetBool(object target)
		{
			if (_compiled)
			{
				try
				{
					return _getBool(target);
				}
				catch
				{
					_compiled = false;
				}
			}
			object value = _field.GetValue(target);
			if (value is bool)
			{
				return (bool)value;
			}
			return false;
		}

		public void SetFloat(object target, float value)
		{
			if (_compiled)
			{
				try
				{
					_setFloat(target, value);
					return;
				}
				catch
				{
					_compiled = false;
				}
			}
			if (_type == typeof(float))
			{
				_field.SetValue(target, value);
			}
			else if (_type == typeof(int))
			{
				_field.SetValue(target, (int)Math.Round(value));
			}
			else if (_type == typeof(double))
			{
				_field.SetValue(target, (double)value);
			}
		}

		public void SetBool(object target, bool value)
		{
			if (_type != typeof(bool))
			{
				return;
			}
			if (_compiled)
			{
				try
				{
					_setBool(target, value);
					return;
				}
				catch
				{
					_compiled = false;
				}
			}
			_field.SetValue(target, value);
		}

		private bool Compile()
		{
			FieldInfo field = _field;
			Type declaringType = field.DeclaringType;
			if (field.IsStatic || field.IsLiteral || field.IsInitOnly || declaringType == null || declaringType.IsValueType || declaringType.ContainsGenericParameters)
			{
				return false;
			}
			Type type = _type;
			Type type2 = (type.IsEnum ? Enum.GetUnderlyingType(type) : null);
			Module module = typeof(BakeManager).Module;
			Type[] parameterTypes = new Type[1] { typeof(object) };
			DynamicMethod dynamicMethod = new DynamicMethod("BakeGetFloat_" + field.Name, typeof(float), parameterTypes, module, skipVisibility: true);
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			if (type == typeof(float) || type == typeof(int) || type == typeof(double))
			{
				EmitLoadField(iLGenerator, declaringType, field);
				if (type != typeof(float))
				{
					iLGenerator.Emit(OpCodes.Conv_R4);
				}
			}
			else
			{
				iLGenerator.Emit(OpCodes.Ldc_R4, 0f);
			}
			iLGenerator.Emit(OpCodes.Ret);
			_getFloat = (Func<object, float>)dynamicMethod.CreateDelegate(typeof(Func<object, float>));
			dynamicMethod = new DynamicMethod("BakeGetInt_" + field.Name, typeof(int), parameterTypes, module, skipVisibility: true);
			iLGenerator = dynamicMethod.GetILGenerator();
			if (type == typeof(int))
			{
				EmitLoadField(iLGenerator, declaringType, field);
			}
			else if (type == typeof(float))
			{
				EmitLoadField(iLGenerator, declaringType, field);
				iLGenerator.Emit(OpCodes.Conv_I4);
			}
			else if (type2 != null)
			{
				EmitLoadField(iLGenerator, declaringType, field);
				bool flag = type2 == typeof(byte) || type2 == typeof(ushort) || type2 == typeof(uint) || type2 == typeof(ulong);
				iLGenerator.Emit(flag ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4);
			}
			else
			{
				iLGenerator.Emit(OpCodes.Ldc_I4_0);
			}
			iLGenerator.Emit(OpCodes.Ret);
			_getInt = (Func<object, int>)dynamicMethod.CreateDelegate(typeof(Func<object, int>));
			dynamicMethod = new DynamicMethod("BakeGetBool_" + field.Name, typeof(bool), parameterTypes, module, skipVisibility: true);
			iLGenerator = dynamicMethod.GetILGenerator();
			if (type == typeof(bool))
			{
				EmitLoadField(iLGenerator, declaringType, field);
			}
			else
			{
				iLGenerator.Emit(OpCodes.Ldc_I4_0);
			}
			iLGenerator.Emit(OpCodes.Ret);
			_getBool = (Func<object, bool>)dynamicMethod.CreateDelegate(typeof(Func<object, bool>));
			dynamicMethod = new DynamicMethod("BakeSetFloat_" + field.Name, typeof(void), new Type[2]
			{
				typeof(object),
				typeof(float)
			}, module, skipVisibility: true);
			iLGenerator = dynamicMethod.GetILGenerator();
			if (type == typeof(float) || type == typeof(int) || type == typeof(double))
			{
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Castclass, declaringType);
				iLGenerator.Emit(OpCodes.Ldarg_1);
				if (type == typeof(int))
				{
					iLGenerator.Emit(OpCodes.Conv_R8);
					iLGenerator.Emit(OpCodes.Call, typeof(Math).GetMethod("Round", new Type[1] { typeof(double) }));
					iLGenerator.Emit(OpCodes.Conv_I4);
				}
				else if (type == typeof(double))
				{
					iLGenerator.Emit(OpCodes.Conv_R8);
				}
				iLGenerator.Emit(OpCodes.Stfld, field);
			}
			iLGenerator.Emit(OpCodes.Ret);
			_setFloat = (Action<object, float>)dynamicMethod.CreateDelegate(typeof(Action<object, float>));
			dynamicMethod = new DynamicMethod("BakeSetBool_" + field.Name, typeof(void), new Type[2]
			{
				typeof(object),
				typeof(bool)
			}, module, skipVisibility: true);
			iLGenerator = dynamicMethod.GetILGenerator();
			if (type == typeof(bool))
			{
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Castclass, declaringType);
				iLGenerator.Emit(OpCodes.Ldarg_1);
				iLGenerator.Emit(OpCodes.Stfld, field);
			}
			iLGenerator.Emit(OpCodes.Ret);
			_setBool = (Action<object, bool>)dynamicMethod.CreateDelegate(typeof(Action<object, bool>));
			return true;
		}

		private static void EmitLoadField(ILGenerator il, Type owner, FieldInfo field)
		{
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Castclass, owner);
			il.Emit(OpCodes.Ldfld, field);
		}
	}

	public const uint Magic = 1262635861u;

	public const int FormatVersion = 2;

	private const int MinFormatVersion = 1;

	private const int SystemRngFormatVersion = 2;

	public const string Extension = ".ukbake";

	public const string StatusLive = "[LIVE INPUT]";

	public const string StatusSynced = "[BAKED - SYNCED - NOT LEGIT]";

	public const string StatusRecording = "[RECORDING BAKE]";

	public const string StatusVerify = "[VERIFY - LIVE INPUT]";

	public const string StatusDrift = "[VERIFY - DRIFT DETECTED]";

	public const string StatusSkipped = "[BAKED - SKIPPED TO END - NOT LEGIT]";

	private const float VerifyTolerance = 0.0001f;

	private const float ApplyEpsilonSq = 1E-10f;

	private const float ApplyEpsilon = 1E-06f;

	private const float NavDestinationEpsilonSq = 0.0001f;

	private const float NavDirectMoveMaxSq = 1f;

	private static readonly string[] EnemyTypeNames = new string[1] { "enemyType" };

	private static readonly string[] EnemyHealthNames = new string[3] { "health", "hp", "currentHealth" };

	private static readonly string[] EnemyDeadNames = new string[2] { "dead", "isDead" };

	private static readonly string[] ProjectileTimerNames = new string[6] { "timeToDelete", "life", "lifetime", "lifeTime", "timer", "fuse" };

	private static readonly string[] ProjectileHitNames = new string[7] { "ricochets", "ricochet", "bounceCount", "bounces", "hitTimes", "hits", "hitAmount" };

	private readonly Plugin _plugin;

	private readonly GameBridge _bridge;

	public ConfigEntry<bool> EnableBakedPlayback;

	public ConfigEntry<bool> VerifyRawPlayback;

	public ConfigEntry<bool> SkipBakedBlocks;

	public ConfigEntry<float> CorrectionThreshold;

	private TasScript _script;

	private string _scriptPath = string.Empty;

	private readonly Dictionary<string, BakeBlockData> _loaded = new Dictionary<string, BakeBlockData>(StringComparer.OrdinalIgnoreCase);

	private readonly HashSet<string> _missing = new HashSet<string>(StringComparer.Ordinal);

	private bool _engaged;

	private bool _tickBeforeValid;

	private int _tickBefore;

	private int _lastTick = int.MinValue;

	private EngineMode _lastEngineMode;

	private TasBakeBlock _active;

	private BakeBlockData _activeData;

	private BakeBlockMode _mode;

	private bool _recording;

	private string _recordPath = string.Empty;

	private int _projValidMask;

	private bool _driftReported;

	private readonly MemoryStream _recBuffer = new MemoryStream(1048576);

	private readonly BinaryWriter _recWriter;

	private readonly List<int> _recOffsets = new List<int>(4096);

	private readonly List<List<SystemRandomSnapshot>> _recSystemRandoms = new List<List<SystemRandomSnapshot>>(4096);

	private float _thresholdSq = 1E-10f;

	private int _tickRng;

	private int _tickPlayer;

	private int _tickEnemies;

	private int _tickNavRepaths;

	private int _tickProjectiles;

	private int _tickDoors;

	private bool _corrLogged;

	private int _corrLastTick;

	private long _corrBlock;

	private int _corrTicksApplied;

	private int _corrTicksCorrected;

	private int _corrMaxTick;

	private int _corrMaxAt = -1;

	private int _corrRng;

	private int _corrPlayer;

	private int _corrEnemies;

	private int _corrNavRepaths;

	private int _corrProjectiles;

	private int _corrDoors;

	private int _projRescans;

	private string _corrBlockName = string.Empty;

	private int _corrVersion;

	private int _corrTextVersion = -1;

	private string _corrText = string.Empty;

	private readonly StringBuilder _corrBuilder = new StringBuilder(160);

	public const string NotLegitWarning = "WARNING: BAKED PLAYBACK IS NOT LEGITIMATE. It replays stored state instead of pure inputs. Runs using it are not valid TAS runs.";

	private static BakeManager s_current;

	private static bool s_runAppliedBakedState;

	private static bool s_runRecordedBake;

	private static bool s_runBakedPlaybackWasOn;

	private bool _rngBroken;

	private bool _systemRngWarned;

	private Component _player;

	private Transform _playerTransform;

	private Rigidbody _playerBody;

	private FieldAccess _fHp;

	private FieldAccess _fAntiHp;

	private FieldAccess _fBoostCharge;

	private FieldAccess _fSliding;

	private FieldAccess _fJumping;

	private FieldAccess _fDashing;

	private FieldAccess _fGroundCheck;

	private FieldAccess _fOnGround;

	private Type _groundCheckType;

	private object _camera;

	private FieldAccess _fRotX;

	private FieldAccess _fRotY;

	private object _gun;

	private FieldAccess _fSlot;

	private FieldAccess _fVariation;

	private Component _charges;

	private FieldAccess[] _chargeFields = new FieldAccess[0];

	private Type _chargesType;

	private bool _chargesSearched;

	private Type[] _projTypes;

	private int _coinType = -1;

	private FieldAccess[] _projTimer;

	private FieldAccess[] _projHits;

	private FieldAccess[] _projShot;

	private FieldAccess[] _projSplit;

	private int[] _projNextOrdinal = new int[0];

	private readonly Dictionary<int, int> _projKeys = new Dictionary<int, int>(256);

	private readonly HashSet<int> _projRoots = new HashSet<int>();

	private readonly List<PendingProjectile> _pending = new List<PendingProjectile>(16);

	private Component[] _liveProj = (Component[])(object)new Component[64];

	private GameObject[] _liveProjObject = (GameObject[])(object)new GameObject[64];

	private Transform[] _liveProjTransform = (Transform[])(object)new Transform[64];

	private Rigidbody[] _liveProjBody = (Rigidbody[])(object)new Rigidbody[64];

	private int[] _liveProjKey = new int[64];

	private int[] _liveProjType = new int[64];

	private int _liveProjCount;

	private readonly Dictionary<int, int> _slotByKey = new Dictionary<int, int>(128);

	private bool _projFullScanPending = true;

	private readonly HashSet<int> _scanRoots = new HashSet<int>();

	private readonly Dictionary<int, int> _frameProjIndex = new Dictionary<int, int>(64);

	private static readonly Comparison<PendingProjectile> PendingOrder = ComparePending;

	private static readonly IComparer<PendingProjectile> PendingComparer = new PendingProjectileComparer();

	private bool _retryProjectileTypes;

	private bool _enemiesCached;

	private int _enemyCount;

	private int[] _enemyIds = new int[0];

	private Component[] _enemyComps = (Component[])(object)new Component[0];

	private Rigidbody[] _enemyBodies = (Rigidbody[])(object)new Rigidbody[0];

	private NavMeshAgent[] _enemyAgents = (NavMeshAgent[])(object)new NavMeshAgent[0];

	private Animator[] _enemyAnimators = (Animator[])(object)new Animator[0];

	private int[] _enemyTypes = new int[0];

	private FieldAccess[] _enemyHealth = new FieldAccess[0];

	private FieldAccess[] _enemyDead = new FieldAccess[0];

	private GameObject[] _enemyObjects = (GameObject[])(object)new GameObject[0];

	private Transform[] _enemyTransforms = (Transform[])(object)new Transform[0];

	private int[] _enemySlotById = new int[0];

	private bool _doorsCached;

	private Component[] _doors = (Component[])(object)new Component[0];

	private FieldAccess[] _doorOpen = new FieldAccess[0];

	private FieldAccess[] _doorLocked = new FieldAccess[0];

	private GameObject[] _rooms = (GameObject[])(object)new GameObject[0];

	public string StatusText { get; private set; }

	public string DetailText { get; private set; }

	public BakeBlockMode Mode => _mode;

	public int CorrectionsLastTick => _corrLastTick;

	public long CorrectionsThisBlock => _corrBlock;

	public string CorrectionText
	{
		get
		{
			if (_corrTextVersion == _corrVersion)
			{
				return _corrText;
			}
			_corrTextVersion = _corrVersion;
			if (_corrTicksApplied == 0)
			{
				_corrText = string.Empty;
				return _corrText;
			}
			StringBuilder corrBuilder = _corrBuilder;
			corrBuilder.Length = 0;
			corrBuilder.Append("Desync corrections ('").Append(_corrBlockName).Append("'): last tick ")
				.Append(_corrLastTick)
				.Append(", block ")
				.Append(_corrBlock)
				.Append(" on ")
				.Append(_corrTicksCorrected)
				.Append('/')
				.Append(_corrTicksApplied)
				.Append(" ticks");
			if (_corrMaxAt >= 0)
			{
				corrBuilder.Append(", max ").Append(_corrMaxTick).Append(" at tick ")
					.Append(_corrMaxAt);
			}
			_corrText = corrBuilder.ToString();
			return _corrText;
		}
	}

	public static bool BakedPlaybackEnabled
	{
		get
		{
			if (s_current != null && s_current.EnableBakedPlayback != null)
			{
				return s_current.EnableBakedPlayback.Value;
			}
			return false;
		}
	}

	public static bool RunAppliedBakedState => s_runAppliedBakedState;

	public static bool RunIsSubmittable
	{
		get
		{
			if (!BakedPlaybackEnabled && !s_runAppliedBakedState && !s_runRecordedBake)
			{
				return !s_runBakedPlaybackWasOn;
			}
			return false;
		}
	}

	public static string NotSubmittableReason
	{
		get
		{
			if (s_runAppliedBakedState)
			{
				return "baked state was applied during this run";
			}
			if (BakedPlaybackEnabled)
			{
				return "Enable Baked Playback is ON";
			}
			if (s_runBakedPlaybackWasOn)
			{
				return "Enable Baked Playback was ON during this run";
			}
			if (s_runRecordedBake)
			{
				return "this run recorded a bake (baking was active)";
			}
			return string.Empty;
		}
	}

	public BakeManager(Plugin plugin, GameBridge bridge)
	{
		_plugin = plugin;
		_bridge = bridge;
		_recWriter = new BinaryWriter(_recBuffer);
		ConfigFile configFile = plugin.ConfigFile;
		EnableBakedPlayback = configFile.Bind<bool>("1. General", "Enable Baked Playback (.ukbake)", false, "Inside a bake block with a valid .ukbake, write the baked world state over the game after every tick (inputs still run).");
		VerifyRawPlayback = configFile.Bind<bool>("1. General", "Verify Raw Playback Against Bake", false, "Inside a baked block played live, compare the player and coin positions to the bake every tick and report the first drift.");
		SkipBakedBlocks = configFile.Bind<bool>("1. General", "Skip Baked Blocks to End", false, "When a bake block has a valid .ukbake, jump straight to its last baked frame and continue live after bake_end.");
		CorrectionThreshold = configFile.Bind<float>("6. Advanced", "Baked Playback Correction Threshold", 0f, "ADVANCED. Enforced baked playback only: live-vs-baked difference (world units for positions, units/s for velocities) that is left uncorrected. 0 (default) snaps every difference above float noise back to the bake on every tick. Any value above 0 lets the game drift from the .ukbake by up to that amount.");
		StatusText = "[LIVE INPUT]";
		DetailText = string.Empty;
		s_current = this;
	}

	public static bool CheckRunSubmittable(string action, out string message)
	{
		if (RunIsSubmittable)
		{
			message = string.Empty;
			return true;
		}
		message = (string.IsNullOrEmpty(action) ? "Run" : action) + " blocked: RUN IS NOT SUBMITTABLE (" + NotSubmittableReason + "). WARNING: BAKED PLAYBACK IS NOT LEGITIMATE. It replays stored state instead of pure inputs. Runs using it are not valid TAS runs.";
		if (s_current != null)
		{
			s_current._plugin.LogWarning(message);
			s_current._plugin.Toast(message, error: true);
		}
		return false;
	}

	public static void BeginRun()
	{
		s_runAppliedBakedState = false;
		s_runRecordedBake = false;
		s_runBakedPlaybackWasOn = false;
	}

	public void OnBeginFrame()
	{
		TasEngine engine = _plugin.Engine;
		_engaged = (engine?.Script)?.HasBakeBlocks ?? false;
		if (_engaged)
		{
			_tickBefore = engine.CurrentTick;
			_tickBeforeValid = true;
		}
	}

	public void OnEndFrame()
	{
		TasEngine engine = _plugin.Engine;
		TasScript tasScript = engine?.Script;
		if (tasScript == null || !tasScript.HasBakeBlocks)
		{
			if (_engaged || _active != null)
			{
				_engaged = false;
				ResetRun();
			}
			_tickBeforeValid = false;
			return;
		}
		_engaged = true;
		if (tasScript != _script || !string.Equals(engine.ScriptPath, _scriptPath, StringComparison.Ordinal))
		{
			SetScript(tasScript, engine.ScriptPath);
		}
		EngineMode mode = engine.Mode;
		if (mode != _lastEngineMode)
		{
			if (_lastEngineMode == EngineMode.Idle || mode == EngineMode.Idle)
			{
				_missing.Clear();
			}
			_lastEngineMode = mode;
		}
		if (mode != EngineMode.Playing && mode != EngineMode.Paused)
		{
			ResetRun();
			_tickBeforeValid = false;
			return;
		}
		if (EnableBakedPlayback.Value)
		{
			s_runBakedPlaybackWasOn = true;
		}
		int currentTick = engine.CurrentTick;
		if (_tickBeforeValid && currentTick == _tickBefore + 1)
		{
			OnTickExecuted(_tickBefore, engine, tasScript);
		}
		else if (_tickBeforeValid && currentTick != _tickBefore)
		{
			BreakContinuity();
		}
		_tickBeforeValid = false;
		if (SkipBakedBlocks.Value && !engine.Finished && !engine.StartupPending && !engine.WaitingForControl)
		{
			TrySkip(engine, tasScript);
		}
	}

	private void SetScript(TasScript script, string path)
	{
		ResetRun();
		_script = script;
		_scriptPath = path ?? string.Empty;
		_loaded.Clear();
		_missing.Clear();
		_lastEngineMode = EngineMode.Idle;
	}

	private void ResetRun()
	{
		if (_recording)
		{
			_plugin.LogInfo("Bake recording of block '" + ((_active != null) ? _active.FileName : "?") + "' dropped: playback left the block before bake_end.");
		}
		if (_active != null)
		{
			LogCorrections(_active, completed: false);
		}
		_recording = false;
		_recSystemRandoms.Clear();
		_active = null;
		_activeData = null;
		_mode = BakeBlockMode.None;
		_lastTick = int.MinValue;
		if ((object)StatusText != "[LIVE INPUT]")
		{
			StatusText = "[LIVE INPUT]";
			DetailText = string.Empty;
		}
	}

	private void BreakContinuity()
	{
		ResetRun();
	}

	private void OnTickExecuted(int tick, TasEngine engine, TasScript script)
	{
		if (tick != _lastTick + 1 && _active != null)
		{
			ResetRun();
		}
		_lastTick = tick;
		if (_active == null || tick < _active.StartTick || tick >= _active.EndTick)
		{
			if (_active != null)
			{
				ResetRun();
			}
			_lastTick = tick;
			if (!EnterBlockAt(tick, script))
			{
				if ((object)StatusText != "[LIVE INPUT]")
				{
					StatusText = "[LIVE INPUT]";
					DetailText = string.Empty;
				}
				return;
			}
		}
		TasBakeBlock active = _active;
		int num = tick - active.StartTick;
		try
		{
			if (_recording)
			{
				EnsurePlayer();
				RecordTick(tick, engine.CurrentTime);
			}
			else if (_activeData != null)
			{
				BakeBlockMode bakeBlockMode = (EnableBakedPlayback.Value ? BakeBlockMode.Enforced : (VerifyRawPlayback.Value ? BakeBlockMode.Verify : BakeBlockMode.Live));
				SetMode(bakeBlockMode);
				if (bakeBlockMode != BakeBlockMode.Live)
				{
					EnsurePlayer();
				}
				if (num >= _activeData.TickCount)
				{
					_projValidMask = 0;
				}
				else
				{
					switch (bakeBlockMode)
					{
					case BakeBlockMode.Enforced:
						TrackProjectiles(_activeData, num, 0);
						BeginCorrectionTick();
						ApplyFrame(_activeData, num, enforcedTick: true);
						EndCorrectionTick(tick);
						break;
					case BakeBlockMode.Verify:
						TrackProjectiles(_activeData, num, (!_driftReported) ? CoinMask() : 0);
						VerifyFrame(_activeData, num, active, tick);
						break;
					default:
						_projValidMask = 0;
						break;
					}
				}
			}
		}
		catch (Exception ex)
		{
			_plugin.LogWarning("Bake: tick " + tick + " of block '" + active.FileName + "' failed: " + ex.Message);
		}
		if (tick == active.EndTick - 1)
		{
			FinishBlock();
		}
	}

	private bool EnterBlockAt(int tick, TasScript script)
	{
		IList<TasBakeBlock> bakeBlocks = script.BakeBlocks;
		TasBakeBlock tasBakeBlock = null;
		for (int i = 0; i < bakeBlocks.Count; i++)
		{
			if (tick >= bakeBlocks[i].StartTick && tick < bakeBlocks[i].EndTick)
			{
				tasBakeBlock = bakeBlocks[i];
				break;
			}
		}
		if (tasBakeBlock == null)
		{
			return false;
		}
		_active = tasBakeBlock;
		_driftReported = false;
		ResetEntityCaches();
		ResetCorrections(tasBakeBlock);
		_projValidMask = ((tick == tasBakeBlock.StartTick) ? (-1) : 0);
		_activeData = GetValidBake(tasBakeBlock);
		if (_activeData != null)
		{
			DetailText = "block '" + tasBakeBlock.FileName + "' (ticks " + tasBakeBlock.StartTick + "-" + (tasBakeBlock.EndTick - 1) + "): valid bake loaded";
			_plugin.LogInfo("Bake: block '" + tasBakeBlock.FileName + "' entered at tick " + tick + " with a valid bake (" + Path.GetFileName(_activeData.Path) + ", " + _activeData.TickCount + " ticks); " + (EnableBakedPlayback.Value ? "Enable Baked Playback is ON: baked state is applied every tick." : "Enable Baked Playback is OFF: the block plays live input only.") + ((tick != tasBakeBlock.StartTick) ? " Entered mid-block: projectiles are not followed." : string.Empty));
			return true;
		}
		if (tick != tasBakeBlock.StartTick)
		{
			SetMode(BakeBlockMode.Live);
			DetailText = "block '" + tasBakeBlock.FileName + "': entered mid-block with no valid bake; not recorded";
			return true;
		}
		_recordPath = SidecarPath(_scriptPath, tasBakeBlock);
		if (_recordPath.Length == 0)
		{
			SetMode(BakeBlockMode.Live);
			DetailText = "block '" + tasBakeBlock.FileName + "': save the script first; an unsaved script cannot be baked";
			_plugin.LogWarning("Bake: block '" + tasBakeBlock.FileName + "' is not recorded because the script has no file path.");
			return true;
		}
		_recBuffer.SetLength(0L);
		_recOffsets.Clear();
		_recSystemRandoms.Clear();
		_recording = true;
		s_runRecordedBake = true;
		SetMode(BakeBlockMode.Record);
		DetailText = "block '" + tasBakeBlock.FileName + "': recording " + tasBakeBlock.TickCount + " ticks";
		_plugin.LogInfo("Bake: recording block '" + tasBakeBlock.FileName + "' (ticks " + tasBakeBlock.StartTick + "-" + (tasBakeBlock.EndTick - 1) + ").");
		return true;
	}

	private void FinishBlock()
	{
		TasBakeBlock active = _active;
		if (_recording)
		{
			_recording = false;
			if (_recOffsets.Count == active.TickCount)
			{
				BakeBlockData bakeBlockData = new BakeBlockData
				{
					Path = _recordPath,
					Name = active.FileName,
					Hash = active.Hash,
					StartTick = active.StartTick,
					TickCount = active.TickCount,
					Offsets = _recOffsets.ToArray(),
					DataLength = (int)_recBuffer.Length,
					Version = 2,
					SystemRandoms = ((_recSystemRandoms.Count == active.TickCount) ? _recSystemRandoms.ToArray() : null)
				};
				bakeBlockData.Data = new byte[bakeBlockData.DataLength];
				Buffer.BlockCopy(_recBuffer.GetBuffer(), 0, bakeBlockData.Data, 0, bakeBlockData.DataLength);
				if (Save(bakeBlockData, out var error))
				{
					_loaded[active.FileName] = bakeBlockData;
					_missing.Remove(active.Hash);
					_plugin.Toast("Baked block '" + active.FileName + "' (" + active.TickCount + " ticks) to " + Path.GetFileName(_recordPath) + ".", error: false);
				}
				else
				{
					_plugin.Toast("Bake write failed for block '" + active.FileName + "': " + error, error: true);
				}
			}
			else
			{
				_plugin.LogWarning("Bake: block '" + active.FileName + "' recorded " + _recOffsets.Count + " of " + active.TickCount + " ticks; nothing written.");
			}
			_recBuffer.SetLength(0L);
			_recSystemRandoms.Clear();
			if (_recBuffer.Capacity > 8388608)
			{
				_recBuffer.Capacity = 1048576;
			}
		}
		LogCorrections(active, completed: true);
		_active = null;
		_activeData = null;
		SetMode(BakeBlockMode.None);
		DetailText = string.Empty;
	}

	private void SetMode(BakeBlockMode mode)
	{
		if (mode != _mode)
		{
			_mode = mode;
			switch (mode)
			{
			case BakeBlockMode.Record:
				StatusText = "[RECORDING BAKE]";
				break;
			case BakeBlockMode.Enforced:
				StatusText = "[BAKED - SYNCED - NOT LEGIT]";
				break;
			case BakeBlockMode.Verify:
				StatusText = (_driftReported ? "[VERIFY - DRIFT DETECTED]" : "[VERIFY - LIVE INPUT]");
				break;
			default:
				StatusText = "[LIVE INPUT]";
				break;
			}
		}
	}

	private BakeBlockData GetValidBake(TasBakeBlock block)
	{
		string reason;
		if (_loaded.TryGetValue(block.FileName, out var value))
		{
			if (string.Equals(value.Hash, block.Hash, StringComparison.Ordinal) && value.TickCount == block.TickCount)
			{
				if (Decode(value, out reason))
				{
					return value;
				}
				_plugin.LogWarning("Bake: block '" + block.FileName + "' could not be decoded (" + reason + "); the block will be re-recorded.");
				_loaded.Remove(block.FileName);
				_missing.Add(block.Hash);
				return null;
			}
			_loaded.Remove(block.FileName);
		}
		if (_missing.Contains(block.Hash))
		{
			return null;
		}
		string text = SidecarPath(_scriptPath, block);
		if (text.Length == 0)
		{
			_missing.Add(block.Hash);
			return null;
		}
		value = Load(text, block.Hash, out reason);
		if (value == null || value.TickCount != block.TickCount || !Decode(value, out reason))
		{
			if (value != null && value.TickCount != block.TickCount)
			{
				reason = "tick count " + value.TickCount + " does not match the block's " + block.TickCount;
			}
			if (!string.IsNullOrEmpty(reason))
			{
				_plugin.LogInfo("Bake: " + Path.GetFileName(text) + " is not used (" + reason + "); the block will be re-recorded.");
			}
			_missing.Add(block.Hash);
			return null;
		}
		value.StartTick = block.StartTick;
		if (value.Version < 2)
		{
			_plugin.LogWarning("Bake: " + Path.GetFileName(text) + " is format " + value.Version + " and only carries UnityEngine.Random: the System.Random seed stream is not applied inside or after this block. Force Re-Bake to record it.");
		}
		_loaded[block.FileName] = value;
		return value;
	}

	private void TrySkip(TasEngine engine, TasScript script)
	{
		IList<TasBakeBlock> bakeBlocks = script.BakeBlocks;
		for (int i = 0; i < bakeBlocks.Count; i++)
		{
			int currentTick = engine.CurrentTick;
			TasBakeBlock tasBakeBlock = null;
			for (int j = 0; j < bakeBlocks.Count; j++)
			{
				if (bakeBlocks[j].StartTick == currentTick)
				{
					tasBakeBlock = bakeBlocks[j];
					break;
				}
			}
			if (tasBakeBlock == null)
			{
				break;
			}
			BakeBlockData validBake = GetValidBake(tasBakeBlock);
			if (validBake == null || validBake.TickCount <= 0)
			{
				break;
			}
			int num = validBake.TickCount - 1;
			ResetEntityCaches();
			bool flag = false;
			try
			{
				flag = engine.ApplyPendingReseed();
				ApplyFrame(validBake, num, enforcedTick: false);
			}
			catch (Exception ex)
			{
				_plugin.LogWarning("Bake: skip of block '" + tasBakeBlock.FileName + "' failed: " + ex.Message);
				if (flag)
				{
					engine.RearmFirstTickReseed();
				}
				break;
			}
			finally
			{
				BeginCorrectionTick();
			}
			TickBakeFrame tickBakeFrame = validBake.Frames[num];
			if (!engine.BakeJumpTo(tasBakeBlock.EndTick, tickBakeFrame.Time, tickBakeFrame.Pitch, tickBakeFrame.Yaw))
			{
				if (flag)
				{
					engine.RearmFirstTickReseed();
				}
				break;
			}
			ResetRun();
			_lastTick = tasBakeBlock.EndTick - 1;
			StatusText = "[BAKED - SKIPPED TO END - NOT LEGIT]";
			DetailText = "skipped block '" + tasBakeBlock.FileName + "' to tick " + tasBakeBlock.EndTick;
			_plugin.LogInfo("Bake: skipped block '" + tasBakeBlock.FileName + "' to its last baked frame; live from tick " + tasBakeBlock.EndTick + ".");
			if (engine.Finished)
			{
				break;
			}
		}
	}

	public int ForceRebake(TasScript script, string scriptPath)
	{
		ResetRun();
		_loaded.Clear();
		_missing.Clear();
		if (script == null || string.IsNullOrEmpty(scriptPath))
		{
			return 0;
		}
		int num = 0;
		IList<TasBakeBlock> bakeBlocks = script.BakeBlocks;
		for (int i = 0; i < bakeBlocks.Count; i++)
		{
			string text = SidecarPath(scriptPath, bakeBlocks[i]);
			if (text.Length > 0 && Delete(text))
			{
				num++;
			}
		}
		return num;
	}

	public int CachedBlockCount(TasScript script)
	{
		if (script == null || script != _script)
		{
			return 0;
		}
		int num = 0;
		IList<TasBakeBlock> bakeBlocks = script.BakeBlocks;
		for (int i = 0; i < bakeBlocks.Count; i++)
		{
			if (_loaded.TryGetValue(bakeBlocks[i].FileName, out var value) && string.Equals(value.Hash, bakeBlocks[i].Hash, StringComparison.Ordinal))
			{
				num++;
			}
		}
		return num;
	}

	public static string SidecarPath(string scriptPath, TasBakeBlock block)
	{
		if (string.IsNullOrEmpty(scriptPath) || block == null)
		{
			return string.Empty;
		}
		try
		{
			string fullPath = Path.GetFullPath(scriptPath);
			string path = Path.GetDirectoryName(fullPath) ?? string.Empty;
			string path2 = SanitizeFileName(Path.GetFileNameWithoutExtension(fullPath)) + "-" + SanitizeFileName(block.FileName) + ".ukbake";
			return Path.Combine(path, path2);
		}
		catch
		{
			return string.Empty;
		}
	}

	private static string SanitizeFileName(string name)
	{
		if (string.IsNullOrEmpty(name))
		{
			return "block";
		}
		char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
		StringBuilder stringBuilder = new StringBuilder(name.Length);
		foreach (char c in name)
		{
			stringBuilder.Append((Array.IndexOf(invalidFileNameChars, c) >= 0 || c == ' ') ? '_' : c);
		}
		return stringBuilder.ToString();
	}

	public static BakeBlockData Load(string path, string expectedHash, out string reason)
	{
		reason = null;
		if (string.IsNullOrEmpty(path) || !File.Exists(path))
		{
			return null;
		}
		try
		{
			byte[] buffer;
			using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
			{
				using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress);
				using MemoryStream memoryStream = new MemoryStream();
				gZipStream.CopyTo(memoryStream);
				buffer = memoryStream.ToArray();
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(buffer, writable: false));
			if (binaryReader.ReadUInt32() != 1262635861)
			{
				reason = "not a .ukbake file";
				return null;
			}
			int num = binaryReader.ReadInt32();
			if (num < 1 || num > 2)
			{
				reason = "format version " + num + ", expected " + 1 + "-" + 2;
				return null;
			}
			BakeBlockData bakeBlockData = new BakeBlockData
			{
				Path = path,
				Version = num
			};
			bakeBlockData.Name = binaryReader.ReadString();
			bakeBlockData.Hash = binaryReader.ReadString();
			if (expectedHash != null && !string.Equals(bakeBlockData.Hash, expectedHash, StringComparison.Ordinal))
			{
				reason = "the script changed since it was baked (hash mismatch)";
				return null;
			}
			bakeBlockData.StartTick = binaryReader.ReadInt32();
			bakeBlockData.TickCount = binaryReader.ReadInt32();
			if (bakeBlockData.TickCount < 0 || bakeBlockData.TickCount > 16000000)
			{
				reason = "bad tick count";
				return null;
			}
			bakeBlockData.Offsets = new int[bakeBlockData.TickCount];
			for (int i = 0; i < bakeBlockData.TickCount; i++)
			{
				bakeBlockData.Offsets[i] = binaryReader.ReadInt32();
			}
			bakeBlockData.DataLength = binaryReader.ReadInt32();
			if (bakeBlockData.DataLength < 0)
			{
				reason = "bad data length";
				return null;
			}
			bakeBlockData.Data = binaryReader.ReadBytes(bakeBlockData.DataLength);
			if (bakeBlockData.Data.Length != bakeBlockData.DataLength)
			{
				reason = "file is truncated";
				return null;
			}
			for (int j = 0; j < bakeBlockData.TickCount; j++)
			{
				if (bakeBlockData.Offsets[j] < 0 || bakeBlockData.Offsets[j] >= bakeBlockData.DataLength)
				{
					reason = "bad frame offset";
					return null;
				}
			}
			return bakeBlockData;
		}
		catch (Exception ex)
		{
			reason = "could not be read: " + ex.Message;
			return null;
		}
	}

	public static bool Save(BakeBlockData data, out string error)
	{
		error = null;
		string text = data.Path + ".tmp";
		try
		{
			string directoryName = Path.GetDirectoryName(Path.GetFullPath(data.Path));
			if (!string.IsNullOrEmpty(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			using (FileStream stream = new FileStream(text, FileMode.Create, FileAccess.Write, FileShare.None))
			{
				using GZipStream output = new GZipStream(stream, CompressionLevel.Fastest);
				using BinaryWriter binaryWriter = new BinaryWriter(output);
				binaryWriter.Write(1262635861u);
				binaryWriter.Write(2);
				binaryWriter.Write(data.Name ?? string.Empty);
				binaryWriter.Write(data.Hash ?? string.Empty);
				binaryWriter.Write(data.StartTick);
				binaryWriter.Write(data.TickCount);
				for (int i = 0; i < data.TickCount; i++)
				{
					binaryWriter.Write(data.Offsets[i]);
				}
				binaryWriter.Write(data.DataLength);
				binaryWriter.Write(data.Data, 0, data.DataLength);
			}
			if (File.Exists(data.Path))
			{
				File.Replace(text, data.Path, null);
			}
			else
			{
				File.Move(text, data.Path);
			}
			return true;
		}
		catch (Exception ex)
		{
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			error = ex.Message;
			return false;
		}
	}

	public static bool Delete(string path)
	{
		try
		{
			if (string.IsNullOrEmpty(path) || !File.Exists(path))
			{
				return false;
			}
			File.Delete(path);
			return true;
		}
		catch
		{
			return false;
		}
	}

	private void RecordTick(int tick, double time)
	{
		BinaryWriter recWriter = _recWriter;
		_recOffsets.Add((int)_recBuffer.Position);
		recWriter.Write(tick);
		recWriter.Write(time);
		WriteRng(recWriter);
		RecordSystemRng(recWriter);
		WritePlayer(recWriter);
		CollectProjectiles();
		WriteProjectiles(recWriter);
		WriteEnemies(recWriter);
		WriteDoors(recWriter);
	}

	private static int TypeBit(int type)
	{
		if (type >= 31)
		{
			return int.MinValue;
		}
		return 1 << type;
	}

	private static bool Decode(BakeBlockData data, out string reason)
	{
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0275: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: 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_029a: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03db: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0413: Unknown result type (might be due to invalid IL or missing references)
		//IL_0418: Unknown result type (might be due to invalid IL or missing references)
		//IL_0421: Unknown result type (might be due to invalid IL or missing references)
		//IL_0426: Unknown result type (might be due to invalid IL or missing references)
		reason = null;
		if (data.Decoded)
		{
			return true;
		}
		try
		{
			int tickCount = data.TickCount;
			TickBakeFrame[] array = new TickBakeFrame[tickCount];
			List<float> list = new List<float>(tickCount * 4);
			List<BakeProjectile> list2 = new List<BakeProjectile>(tickCount * 4);
			List<BakeEnemy> list3 = new List<BakeEnemy>(tickCount * 4);
			List<byte> list4 = new List<byte>(tickCount * 4);
			List<byte> list5 = new List<byte>(tickCount * 2);
			HashSet<int> hashSet = new HashSet<int>();
			HashSet<int> hashSet2 = new HashSet<int>();
			int[] array2 = new int[32];
			int[] array3 = new int[32];
			using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(data.Data, 0, data.DataLength, writable: false)))
			{
				Stream baseStream = binaryReader.BaseStream;
				BakeProjectile item = default(BakeProjectile);
				BakeEnemy item2 = default(BakeEnemy);
				for (int i = 0; i < tickCount; i++)
				{
					baseStream.Position = data.Offsets[i];
					TickBakeFrame tickBakeFrame = new TickBakeFrame
					{
						Tick = binaryReader.ReadInt32(),
						Time = binaryReader.ReadDouble(),
						Rng0 = binaryReader.ReadInt32(),
						Rng1 = binaryReader.ReadInt32(),
						Rng2 = binaryReader.ReadInt32(),
						Rng3 = binaryReader.ReadInt32()
					};
					if (data.Version >= 2)
					{
						tickBakeFrame.HasSystemSeedStream = true;
						tickBakeFrame.SystemSeedStream = binaryReader.ReadInt32();
					}
					tickBakeFrame.HasPlayer = binaryReader.ReadByte() != 0;
					tickBakeFrame.ChargeStart = list.Count;
					if (tickBakeFrame.HasPlayer)
					{
						tickBakeFrame.PlayerPosition = ReadV3(binaryReader);
						tickBakeFrame.PlayerVelocity = ReadV3(binaryReader);
						tickBakeFrame.Pitch = binaryReader.ReadSingle();
						tickBakeFrame.Yaw = binaryReader.ReadSingle();
						tickBakeFrame.Health = binaryReader.ReadSingle();
						tickBakeFrame.HardDamage = binaryReader.ReadSingle();
						tickBakeFrame.Stamina = binaryReader.ReadSingle();
						tickBakeFrame.MoveFlags = binaryReader.ReadByte();
						tickBakeFrame.WeaponSlot = binaryReader.ReadInt32();
						tickBakeFrame.WeaponVariation = binaryReader.ReadInt32();
						tickBakeFrame.ChargeCount = binaryReader.ReadByte();
						for (int j = 0; j < tickBakeFrame.ChargeCount; j++)
						{
							list.Add(binaryReader.ReadSingle());
						}
					}
					tickBakeFrame.ProjectileStart = list2.Count;
					tickBakeFrame.ProjectileCount = ReadCount(binaryReader);
					for (int k = 0; k < array3.Length; k++)
					{
						array3[k] = 0;
					}
					hashSet2.Clear();
					int num = 0;
					for (int l = 0; l < tickBakeFrame.ProjectileCount; l++)
					{
						item.Key = binaryReader.ReadInt32();
						item.Type = binaryReader.ReadInt32();
						item.Position = ReadV3(binaryReader);
						item.Rotation = ReadQ(binaryReader);
						item.Velocity = ReadV3(binaryReader);
						item.AngularVelocity = ReadV3(binaryReader);
						item.Timer = binaryReader.ReadSingle();
						item.Hits = binaryReader.ReadInt32();
						item.Flags = binaryReader.ReadByte();
						list2.Add(item);
						int num2 = ((item.Type >= 0 && item.Type < 31) ? item.Type : 31);
						array3[num2]++;
						hashSet2.Add(item.Key);
						if (!hashSet.Contains(item.Key))
						{
							num |= TypeBit(num2);
						}
					}
					for (int m = 0; m < array3.Length; m++)
					{
						if (array3[m] != array2[m])
						{
							num |= TypeBit(m);
						}
					}
					tickBakeFrame.ProjectileChangeMask = num;
					HashSet<int> hashSet3 = hashSet;
					hashSet = hashSet2;
					hashSet2 = hashSet3;
					int[] array4 = array2;
					array2 = array3;
					array3 = array4;
					tickBakeFrame.EnemyStart = list3.Count;
					tickBakeFrame.EnemyCount = ReadCount(binaryReader);
					for (int n = 0; n < tickBakeFrame.EnemyCount; n++)
					{
						item2.Key = binaryReader.ReadInt32();
						item2.Type = binaryReader.ReadInt32();
						item2.Position = ReadV3(binaryReader);
						item2.Rotation = ReadQ(binaryReader);
						item2.Velocity = ReadV3(binaryReader);
						item2.Health = binaryReader.ReadSingle();
						item2.Flags = binaryReader.ReadByte();
						item2.NavDestination = ReadV3(binaryReader);
						item2.NavVelocity = ReadV3(binaryReader);
						int num3 = binaryReader.ReadByte();
						for (int num4 = 0; num4 < num3; num4++)
						{
							binaryReader.ReadSingle();
						}
						item2.StateHash = binaryReader.ReadInt32();
						item2.NormalizedTime = binaryReader.ReadSingle();
						list3.Add(item2);
					}
					tickBakeFrame.DoorStart = list4.Count;
					tickBakeFrame.DoorCount = ReadCount(binaryReader);
					for (int num5 = 0; num5 < tickBakeFrame.DoorCount; num5++)
					{
						list4.Add(binaryReader.ReadByte());
					}
					tickBakeFrame.RoomStart = list5.Count;
					tickBakeFrame.RoomCount = ReadCount(binaryReader);
					int num6 = tickBakeFrame.RoomCount + 7 >> 3;
					for (int num7 = 0; num7 < num6; num7++)
					{
						list5.Add(binaryReader.ReadByte());
					}
					array[i] = tickBakeFrame;
				}
			}
			data.Frames = array;
			data.Charges = list.ToArray();
			data.Projectiles = list2.ToArray();
			data.Enemies = list3.ToArray();
			data.DoorFlags = list4.ToArray();
			data.RoomBits = list5.ToArray();
			data.Decoded = true;
			data.Data = new byte[0];
			return true;
		}
		catch (Exception ex)
		{
			reason = "frame decode failed: " + ex.Message;
			return false;
		}
	}

	private static int ReadCount(BinaryReader r)
	{
		int num = r.ReadInt32();
		if (num < 0 || num > 16777216)
		{
			throw new InvalidDataException("bad entry count " + num);
		}
		return num;
	}

	private static void WriteV3(BinaryWriter w, Vector3 v)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		w.Write(v.x);
		w.Write(v.y);
		w.Write(v.z);
	}

	private static void WriteQ(BinaryWriter w, Quaternion q)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: 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)
		w.Write(q.x);
		w.Write(q.y);
		w.Write(q.z);
		w.Write(q.w);
	}

	private static Vector3 ReadV3(BinaryReader r)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		float num = r.ReadSingle();
		float num2 = r.ReadSingle();
		float num3 = r.ReadSingle();
		return new Vector3(num, num2, num3);
	}

	private static Quaternion ReadQ(BinaryReader r)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		float num = r.ReadSingle();
		float num2 = r.ReadSingle();
		float num3 = r.ReadSingle();
		float num4 = r.ReadSingle();
		return new Quaternion(num, num2, num3, num4);
	}

	private long BeginCount(BinaryWriter w)
	{
		long position = _recBuffer.Position;
		w.Write(0);
		return position;
	}

	private void PatchCount(BinaryWriter w, long at, int count)
	{
		long position = _recBuffer.Position;
		_recBuffer.Position = at;
		w.Write(count);
		_recBuffer.Position = position;
	}

	private void WriteRng(BinaryWriter w)
	{
		int s = 0;
		int s2 = 0;
		int s3 = 0;
		int s4 = 0;
		if (!_rngBroken)
		{
			try
			{
				ReadRngBits(out s, out s2, out s3, out s4);
			}
			catch (Exception ex)
			{
				_rngBroken = true;
				_plugin.LogWarning("Bake: Random.state cannot be read (" + ex.Message + "); RNG is not baked.");
			}
		}
		w.Write(s);
		w.Write(s2);
		w.Write(s3);
		w.Write(s4);
	}

	private static void ReadRngBits(out int s0, out int s1, out int s2, out int s3)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		RandomStateBits randomStateBits = new RandomStateBits
		{
			State = Random.state
		};
		s0 = randomStateBits.S0;
		s1 = randomStateBits.S1;
		s2 = randomStateBits.S2;
		s3 = randomStateBits.S3;
	}

	private static void WriteRngBits(int s0, int s1, int s2, int s3)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		RandomStateBits randomStateBits = new RandomStateBits
		{
			S0 = s0,
			S1 = s1,
			S2 = s2,
			S3 = s3
		};
		Random.state = randomStateBits.State;
	}

	private void RecordSystemRng(BinaryWriter w)
	{
		RngController rng = _plugin.Rng;
		w.Write(rng?.SystemSeedStream ?? 0);
		List<SystemRandomSnapshot> item = null;
		if (rng != null)
		{
			List<SystemRandomSnapshot> previous = ((_recSystemRandoms.Count > 0) ? _recSystemRandoms[_recSystemRandoms.Count - 1] : null);
			try
			{
				item = rng.CaptureSystemRandoms(previous);
			}
			catch (Exception ex)
			{
				if (!_systemRngWarned)
				{
					_systemRngWarned = true;
					_plugin.LogWarning("Bake: System.Random states cannot be captured (" + ex.Message + ").");
				}
			}
		}
		_recSystemRandoms.Add(item);
	}

	private void ApplySystemRng(BakeBlockData data, int index, ref TickBakeFrame f)
	{
		RngController rng = _plugin.Rng;
		if (rng == null)
		{
			return;
		}
		if (f.HasSystemSeedStream && rng.SystemSeedStream != f.SystemSeedStream)
		{
			rng.SystemSeedStream = f.SystemSeedStream;
			_tickRng++;
		}
		List<SystemRandomSnapshot>[] systemRandoms = data.SystemRandoms;
		if (systemRandoms == null || index < 0 || index >= systemRandoms.Length || systemRandoms[index] == null)
		{
			return;
		}
		try
		{
			rng.RestoreSystemRandoms(systemRandoms[index]);
		}
		catch (Exception ex)
		{
			if (!_systemRngWarned)
			{
				_systemRngWarned = true;
				_plugin.LogWarning("Bake: System.Random states cannot be restored (" + ex.Message + ").");
			}
		}
	}

	private bool EnsurePlayer()
	{
		Component playerComponent = _bridge.PlayerComponent;
		if ((Object)(object)playerComponent == (Object)null)
		{
			_player = null;
			return false;
		}
		if (playerComponent != _player)
		{
			if (_player != null)
			{
				_enemiesCached = false;
				_doorsCached = false;
				if (_projKeys.Count > 0)
				{
					_projValidMask = 0;
				}
				_projKeys.Clear();
				for (int i = 0; i < _projNextOrdinal.Length; i++)
				{
					_projNextOrdinal[i] = 0;
				}
				ClearLiveProjectiles();
			}
			_player = playerComponent;
			_playerTransform = playerComponent.transform;
			_playerBody = playerComponent.GetComponent<Rigidbody>();
			Type type = ((object)playerComponent).GetType();
			_fHp = NamedField(type, "hp", "health", "currentHealth");
			_fAntiHp = NamedField(type, "antiHp", "antiHP", "hardDamage");
			_fBoostCharge = NamedField(type, "boostCharge", "stamina");
			_fSliding = NamedField(type, "sliding");
			_fJumping = NamedField(type, "jumping");
			_fDashing = NamedField(type, "boost");
			_fGroundCheck = NamedField(type, "gc");
			_fOnGround = null;
			_groundCheckType = null;
			_chargesSearched = false;
		}
		object cameraController = _bridge.CameraController;
		if (cameraController != _camera)
		{
			_camera = cameraController;
			_fRotX = ((cameraController != null) ? NamedField(cameraController.GetType(), "rotationX") : null);
			_fRotY = ((cameraController != null) ? NamedField(cameraController.GetType(), "rotationY") : null);
		}
		object gunControl = _bridge.GunControl;
		if (gunControl != _gun)
		{
			_gun = gunControl;
			_fSlot = ((gunControl != null) ? NamedField(gunControl.GetType(), "currentSlotIndex") : null);
			_fVariation = ((gunControl != null) ? NamedField(gunControl.GetType(), "currentVariationIndex") : null);
		}
		if (!_chargesSearched || ((Object)(object)_charges == (Object)null && _charges != null))
		{
			_chargesSearched = true;
			_charges = null;
			_chargeFields = new FieldAccess[0];
			if (_chargesType == null)
			{
				_chargesType = _bridge.FindType("WeaponCharges");
			}
			if (_chargesType != null)
			{
				ref Component charges = ref _charges;
				Object obj = Object.FindObjectOfType(_chargesType);
				charges = (Component)(object)((obj is Component) ? obj : null);
				if ((Object)(object)_charges != (Object)null)
				{
					_chargeFields = FloatFields(_chargesType);
				}
			}
		}
		return true;
	}

	private void WritePlayer(BinaryWriter w)
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		if (!EnsurePlayer())
		{
			w.Write((byte)0);
			return;
		}
		w.Write((byte)1);
		Component player = _player;
		WriteV3(w, player.transform.position);
		WriteV3(w, ((Object)(object)_playerBody != (Object)null && !_playerBody.isKinematic) ? _playerBody.velocity : Vector3.zero);
		w.Write((_camera != null) ? (0f - GetFloat(_fRotX, _camera)) : 0f);
		w.Write((_camera != null) ? GetFloat(_fRotY, _camera) : 0f);
		w.Write(GetFloat(_fHp, player));
		w.Write(GetFloat(_fAntiHp, player));
		w.Write(GetFloat(_fBoostCharge, player));
		w.Write(ReadMoveFlags(player));
		w.Write((_gun != null) ? GetInt(_fSlot, _gun) : (-1));
		w.Write((_gun != null) ? GetInt(_fVariation, _gun) : (-1));
		int num = (((Object)(object)_charges != (Object)null) ? Math.Min(255, _chargeFields.Length) : 0);
		w.Write((byte)num);
		for (int i = 0; i < num; i++)
		{
			w.Write(GetFloat(_chargeFields[i], _charges));
		}
	}

	private byte ReadMoveFlags(Component player)
	{
		byte b = 0;
		if (_fGroundCheck != null)
		{
			object value = _fGroundCheck.GetValue(player);
			if (value != null)
			{
				Type type = value.GetType();
				if ((object)type != _groundCheckType)
				{
					_groundCheckType = type;
					_fOnGround = NamedField(type, "onGround");
				}
				if (GetBool(_fOnGround, value))
				{
					b |= 1;
				}
			}
		}
		if (GetBool(_fSliding, player))
		{
			b |= 2;
		}
		if (GetBool(_fJumping, player))
		{
			b |= 4;
		}
		if (GetBool(_fDashing, player))
		{
			b |= 8;
		}
		return b;
	}

	private void ApplyPlayer(BakeBlockData data, ref TickBakeFrame f)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: 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)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		if (!f.HasPlayer || !EnsurePlayer())
		{
			return;
		}
		Component player = _player;
		Transform val = _playerTransform;
		if ((Object)(object)val == (Object)null)
		{
			val = (_playerTransform = player.transform);
		}
		Vector3 val2 = val.position - f.PlayerPosition;
		if (((Vector3)(ref val2)).sqrMagnitude > _thresholdSq)
		{
			val.position = f.PlayerPosition;
			if ((Object)(object)_playerBody != (Object)null)
			{
				_playerBody.position = f.PlayerPosition;
			}
			_tickPlayer++;
		}
		if ((Object)(object)_playerBody != (Object)null && !_playerBody.isKinematic)
		{
			val2 = _playerBody.velocity - f.PlayerVelocity;
			if (((Vector3)(ref val2)).sqrMagnitude > _thresholdSq)
			{
				_playerBody.velocity = f.PlayerVelocity;
				_tickPlayer++;
			}
		}
		if (_camera != null && _fRotX != null && _fRotY != null)
		{
			if (Math.Abs(0f - GetFloat(_fRotX, _camera) - f.Pitch) > 1E-06f)
			{
				SetFloat(_fRotX, _camera, 0f - f.Pitch);
				_tickPlayer++;
			}
			if (Math.Abs(GetFloat(_fRotY, _camera) - f.Yaw) > 1E-06f)
			{
				SetFloat(_fRotY, _camera, f.Yaw);
				_tickPlayer++;
			}
		}
		if (_fHp != null && Math.Abs(GetFloat(_fHp, player) - f.Health) > 1E-06f)
		{
			SetFloat(_fHp, player, f.Health);
			_tickPlayer++;
		}
		if (_fAntiHp != null && Math.Abs(GetFloat(_fAntiHp, player) - f.HardDamage) > 1E-06f)
		{
			SetFloat(_fAntiHp, player, f.HardDamage);
			_tickPlayer++;
		}
		if (_fBoostCharge != null && Math.Abs(GetFloat(_fBoostCharge, player) - f.Stamina) > 1E-06f)
		{
			SetFloat(_fBoostCharge, player, f.Stamina);
			_tickPlayer++;
		}
		if (!((Object)(object)_charges != (Object)null))
		{
			return;
		}
		int num = Math.Min(f.ChargeCount, _chargeFields.Length);
		float[] charges = data.Charges;
		for (int i = 0; i < num; i++)
		{
			float num2 = charges[f.ChargeStart + i];
			if (Math.Abs(GetFloat(_chargeFields[i], _charges) - num2) > 1E-06f)
			{
				SetFloat(_chargeFields[i], _charges, num2);
				_tickPlayer++;
			}
		}
	}

	private static int ComparePending(PendingProjectile a, PendingProjectile b)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		if (a.Type != b.Type)
		{
			return a.Type.CompareTo(b.Type);
		}
		int num = a.Position.x.CompareTo(b.Position.x);
		if (num != 0)
		{
			return num;
		}
		num = a.Position.y.CompareTo(b.Position.y);
		if (num != 0)
		{
			return num;
		}
		return a.Position.z.CompareTo(b.Position.z);
	}

	private void EnsureProjectileTypes()
	{
		if (_projTypes != null)
		{
			return;
		}
		string[] bakeProjectileTypeNames = SaveStateManager.BakeProjectileTypeNames;
		_projTypes = new Type[bakeProjectileTypeNames.Length];
		_projTimer = new FieldAccess[bakeProjectileTypeNames.Length];
		_projHits = new FieldAccess[bakeProjectileTypeNames.Length];
		_projShot = new FieldAccess[bakeProjectileTypeNames.Length];
		_projSplit = new FieldAccess[bakeProjectileTypeNames.Length];
		_projNextOrdinal = new int[bakeProjectileTypeNames.Length];
		for (int i = 0; i < bakeProjectileTypeNames.Length; i++)
		{
			Type type = _bridge.FindType(bakeProjectileTypeNames[i]);
			_projTypes[i] = type;
			if (!(type == null))
			{
				bool flag = bakeProjectileTypeNames[i] == "Coin";
				if (flag)
				{
					_coinType = i;
				}
				_projTimer[i] = NamedField(type, flag ? CoinState.TimerNames : ProjectileTimerNames);
				_projHits[i] = NamedField(type, flag ? CoinState.HitNames : ProjectileHitNames);
				_projShot[i] = NamedField(type, CoinState.ShotNames);
				_projSplit[i] = (flag ? NamedField(type, CoinState.SplitNames) : null);
			}
		}
		for (int j = 0; j < _projTypes.Length; j++)
		{
			if (_projTypes[j] == null)
			{
				_retryProjectileTypes = true;
				break;
			}
		}
	}

	private void CollectProjectiles()
	{
		//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)
		EnsureProjectileTypes();
		_liveProjCount = 0;
		_projRoots.Clear();
		_pending.Clear();
		for (int i = 0; i < _projTypes.Length; i++)
		{
			Type type = _projTypes[i];
			if (type == null)
			{
				continue;
			}
			Object[] array;
			try
			{
				array = Object.FindObjectsOfType(type);
			}
			catch
			{
				continue;
			}
			foreach (Object obj2 in array)
			{
				Component val = (Component)(object)((obj2 is Component) ? obj2 : null);
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				GameObject gameObject = val.gameObject;
				if (!gameObject.activeInHierarchy || SaveStateManager.IsTemplateClone(gameObject))
				{
					continue;
				}
				int instanceID = ((Object)gameObject).GetInstanceID();
				if (_projRoots.Add(instanceID))
				{
					if (_projKeys.TryGetValue(instanceID, out var value))
					{
						AddLiveProjectile(val, value, i);
						continue;
					}
					_pending.Add(new PendingProjectile
					{
						Component = val,
						Type = i,
						Id = instanceID,
						Position = gameObject.transform.position
					});
				}
			}
		}
		if (_pending.Count > 1)
		{
			_pending.Sort(PendingOrder);
		}
		for (int k = 0; k < _pending.Count; k++)
		{
			PendingProjectile pendingProjectile = _pending[k];
			int num = (pendingProjectile.Type << 20) | (_projNextOrdinal[pendingProjectile.Type]++ & 0xFFFFF);
			_projKeys[pendingProjectile.Id] = num;
			AddLiveProjectile(pendingProjectile.Component, num, pendingProjectile.Type);
		}
		_pending.Clear();
	}

	private void AddLiveProjectile(Component component, int key, int type)
	{
		if (_liveProjCount == _liveProj.Length)
		{
			int newSize = _liveProj.Length * 2;
			Array.Resize(ref _liveProj, newSize);
			Array.Resize(ref _liveProjObject, newSize);
			Array.Resize(ref _liveProjTransform, newSize);
			Array.Resize(ref _liveProjBody, newSize);
			Array.Resize(ref _liveProjKey, newSize);
			Array.Resize(ref _liveProjType, newSize);
		}
		_liveProj[_liveProjCount] = component;
		_liveProjObject[_liveProjCount] = component.gameObject;
		_liveProjTransform[_liveProjCount] = component.transform;
		_liveProjBody[_liveProjCount] = component.GetComponent<Rigidbody>();
		_liveProjKey[_liveProjCount] = key;
		_liveProjType[_liveProjCount] = type;
		_liveProjCount++;
	}

	private void ClearLiveProjectiles()
	{
		_liveProjCount = 0;
		Array.Clear(_liveProj, 0, _liveProj.Length);
		Array.Clear(_liveProjObject, 0, _liveProjObject.Length);
		Array.Clear(_liveProjTransform, 0, _liveProjTransform.Length);
		Array.Clear(_liveProjBody, 0, _liveProjBody.Length);
		_slotByKey.Clear();
		_projFullScanPending = true;
	}

	private int CoinMask()
	{
		EnsureProjectileTypes();
		if (_coinType < 0)
		{
			return 0;
		}
		return TypeBit(_coinType);
	}

	private void TrackProjectiles(BakeBlockData data, int index, int forceMask)
	{
		if (_projValidMask == 0)
		{
			return;
		}
		EnsureProjectileTypes();
		ref TickBakeFrame reference = ref data.Frames[index];
		int num = forceMask | reference.ProjectileChangeMask;
		if (_projFullScanPending)
		{
			num = -1;
			_projFullScanPending = false;
		}
		BakeProjectile[] projectiles = data.Projectiles;
		int num2 = reference.ProjectileStart + reference.ProjectileCount;
		for (int i = reference.ProjectileStart; i < num2; i++)
		{
			int type = projectiles[i].Type;
			if (type >= 0 && type < _projNextOrdinal.Length && (projectiles[i].Key & 0xFFFFF) >= _projNextOrdinal[type])
			{
				num |= TypeBit(type);
			}
		}
		num &= _projValidMask;
		if (num == 0)
		{
			return;
		}
		bool flag = false;
		for (int j = 0; j < _projTypes.Length; j++)
		{
			if ((num & TypeBit(j)) != 0 && _projTypes[j] != null)
			{
				RescanProjectileType(j);
				flag = true;
			}
		}
		if (flag)
		{
			_slotByKey.Clear();
			for (int k = 0; k < _liveProjCount; k++)
			{
				_slotByKey[_liveProjKey[k]] = k;
			}
		}
	}

	private void RescanProjectileType(int t)
	{
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		_projRescans++;
		int num = 0;
		for (int i = 0; i < _liveProjCount; i++)
		{
			if (_liveProjType[i] != t)
			{
				if (num != i)
				{
					_liveProj[num] = _liveProj[i];
					_liveProjObject[num] = _liveProjObject[i];
					_liveProjTransform[num] = _liveProjTransform[i];
					_liveProjBody[num] = _liveProjBody[i];
					_liveProjKey[num] = _liveProjKey[i];
					_liveProjType[num] = _liveProjType[i];
				}
				num++;
			}
		}
		for (int j = num; j < _liveProjCount; j++)
		{
			_liveProj[j] = null;
			_liveProjObject[j] = null;
			_liveProjTransform[j] = null;
			_liveProjBody[j] = null;
		}
		_liveProjCount = num;
		Object[] array;
		try
		{
			array = Object.FindObjectsOfType(_projTypes[t]);
		}
		catch
		{
			return;
		}
		_scanRoots.Clear();
		_pending.Clear();
		foreach (Object obj2 in array)
		{
			Component val = (Component)(object)((obj2 is Component) ? obj2 : null);
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			GameObject gameObject = val.gameObject;
			if (!gameObject.activeInHierarchy)
			{
				continue;
			}
			int instanceID = ((Object)gameObject).GetInstanceID();
			if (!_scanRoots.Add(instanceID))
			{
				continue;
			}
			if (_projKeys.TryGetValue(instanceID, out var value))
			{
				if (value >> 20 == t)
				{
					AddLiveProjectile(val, value, t);
				}
			}
			else if (!SaveStateManager.IsTemplateClone(gameObject) && !ClaimedByLowerType(gameObject, t))
			{
				_pending.Add(new PendingProjectile
				{
					Component = val,
					Type = t,
					Id = instanceID,
					Position = gameObject.transform.position
				});
			}
		}
		if (_pending.Count > 1)
		{
			_pending.Sort(PendingComparer);
		}
		for (int l = 0; l < _pending.Count; l++)
		{
			PendingProjectile pendingProjectile = _pending[l];
			int num2 = (t << 20) | (_projNextOrdinal[t]++ & 0xFFFFF);
			_projKeys[pendingProjectile.Id] = num2;
			AddLiveProjectile(pendingProjectile.Component, num2, t);
		}
		_pending.Clear();
	}

	private bool ClaimedByLowerType(GameObject root, int t)
	{
		for (int i = 0; i < t; i++)
		{
			if (_projTypes[i] != null && (Object)(object)root.GetComponent(_projTypes[i]) != (Object)null)
			{
				return true;
			}
		}
		return false;
	}

	private void WriteProjectiles(BinaryWriter w)
	{
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		w.Write(_liveProjCount);
		for (int i = 0; i < _liveProjCount; i++)
		{
			Component target = _liveProj[i];
			int num = _liveProjType[i];
			Transform val = _liveProjTransform[i];
			Rigidbody val2 = _liveProjBody[i];
			bool flag = (Object)(object)val2 != (Object)null && !val2.isKinematic;
			w.Write(_liveProjKey[i]);
			w.Write(num);
			WriteV3(w, val.position);
			WriteQ(w, val.rotation);
			WriteV3(w, flag ? val2.velocity : Vector3.zero);
			WriteV3(w, flag ? val2.angularVelocity : Vector3.zero);
			w.Write(GetFloat(_projTimer[num], target));
			w.Write(GetInt(_projHits[num], target));
			byte b = 0;
			if (GetBool(_projShot[num], target))
			{
				b |= 1;
			}
			if (GetBool(_projSplit[num], target))
			{
				b |= 2;
			}
			w.Write(b);
		}
	}

	private void ApplyProjectiles(BakeBlockData data, ref TickBakeFrame f)
	{
		//IL_00bc: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_020a: Unknown result type (might be due to invalid IL or missing references)
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_022e: Unknown result type (might be due to invalid IL or missing references)
		if (_projValidMask == 0 || _liveProjCount == 0)
		{
			return;
		}
		BakeProjectile[] projectiles = data.Projectiles;
		int num = f.ProjectileStart + f.ProjectileCount;
		for (int i = f.ProjectileStart; i < num; i++)
		{
			int type = projectiles[i].Type;
			if (type < 0 || type >= _projTypes.Length || (_projValidMask & TypeBit(type)) == 0 || !_slotByKey.TryGetValue(projectiles[i].Key, out var value))
			{
				continue;
			}
			Component val = _liveProj[value];
			if ((Object)(object)val == (Object)null || !_liveProjObject[value].activeInHierarchy)
			{
				continue;
			}
			Transform val2 = _liveProjTransform[value];
			Vector3 val3 = val2.position - projectiles[i].Position;
			if (((Vector3)(ref val3)).sqrMagnitude > _thresholdSq)
			{
				val2.position = projectiles[i].Position;
				_tickProjectiles++;
			}
			if (Quaternion.Dot(val2.rotation, projectiles[i].Rotation) < 0.9999999f)
			{
				val2.rotation = projectiles[i].Rotation;
				_tickProjectiles++;
			}
			Rigidbody val4 = _liveProjBody[value];
			if ((Object)(object)val4 != (Object)null && !val4.isKinematic)
			{
				val3 = val4.position - projectiles[i].Position;
				if (((Vector3)(ref val3)).sqrMagnitude > _thresholdSq)
				{
					val4.position = projectiles[i].Position;
					_tickProjectiles++;
				}
				val3 = val4.velocity - projectiles[i].Velocity;
				if (((Vector3)(ref val3)).sqrMagnitude > _thresholdSq)
				{
					val4.velocity = projectiles[i].Velocity;
					_tickProjectiles++;
				}
				val3 = val4.angularVelocity - projectiles[i].AngularVelocity;
				if (((Vector3)(ref val3)).sqrMagnitude > _thresholdSq)
				{
					val4.angularVelocity = projectiles[i].AngularVelocity;
					_tickProjectiles++;
				}
			}
			FieldAccess fieldAccess = _projTimer[type];
			if (fieldAccess != null && Math.Abs(fieldAccess.GetFloat(val) - projectiles[i].Timer) > 1E-06f)
			{
				fieldAccess.SetFloat(val, projectiles[i].Timer);
				_tickProjectiles++;
			}
			FieldAccess fieldAccess2 = _projHits[type];
			if (fieldAccess2 != null && fieldAccess2.GetInt(val) != projectiles[i].Hits)
			{
				fieldAccess2.SetFloat(val, projectiles[i].Hits);
				_tickProjectiles++;
			}
			bool flag = (projectiles[i].Flags & 1) != 0;
			FieldAccess fieldAccess3 = _projShot[type];
			if (fieldAccess3 != null && fieldAccess3.GetBool(val) != flag)
			{
				fieldAccess3.SetBool(val, flag);
				_tickProjectiles++;
			}
			bool flag2 = (projectiles[i].Flags & 2) != 0;
			FieldAccess fieldAccess4 = _projSplit[type];
			if (fieldAccess4 != null && fieldAccess4.GetBool(val) != flag2)
			{
				fieldAccess4.SetBool(val, flag2);
				_tickProjectiles++;
			}
		}
	}

	private void EnsureEnemies()
	{
		if (_enemiesCached)
		{
			return;
		}
		_enemiesCached = true;
		EntityRegistry entities = _bridge.Entities;
		int levelCount = entities.LevelCount;
		_enemySlotById = new int[levelCount + 1];
		for (int i = 0; i < _enemySlotById.Length; i++)
		{
			_enemySlotById[i] = -1;
		}
		List<EntityRegistry.Entity> list = new List<EntityRegistry.Entity>(64);
		for (int j = 1; j <= levelCount; j++)
		{
			EntityRegistry.Entity entity = entities.Find(j);
			if (entity != null && entity.Category == "enemy" && GameBridge.IsAlive(entity.Component) && !SaveStateManager.IsTemplateClone(entity.Component.gameObject))
			{
				list.Add(entity);
			}
		}
		_enemyCount = list.Count;
		_enemyIds = new int[_enemyCount];
		_enemyComps = (Component[])(object)new Component[_enemyCount];
		_enemyBodies = (Rigidbody[])(object)new Rigidbody[_enemyCount];
		_enemyAgents = (NavMeshAgent[])(object)new NavMeshAgent[_enemyCount];
		_enemyAnimators = (Animator[])(object)new Animator[_enemyCount];
		_enemyTypes = new int[_enemyCount];
		_enemyHealth = new FieldAccess[_enemyCount];
		_enemyDead = new FieldAccess[_enemyCount];
		_enemyObjects = (GameObject[])(object)new GameObject[_enemyCount];
		_enemyTransforms = (Transform[])(object)new Transform[_enemyCount];
		for (int k = 0; k < _enemyCount; k++)
		{
			Component component = list[k].Component;
			GameObject gameObject = component.gameObject;
			_enemyIds[k] = list[k].Id;
			_enemyComps[k] = component;
			_enemyObjects[k] = gameObject;
			_enemyTransforms[k] = component.transform;
			_enemyBodies[k] = gameObject.GetComponent<Rigidbody>();
			_enemyAgents[k] = gameObject.GetComponent<NavMeshAgent>();
			Animator component2 = gameObject.GetComponent<Animator>();
			_enemyAnimators[k] = (((Object)(object)component2 != (Object)null) ? component2 : gameObject.GetComponentInChildren<Animator>(true));
			_enemyTypes[k] = GameBridge.ToInt(_bridge.GetMember(component, EnemyTypeNames), -1);
			Type type = ((object)component).GetType();
			_enemyHealth[k] = NamedField(type, EnemyHealthNames);
			_enemyDead[k] = NamedField(type, EnemyDeadNames);
			int id = list[k].Id;
			if (id >= 0 && id < _enemySlotById.Length && _enemySlotById[id] < 0)
			{
				_enemySlotById[id] = k;
			}
		}
	}

	private void WriteEnemies(BinaryWriter w)
	{
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0185: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: 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)
		EnsureEnemies();
		long at = BeginCount(w);
		int num = 0;
		for (int i = 0; i < _enemyCount; i++)
		{
			Component val = _enemyComps[i];
			if (GameBridge.IsAlive(val) && val.gameObject.activeInHierarchy)
			{
				Transform transform = val.transform;
				Rigidbody val2 = _enemyBodies[i];
				NavMeshAgent val3 = _enemyAgents[i];
				bool flag = (Object)(object)val3 != (Object)null && ((Behaviour)val3).isActiveAndEnabled && val3.isOnNavMesh;
				Vector3 v = (((Object)(object)val2 != (Object)null && !val2.isKinematic) ? val2.velocity : (flag ? val3.velocity : Vector3.zero));
				byte b = 0;
				if (GetBool(_enemyDead[i], val))
				{
					b |= 1;
				}
				Vector3 v2 = Vector3.zero;
				Vector3 v3 = Vector3.zero;
				if (flag)
				{
					b |= 2;
					v2 = val3.destination;
					v3 = val3.velocity;
				}
				int value = 0;
				float value2 = 0f;
				Animator val4 = _enemyAnimators[i];
				if ((Object)(object)val4 != (Object)null && ((Behaviour)val4).isActiveAndEnabled && (Object)(object)val4.runtimeAnimatorController != (Object)null && val4.layerCount > 0)
				{
					b |= 4;
					AnimatorStateInfo currentAnimatorStateInfo = val4.GetCurrentAnimatorStateInfo(0);
					value = ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash;
					value2 = ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime;
				}
				w.Write(_enemyIds[i]);
				w.Write(_enemyTypes[i]);
				WriteV3(w, transform.position);
				WriteQ(w, transform.rotation);
				WriteV3(w, v);
				w.Write(GetFloat(_enemyHealth[i], val));
				w.Write(b);
				WriteV3(w, v2);
				WriteV3(w, v3);
				w.Write((byte)0);
				w.Write(value);
				w.Write(value2);
				num++;
			}
		}
		PatchCount(w, at, num);
	}

	private void ApplyEnemies(BakeBlockData data, ref TickBakeFrame f)
	{
		//IL_0098: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0222: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: 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)
		//IL_011f: 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)
		//IL_014d: 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_0137: 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_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_027d: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_0297: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_035a: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Unknown result type (might be due to invalid IL or missing references)
		EnsureEnemies();
		BakeEnemy[] enemies = data.Enemies;
		int num = f.EnemyStart + f.EnemyCount;
		for (int i = f.EnemyStart; i < num; i++)
		{
			int key = enemies[i].Key;
			if (key < 0 || key >= _enemySlotById.Length)
			{
				continue;
			}
			int num2 = _enemySlotById[key];
			if (num2 < 0)
			{
				continue;
			}
			Component val = _enemyComps[num2];
			if ((Object)(object)val == (Object)null || !_enemyObjects[num2].activeInHierarchy)
			{
				continue;
			}
			Transform val2 = _enemyTransforms[num2];
			Vector3 position = enemies[i].Position;
			Vector3 val3 = val2.position - position;
			float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
			bool flag = sqrMagnitude > _thresholdSq;
			NavMeshAgent val4 = (((enemies[i].Flags & 2) != 0) ? _enemyAgents[num2] : null);
			if ((Object)(object)val4 != (Object)null && ((Behaviour)val4).isActiveAndEnabled && val4.isOnNavMesh)
			{
				val3 = val4.destination - enemies[i].NavDestination;
				if (((Vector3)(ref val3)).sqrMagnitude > 0.0001f || (flag && !MoveAgentDirect(val4, val2, position, sqrMagnitude)))
				{
					SaveStateManager.BakeRestoreAgent(val4, position, enemies[i].NavDestination, enemies[i].NavVelocity);
					_tickNavRepaths++;
					_tickEnemies++;
				}
				else
				{
					if (flag)
					{
						_tickEnemies++;
					}
					val3 = val4.velocity - enemies[i].NavVelocity;
					if (((Vector3)(ref val3)).sqrMagnitude > _thresholdSq)
					{
						val4.velocity = enemies[i].NavVelocity;
						_tickEnemies++;
					}
				}
			}
			else if (flag)
			{
				val2.position = position;
				_tickEnemies++;
			}
			if (Quaternion.Dot(val2.rotation, enemies[i].Rotation) < 0.9999999f)
			{
				val2.rotation = enemies[i].Rotation;
				_tickEnemies++;
			}
			Rigidbody val5 = _enemyBodies[num2];
			if ((Object)(object)val5 != (Object)null && !val5.isKinematic)
			{
				if (flag)
				{
					val5.position = position;
				}
				val3 = val5.velocity - enemies[i].Velocity;
				if (((Vector3)(ref val3)).sqrMagnitude > _thresholdSq)
				{
					val5.velocity = enemies[i].Velocity;
					_tickEnemies++;
				}
			}
			FieldAccess fieldAccess = _enemyHealth[num2];
			if (fieldAccess != null && Math.Abs(fieldAccess.GetFloat(val) - enemies[i].Health) > 1E-06f)
			{
				fieldAccess.SetFloat(val, enemies[i].Health);
				_tickEnemies++;
			}
			if ((enemies[i].Flags & 4) == 0 || enemies[i].StateHash == 0)
			{
				continue;
			}
			Animator val6 = _enemyAnimators[num2];
			if ((Object)(object)val6 != (Object)null && ((Behaviour)val6).isActiveAndEnabled && (Object)(object)val6.runtimeAnimatorController != (Object)null)
			{
				AnimatorStateInfo currentAnimatorStateInfo = val6.GetCurrentAnimatorStateInfo(0);
				if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash != enemies[i].StateHash || Math.Abs(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime - enemies[i].NormalizedTime) > 0.0001f)
				{
					val6.Play(enemies[i].StateHash, 0, enemies[i].NormalizedTime);
					_tickEnemies++;
				}
			}
		}
	}

	private static bool MoveAgentDirect(NavMeshAgent agent, Transform transform, Vector3 position, float driftSq)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: 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_003d: 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)
		if (driftSq > 1f)
		{
			return false;
		}
		try
		{
			agent.nextPosition = position;
			Vector3 val = agent.nextPosition - position;
			if (((Vector3)(ref val)).sqrMagnitude > 1E-10f)
			{
				return false;
			}
			val = transform.position - position;
			if (((Vector3)(ref val)).sqrMagnitude > 1E-10f)
			{
				transform.position = position;
			}
			return true;
		}
		catch
		{
			return false;
		}
	}

	private void EnsureDoors()
	{
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		if (_doorsCached)
		{
			return;
		}
		_doorsCached = true;
		_doors = (Component[])(object)new Component[0];
		_rooms = (GameObject[])(object)new GameObject[0];
		Type type = _bridge.FindType("Door");
		if (type == null)
		{
			return;
		}
		Object[] array;
		try
		{
			array = Object.FindObjectsOfType(type, true);
		}
		catch
		{
			return;
		}
		List<KeyValuePair<string, Component>> list = new List<KeyValuePair<string, Component>>(array.Length);
		foreach (Object obj2 in array)
		{
			Component val = (Component)(object)((obj2 is Component) ? obj2 : null);
			if (!((Object)(object)val == (Object)null))
			{
				Scene scene = val.gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && !SaveStateManager.IsTemplateClone(val.gameObject))
				{
					list.Add(new KeyValuePair<string, Component>(HierarchyKey(val), val));
				}
			}
		}
		list.Sort((KeyValuePair<string, Component> a, KeyValuePair<string, Component> b) => string.CompareOrdinal(a.Key, b.Key));
		_doors = (Component[])(object)new Component[list.Count];
		_doorOpen = new FieldAccess[list.Count];
		_doorLocked = new FieldAccess[list.Count];
		List<GameObject> list2 = new List<GameObject>(32);
		HashSet<int> seen = new HashSet<int>();
		for (int num = 0; num < list.Count; num++)
		{
			Component value = list[num].Value;
			_doors[num] = value;
			Type type2 = ((object)value).GetType();
			_doorOpen[num] = NamedField(type2, "open");
			_doorLocked[num] = NamedField(type2, "locked");
			AddRooms(_bridge.GetMember(value, new string[1] { "activatedRooms" }) as GameObject[], list2, seen);
			AddRooms(_bridge.GetMember(value, new string[1] { "deactivatedRooms" }) as GameObject[], list2, seen);
		}
		_rooms = list2.ToArray();
	}

	private static void AddRooms(GameObject[] list, List<GameObject> into, HashSet<int> seen)
	{
		if (list == null)
		{
			return;
		}
		for (int i = 0; i < list.Length; i++)
		{
			if ((Object)(object)list[i] != (Object)null && seen.Add(((Object)list[i]).GetInstanceID()))
			{
				into.Add(list[i]);
			}
		}
	}

	private static string HierarchyKey(Component component)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		StringBuilder stringBuilder = new StringBuilder(64);
		Scene scene = component.gameObject.scene;
		stringBuilder.Append(((Scene)(ref scene)).name).Append('|');
		List<int> list = new List<int>(16);
		Transform val = component.transform;
		while ((Object)(object)val != (Object)null)
		{
			list.Add(val.GetSiblingIndex());
			val = val.parent;
		}
		for (int num = list.Count - 1; num >= 0; num--)
		{
			stringBuilder.Append(list[num].ToString("D6", CultureInfo.InvariantCulture)).Append('/');
		}
		return stringBuilder.ToString();
	}

	private void WriteDoors(BinaryWriter w)
	{
		EnsureDoors();
		w.Write(_doors.Length);
		for (int i = 0; i < _doors.Length; i++)
		{
			Component val = _doors[i];
			byte b = 0;
			if (GameBridge.IsAlive(val))
			{
				if (GetBool(_doorOpen[i], val))
				{
					b |= 1;
				}
				if (GetBool(_doorLocked[i], val))
				{
					b |= 2;
				}
			}
			w.Write(b);
		}
		w.Write(_rooms.Length);
		int num = _rooms.Length + 7 >> 3;
		for (int j = 0; j < num; j++)
		{
			byte b2 = 0;
			for (int k = 0; k < 8; k++)
			{
				int num2 = (j << 3) + k;
				if (num2 < _rooms.Length && (Object)(object)_rooms[num2] != (Object)null && _rooms[num2].activeSelf)
				{
					b2 |= (byte)(1 << k);
				}
			}
			w.Write(b2);
		}
	}

	private void ApplyDoors(BakeBlockData data, ref TickBakeFrame f)
	{
		EnsureDoors();
		byte[] doorFlags = data.DoorFlags;
		int num = Math.Min(f.DoorCount, _doors.Length);
		for (int i = 0; i < num; i++)
		{
			Component val = _doors[i];
			if (!((Object)(object)val == (Object)null))
			{
				byte num2 = doorFlags[f.DoorStart + i];
				bool flag = (num2 & 1) != 0;
				bool flag2 = (num2 & 2) != 0;
				FieldAccess fieldAccess = _doorOpen[i];
				if (fieldAccess != null && fieldAccess.GetBool(val) != flag)
				{
					fieldAccess.SetBool(val, flag);
					_tickDoors++;
				}
				FieldAccess fieldAccess2 = _doorLocked[i];
				if (fieldAccess2 != null && fieldAccess2.GetBool(val) != flag2)
				{
					fieldAccess2.SetBool(val, flag2);
					_tickDoors++;
				}
			}
		}
		byte[] roomBits = data.RoomBits;
		int num3 = Math.Min(f.RoomCount, _rooms.Length);
		for (int j = 0; j < num3; j++)
		{
			GameObject val2 = _rooms[j];
			if (!((Object)(object)val2 == (Object)null))
			{
				bool flag3 = (roomBits[f.RoomStart + (j >> 3)] & (1 << (j & 7))) != 0;
				if (val2.activeSelf != flag3)
				{
					val2.SetActive(flag3);
					_tickDoors++;
				}
			}
		}
	}

	private void ResetEntityCaches()
	{
		_enemiesCached = false;
		_doorsCached = false;
		_projKeys.Clear();
		if (_retryProjectileTypes)
		{
			_retryProjectileTypes = false;
			_projTypes = null;
		}
		for (int i = 0; i < _projNextOrdinal.Length; i++)
		{
			_projNextOrdinal[i] = 0;
		}
		ClearLiveProjectiles();
	}

	private void ApplyFrame(BakeBlockData data, int index, bool enforcedTick)
	{
		s_runAppliedBakedState = true;
		float num = ((enforcedTick && CorrectionThreshold != null) ? CorrectionThreshold.Value : 0f);
		_thresholdSq = ((num > 0f && !float.IsInfinity(num) && num * num > 1E-10f) ? (num * num) : 1E-10f);
		ref TickBakeFrame reference = ref data.Frames[index];
		if (!_rngBroken)
		{
			try
			{
				ReadRngBits(out var s, out var s2, out var s3, out var s4);
				if (s != reference.Rng0 || s2 != reference.Rng1 || s3 != reference.Rng2 || s4 != reference.Rng3)
				{
					WriteRngBits(reference.Rng0, reference.Rng1, reference.Rng2, reference.Rng3);
					_tickRng++;
				}
			}
			catch
			{
				_rngBroken = true;
			}
		}
		ApplySystemRng(data, index, ref reference);
		ApplyPlayer(data, ref reference);
		ApplyEnemies(data, ref reference);
		if (enforcedTick)
		{
			ApplyProjectiles(data, ref reference);
		}
		ApplyDoors(data, ref reference);
	}

	private void ResetCorrections(TasBakeBlock block)
	{
		BeginCorrectionTick();
		_corrLastTick = 0;
		_corrBlock = 0L;
		_corrTicksApplied = 0;
		_corrTicksCorrected = 0;
		_corrMaxTick = 0;
		_corrMaxAt = -1;
		_corrRng = (_corrPlayer = (_corrEnemies = (_corrNavRepaths = (_corrProjectiles = (_corrDoors = 0)))));
		_projRescans = 0;
		_corrLogged = false;
		_corrBlockName = ((block != null) ? block.FileName : string.Empty);
		_corrVersion++;
	}

	private void BeginCorrectionTick()
	{
		_tickRng = (_tickPlayer = (_tickEnemies = (_tickNavRepaths = (_tickProjectiles = (_tickDoors = 0)))));
	}

	private void EndCorrectionTick(int tick)
	{
		int num = _tickRng + _tickPlayer + _tickEnemies + _tickProjectiles + _tickDoors;
		_corrRng += _tickRng;
		_corrPlayer += _tickPlayer;
		_corrEnemies += _tickEnemies;
		_corrNavRepaths += _tickNavRepaths;
		_corrProjectiles += _tickProjectiles;
		_corrDoors += _tickDoors;
		_corrTicksApplied++;
		if (num > 0)
		{
			_corrTicksCorrected++;
		}
		if (num > _corrMaxTick)
		{
			_corrMaxTick = num;
			_corrMaxAt = tick;
		}
		_corrBlock += num;
		_corrLastTick = num;
		_corrVersion++;
		BeginCorrectionTick();
	}

	private void LogCorrections(TasBakeBlock block, bool completed)
	{
		if (!_corrLogged && _corrTicksApplied != 0)
		{
			_corrLogged = true;
			_plugin.LogInfo("Bake: block '" + ((block != null) ? block.FileName : _corrBlockName) + "' enforced playback " + (completed ? "finished" : "left early") + ": " + _corrTicksApplied + " tick(s) applied, " + _corrBlock + " correction(s) on " + _corrTicksCorrected + " tick(s)" + ((_corrMaxAt >= 0) ? (" (max " + _corrMaxTick + " at tick " + _corrMaxAt + ")") : string.Empty) + "; RNG " + _corrRng + ", player " + _corrPlayer + ", enemies " + _corrEnemies + " (NavMesh re-paths " + _corrNavRepaths + "), projectiles " + _corrProjectiles + ", doors/rooms " + _corrDoors + "; projectile type rescans " + _projRescans + ".");
		}
	}

	private void VerifyFrame(BakeBlockData data, int index, TasBakeBlock block, int tick)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: 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_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		if (_driftReported)
		{
			return;
		}
		ref TickBakeFrame reference = ref data.Frames[index];
		if (reference.HasPlayer && EnsurePlayer())
		{
			Vector3 val = (((Object)(object)_playerTransform != (Object)null) ? _playerTransform.position : _player.transform.position);
			float num = Vector3.Distance(val, reference.PlayerPosition);
			if (num > 0.0001f)
			{
				ReportDrift(block, tick, "player position is " + num.ToString("0.######", CultureInfo.InvariantCulture) + " units off (live " + ((Vector3)(ref val)).ToString("F4") + ", baked " + ((Vector3)(ref reference.PlayerPosition)).ToString("F4") + ")");
				return;
			}
		}
		if (_coinType < 0 || (_projValidMask & TypeBit(_coinType)) == 0)
		{
			return;
		}
		BakeProjectile[] projectiles = data.Projectiles;
		int num2 = reference.ProjectileStart + reference.ProjectileCount;
		_frameProjIndex.Clear();
		int num3 = 0;
		for (int i = reference.ProjectileStart; i < num2; i++)
		{
			if (projectiles[i].Type == _coinType)
			{
				_frameProjIndex[projectiles[i].Key] = i;
				num3++;
			}
		}
		int num4 = 0;
		for (int j = 0; j < _liveProjCount; j++)
		{
			if (_liveProjType[j] == _coinType)
			{
				num4++;
				if (!_frameProjIndex.TryGetValue(_liveProjKey[j], out var value))
				{
					ReportDrift(block, tick, "a coin exists live that the bake does not have (key " + _liveProjKey[j] + ")");
					return;
				}
				Vector3 position = _liveProjTransform[j].position;
				float num5 = Vector3.Distance(position, projectiles[value].Position);
				if (num5 > 0.0001f)
				{
					ReportDrift(block, tick, "coin " + (_liveProjKey[j] & 0xFFFFF) + " is " + num5.ToString("0.######", CultureInfo.InvariantCulture) + " units off (live " + ((Vector3)(ref position)).ToString("F4") + ", baked " + ((Vector3)(ref projectiles[value].Position)).ToString("F4") + ")");
					return;
				}
			}
		}
		if (num3 != num4)
		{
			ReportDrift(block, tick, "coin count " + num4 + " live vs " + num3 + " baked");
		}
	}

	private void ReportDrift(TasBakeBlock block, int tick, string detail)
	{
		_driftReported = true;
		StatusText = "[VERIFY - DRIFT DETECTED]";
		DetailText = "block '" + block.FileName + "': drift at tick " + tick;
		string message = "Bake drift in block '" + block.FileName + "' at tick " + tick + " (block tick " + (tick - block.StartTick) + "): " + detail + ".";
		_plugin.LogWarning(message);
		_plugin.Toast(message, error: true);
	}

	private FieldAccess NamedField(Type type, params string[] names)
	{
		if (type == null || names == null)
		{
			return null;
		}
		for (int i = 0; i < names.Length; i++)
		{
			FieldInfo fieldInfo = _bridge.FindMember(type, names[i]) as FieldInfo;
			if (fieldInfo != null)
			{
				return FieldAccess.For(fieldInfo);
			}
		}
		return null;
	}

	private static FieldAccess[] FloatFields(Type type)
	{
		List<FieldInfo> list = new List<FieldInfo>(16);
		Type type2 = type;
		while (type2 != null && type2 != typeof(MonoBehaviour) && type2 != typeof(object))
		{
			FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < fields.Length; i++)
			{
				if (fields[i].FieldType == typeof(float) && !fields[i].IsInitOnly)
				{
					list.Add(fields[i]);
				}
			}
			type2 = type2.BaseType;
		}
		list.Sort((FieldInfo a, FieldInfo b) => string.CompareOrdinal(a.DeclaringType.Name + "." + a.Name, b.DeclaringType.Name + "." + b.Name));
		FieldAccess[] array = new FieldAccess[list.Count];
		for (int num = 0; num < array.Length; num++)
		{
			array[num] = FieldAccess.For(list[num]);
		}
		return array;
	}

	private static float GetFloat(FieldAccess field, object target)
	{
		if (field != null && target != null)
		{
			return field.GetFloat(target);
		}
		return 0f;
	}

	private static int GetInt(FieldAccess field, object target)
	{
		if (field != null && target != null)
		{
			return field.GetInt(target);
		}
		return 0;
	}

	private static bool GetBool(FieldAccess field, object target)
	{
		if (field != null && target != null)
		{
			return field.GetBool(target);
		}
		return false;
	}

	private static void SetFloat(FieldAccess field, object target, float value)
	{
		if (field != null && target != null)
		{
			field.SetFloat(target, value);
		}
	}
}
[Serializable]
public sealed class UktasBranch
{
	public string Id = string.Empty;

	public string Name = string.Empty;

	public string ParentId = string.Empty;

	public double ForkTime;

	public int ForkTick;

	public string Script = string.Empty;

	public double TotalSeconds;

	public int TotalTicks;
}
[Serializable]
public sealed class UktasProjectData
{
	public int Version = 1;

	public string Name = string.Empty;

	public string Author = string.Empty;

	public int Seed;

	public string TargetLevel = string.Empty;

	public string ActiveBranchId = string.Empty;

	public List<UktasBranch> Branches = new List<UktasBranch>();
}
public sealed class BranchProject
{
	public const string ProjectExtension = ".uktasproj";

	public const string BridgedSuffix = "-bridged.uktas";

	public UktasProjectData Data { get; private set; }

	public string ProjectPath { get; private set; }

	public string BridgedPath => Path.Combine(Path.GetDirectoryName(ProjectPath) ?? string.Empty, BaseName + "-bridged.uktas");

	public string BaseName => Path.GetFileNameWithoutExtension(ProjectPath);

	public UktasBranch Active => FindBranch(Data.ActiveBranchId);

	public IList<UktasBranch> Branches => Data.Branches;

	private BranchProject(UktasProjectData data, string projectPath)
	{
		Data = data;
		ProjectPath = projectPath;
	}

	public static BranchProject Create(string projectPath, string name, string author, int seed, string targetLevel, TasScript initial)
	{
		if (initial == null)
		{
			throw new ArgumentNullException("initial");
		}
		UktasProjectData obj = new UktasProjectData
		{
			Name = (string.IsNullOrEmpty(name) ? Path.GetFileNameWithoutExtension(projectPath) : name),
			Author = (author ?? string.Empty),
			Seed = seed,
			TargetLevel = (targetLevel ?? string.Empty)
		};
		UktasBranch uktasBranch = new UktasBranch
		{
			Id = NewId(),
			Name = "Main Route"
		};
		obj.Branches.Add(uktasBranch);
		obj.ActiveBranchId = uktasBranch.Id;
		BranchProject branchProject = new BranchProject(obj, Path.GetFullPath(projectPath));
		branchProject.Refresh(uktasBranch, initial);
		branchProject.Save();
		branchProject.WriteBridged();
		return branchProject;
	}

	public static BranchProject Open(string projectPath)
	{
		string fullPath = Path.GetFullPath(projec