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[] 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 { public int Compare(PendingProjectile a, PendingProjectile b) { return ComparePending(a, b); } } private sealed class FieldAccess { private static readonly Dictionary s_cache = new Dictionary(); private readonly FieldInfo _field; private readonly Type _type; private bool _compiled; private Func _getFloat; private Func _getInt; private Func _getBool; private Action _setFloat; private Action _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)dynamicMethod.CreateDelegate(typeof(Func)); 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)dynamicMethod.CreateDelegate(typeof(Func)); 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)dynamicMethod.CreateDelegate(typeof(Func)); 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)dynamicMethod.CreateDelegate(typeof(Action)); 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)dynamicMethod.CreateDelegate(typeof(Action)); 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 EnableBakedPlayback; public ConfigEntry VerifyRawPlayback; public ConfigEntry SkipBakedBlocks; public ConfigEntry CorrectionThreshold; private TasScript _script; private string _scriptPath = string.Empty; private readonly Dictionary _loaded = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly HashSet _missing = new HashSet(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 _recOffsets = new List(4096); private readonly List> _recSystemRandoms = new List>(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 _projKeys = new Dictionary(256); private readonly HashSet _projRoots = new HashSet(); private readonly List _pending = new List(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 _slotByKey = new Dictionary(128); private bool _projFullScanPending = true; private readonly HashSet _scanRoots = new HashSet(); private readonly Dictionary _frameProjIndex = new Dictionary(64); private static readonly Comparison PendingOrder = ComparePending; private static readonly IComparer 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("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("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("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("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 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 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 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 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 list = new List(tickCount * 4); List list2 = new List(tickCount * 4); List list3 = new List(tickCount * 4); List list4 = new List(tickCount * 4); List list5 = new List(tickCount * 2); HashSet hashSet = new HashSet(); HashSet hashSet2 = new HashSet(); 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 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 item = null; if (rng != null) { List 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[] 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(); 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(); _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 list = new List(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(); _enemyAgents[k] = gameObject.GetComponent(); Animator component2 = gameObject.GetComponent(); _enemyAnimators[k] = (((Object)(object)component2 != (Object)null) ? component2 : gameObject.GetComponentInChildren(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> list = new List>(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(HierarchyKey(val), val)); } } } list.Sort((KeyValuePair a, KeyValuePair 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 list2 = new List(32); HashSet seen = new HashSet(); 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 into, HashSet 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 list = new List(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 list = new List(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 Branches = new List(); } 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 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(projectPath); UktasProjectData uktasProjectData = JsonUtility.FromJson(File.ReadAllText(fullPath)); if (uktasProjectData == null || uktasProjectData.Branches == null || uktasProjectData.Branches.Count == 0) { throw new InvalidDataException("Project has no branches: " + fullPath); } if (FindIn(uktasProjectData, uktasProjectData.ActiveBranchId) == null) { uktasProjectData.ActiveBranchId = uktasProjectData.Branches[0].Id; } return new BranchProject(uktasProjectData, fullPath); } public void Save() { string contents = JsonUtility.ToJson((object)Data, true); string directoryName = Path.GetDirectoryName(ProjectPath); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } File.WriteAllText(ProjectPath, contents); } public void WriteBridged() { UktasBranch active = Active; if (active == null) { throw new InvalidOperationException("No active branch."); } File.WriteAllText(BridgedPath, active.Script); } public void SyncActive(TasScript live) { UktasBranch active = Active; if (active != null && live != null) { Refresh(active, live); } } public UktasBranch Fork(string name, TasScript live, int tick, out TasScript forkedScript) { if (live == null) { throw new ArgumentNullException("live"); } UktasBranch active = Active; if (active == null) { throw new InvalidOperationException("No active branch."); } SyncActive(live); TasScript tasScript = TasScript.Parse(live.Serialize(), name ?? "branch"); tick = Mathf.Clamp(tick, 0, Mathf.Max(0, tasScript.TotalTicks)); tasScript.TruncateAtTick(tick); UktasBranch uktasBranch = new UktasBranch { Id = NewId(), Name = (string.IsNullOrEmpty(name) ? ("Branch " + (Data.Branches.Count + 1)) : name), ParentId = active.Id, ForkTick = tick, ForkTime = tasScript.TimeAtTick(tick) }; Refresh(uktasBranch, tasScript); Data.Branches.Add(uktasBranch); Data.ActiveBranchId = uktasBranch.Id; Save(); WriteBridged(); forkedScript = TasScript.Parse(uktasBranch.Script, uktasBranch.Name); return uktasBranch; } public UktasBranch AddDivergentBranch(string name, TasScript live, TasScript full, int forkTick) { if (full == null) { throw new ArgumentNullException("full"); } UktasBranch active = Active; if (active == null) { throw new InvalidOperationException("No active branch."); } SyncActive(live ?? full); UktasBranch uktasBranch = new UktasBranch { Id = NewId(), Name = (string.IsNullOrEmpty(name) ? ("Branch " + (Data.Branches.Count + 1)) : name), ParentId = active.Id, ForkTick = Mathf.Max(0, forkTick), ForkTime = full.TimeAtTick(Mathf.Max(0, forkTick)) }; Refresh(uktasBranch, full); Data.Branches.Add(uktasBranch); Data.ActiveBranchId = uktasBranch.Id; Save(); WriteBridged(); return uktasBranch; } public TasScript SwitchTo(string branchId, TasScript live) { UktasBranch uktasBranch = FindBranch(branchId); if (uktasBranch == null) { throw new KeyNotFoundException("No branch with id " + branchId); } SyncActive(live); Data.ActiveBranchId = uktasBranch.Id; Save(); WriteBridged(); return TasScript.Parse(uktasBranch.Script, uktasBranch.Name); } public void Rename(string branchId, string name) { UktasBranch uktasBranch = FindBranch(branchId); if (uktasBranch != null && !string.IsNullOrEmpty(name)) { uktasBranch.Name = name; Save(); } } public UktasBranch FindBranch(string id) { return FindIn(Data, id); } public double DeltaAgainstActive(UktasBranch branch) { UktasBranch active = Active; if (active == null || branch == null) { return 0.0; } return branch.TotalSeconds - active.TotalSeconds; } public static string FormatDelta(double seconds) { if (Math.Abs(seconds) < 5E-07) { return "±0.000000 s"; } return ((seconds > 0.0) ? "+" : string.Empty) + seconds.ToString("0.000000", CultureInfo.InvariantCulture) + " s"; } private void Refresh(UktasBranch branch, TasScript script) { branch.Script = script.Serialize(); branch.TotalSeconds = script.TotalTime; branch.TotalTicks = script.TotalTicks; } private static UktasBranch FindIn(UktasProjectData data, string id) { if (string.IsNullOrEmpty(id) || data.Branches == null) { return null; } for (int i = 0; i < data.Branches.Count; i++) { if (data.Branches[i] != null && data.Branches[i].Id == id) { return data.Branches[i]; } } return null; } private static string NewId() { return Guid.NewGuid().ToString("N"); } } public struct CoinPathPoint { public int Tick; public Vector3 Position; } public sealed class CoinPath { public int Id; public int LastTick = -1; public bool Closed; public bool Punched; public bool Shot; public bool ShotByEnemy; public bool Targeting; public Vector3 EventPoint; public bool HasEventPoint; public Vector3 TargetPoint; public bool HasTargetPoint; public readonly List Points = new List(512); } public sealed class CoinPathManager { private const int MaxTrails = 256; private const int MaxPointsPerTrail = 8000; private const float ThicknessStep = 0.02f; private const float DashLength = 0.6f; private static readonly Color FlightColor = new Color(1f, 0.83f, 0.25f); private static readonly Color PunchedColor = new Color(0.35f, 1f, 0.5f); private static readonly Color ShotColor = new Color(0.3f, 0.8f, 1f); private static readonly Color EnemyShotColor = new Color(1f, 0.35f, 0.35f); private static readonly Color TargetColor = new Color(1f, 0.3f, 0.85f); private readonly Plugin _plugin; private readonly List _paths = new List(64); private readonly List _coins = new List(16); private readonly HashSet _seen = new HashSet(); private Material _material; private int _lastSampledTick = -1; public int Count => _paths.Count; public IList Paths => _paths; public CoinPathManager(Plugin plugin) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown _plugin = plugin; Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(OnCameraPostRender)); } public void Dispose() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown Camera.onPostRender = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(OnCameraPostRender)); if ((Object)(object)_material != (Object)null) { Object.Destroy((Object)(object)_material); } _material = null; } public void Clear() { _paths.Clear(); _lastSampledTick = -1; } public void Sample(int tick) { //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0246: 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_0260: Unknown result type (might be due to invalid IL or missing references) if (_plugin.CoinPathEnabled == null || !_plugin.CoinPathEnabled.Value || tick == _lastSampledTick) { return; } GameBridge bridge = _plugin.Bridge; if (bridge == null) { return; } _lastSampledTick = tick; int num = bridge.CollectCoins(_coins); _seen.Clear(); for (int i = 0; i < num; i++) { GameBridge.CoinInfo coinInfo = _coins[i]; _seen.Add(coinInfo.Id); CoinPath coinPath = Find(coinInfo.Id); if (coinPath == null) { coinPath = new CoinPath { Id = coinInfo.Id }; _paths.Add(coinPath); TrimTrails(); } if (coinPath.LastTick >= 0 && tick < coinPath.LastTick) { int num2 = FirstPointAfter(coinPath, tick); if (num2 < coinPath.Points.Count) { coinPath.Points.RemoveRange(num2, coinPath.Points.Count - num2); } } if (coinPath.Points.Count == 0 || coinPath.Points[coinPath.Points.Count - 1].Tick != tick) { coinPath.Points.Add(new CoinPathPoint { Tick = tick, Position = coinInfo.Position }); if (coinPath.Points.Count > 8000) { coinPath.Points.RemoveRange(0, coinPath.Points.Count - 8000); } } coinPath.LastTick = tick; coinPath.Closed = false; if (coinInfo.Power > 1f || coinInfo.Name.StartsWith("NewCoin", StringComparison.OrdinalIgnoreCase)) { coinPath.Punched = true; } if (coinInfo.Shot) { coinPath.Shot = true; } if (coinInfo.ShotByEnemy) { coinPath.ShotByEnemy = true; } if (coinInfo.HasTargetPoint) { coinPath.Targeting = true; coinPath.TargetPoint = coinInfo.TargetPoint; coinPath.HasTargetPoint = true; } if (!coinPath.HasEventPoint && (coinInfo.Shot || coinInfo.ShotByEnemy)) { coinPath.EventPoint = coinInfo.Position; coinPath.HasEventPoint = true; if (!coinPath.HasTargetPoint && TryFindEnemy(coinPath.EventPoint, out var point)) { coinPath.Targeting = true; coinPath.TargetPoint = point; coinPath.HasTargetPoint = true; } } } for (int j = 0; j < _paths.Count; j++) { CoinPath coinPath2 = _paths[j]; if (!coinPath2.Closed && !_seen.Contains(coinPath2.Id)) { coinPath2.Closed = true; } } } private bool TryFindEnemy(Vector3 origin, out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) point = Vector3.zero; GameBridge bridge = _plugin.Bridge; if (bridge == null) { return false; } if (!bridge.Entities.TryFindNearest("enemy", origin, out var nearest, out var _) || nearest == null) { return false; } if (bridge.Entities.TryGetAimPosition(nearest.Id, out point)) { return true; } if ((Object)(object)nearest.Component == (Object)null) { return false; } point = nearest.Component.transform.position; return true; } private CoinPath Find(int id) { for (int i = 0; i < _paths.Count; i++) { if (_paths[i].Id == id) { return _paths[i]; } } return null; } private static int FirstPointAfter(CoinPath path, int tick) { for (int i = 0; i < path.Points.Count; i++) { if (path.Points[i].Tick > tick) { return i; } } return path.Points.Count; } private void TrimTrails() { while (_paths.Count > 256) { int index = 0; for (int i = 0; i < _paths.Count; i++) { if (_paths[i].Closed) { index = i; break; } } _paths.RemoveAt(index); } } private bool ShouldDraw() { if (_plugin.CoinPathEnabled == null || !_plugin.CoinPathEnabled.Value) { return false; } if (_plugin.Video != null && _plugin.Video.Rendering) { return false; } if (_plugin.CleanRecordingActive) { return false; } TasEngine engine = _plugin.Engine; if (engine != null && engine.RenderSuppressed) { return false; } return true; } private static Color ColorFor(CoinPath path, float opacity) { //IL_0008: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_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_0064: Unknown result type (might be due to invalid IL or missing references) Color result = (path.ShotByEnemy ? EnemyShotColor : (path.Shot ? ShotColor : (path.Punched ? PunchedColor : ((!path.Targeting) ? FlightColor : TargetColor)))); result.a = Mathf.Clamp01(path.Closed ? (opacity * 0.65f) : opacity); return result; } private void OnCameraPostRender(Camera camera) { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: 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_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0127: 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_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0285: 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) if ((Object)(object)camera == (Object)null || (Object)(object)camera != (Object)(object)Camera.main || _paths.Count == 0 || !ShouldDraw()) { return; } EnsureMaterial(); float num = Mathf.Clamp01((_plugin.CoinPathOpacity != null) ? _plugin.CoinPathOpacity.Value : 0.9f); int num2 = Mathf.Clamp(Mathf.RoundToInt((_plugin.CoinPathThickness != null) ? _plugin.CoinPathThickness.Value : 2f), 1, 6); Vector3 right = ((Component)camera).transform.right; _material.SetPass(0); GL.PushMatrix(); GL.MultMatrix(Matrix4x4.identity); for (int i = 0; i < num2; i++) { float num3 = ((float)i - (float)(num2 - 1) * 0.5f) * 0.02f; GL.Begin(1); for (int j = 0; j < _paths.Count; j++) { CoinPath coinPath = _paths[j]; if (coinPath.Points.Count >= 2) { GL.Color(ColorFor(coinPath, num)); for (int k = 1; k < coinPath.Points.Count; k++) { GL.Vertex(coinPath.Points[k - 1].Position + right * num3); GL.Vertex(coinPath.Points[k].Position + right * num3); } } } GL.End(); } GL.Begin(1); for (int l = 0; l < _paths.Count; l++) { CoinPath coinPath2 = _paths[l]; if (coinPath2.HasEventPoint) { Color val = (coinPath2.ShotByEnemy ? EnemyShotColor : ShotColor); val.a = num; GL.Color(val); Cross(coinPath2.EventPoint, right, 0.3f); } if (coinPath2.HasEventPoint && coinPath2.HasTargetPoint) { Color targetColor = TargetColor; targetColor.a = num; GL.Color(targetColor); Dashed(coinPath2.EventPoint, coinPath2.TargetPoint); } else if (coinPath2.Targeting && coinPath2.Points.Count > 0 && coinPath2.HasTargetPoint) { Color targetColor2 = TargetColor; targetColor2.a = num; GL.Color(targetColor2); Dashed(coinPath2.Points[coinPath2.Points.Count - 1].Position, coinPath2.TargetPoint); } } GL.End(); GL.Begin(1); for (int m = 0; m < _paths.Count; m++) { CoinPath coinPath3 = _paths[m]; if (!coinPath3.Closed && coinPath3.Points.Count != 0) { GL.Color(ColorFor(coinPath3, num)); Cross(coinPath3.Points[coinPath3.Points.Count - 1].Position, right, 0.15f); } } GL.End(); GL.PopMatrix(); } private static void Cross(Vector3 point, Vector3 right, float size) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) GL.Vertex(point + Vector3.up * size); GL.Vertex(point - Vector3.up * size); GL.Vertex(point + right * size); GL.Vertex(point - right * size); GL.Vertex(point + Vector3.forward * size); GL.Vertex(point - Vector3.forward * size); } private static void Dashed(Vector3 from, Vector3 to) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) Vector3 val = to - from; float magnitude = ((Vector3)(ref val)).magnitude; if (!(magnitude < 0.0001f)) { Vector3 val2 = val / magnitude; for (float num = 0f; num < magnitude; num += 1.2f) { float num2 = Mathf.Min(num + 0.6f, magnitude); GL.Vertex(from + val2 * num); GL.Vertex(from + val2 * num2); } } } private void EnsureMaterial() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (!((Object)(object)_material != (Object)null)) { Shader val = Shader.Find("Hidden/Internal-Colored"); _material = new Material(val); ((Object)_material).hideFlags = (HideFlags)61; _material.SetInt("_SrcBlend", 5); _material.SetInt("_DstBlend", 10); _material.SetInt("_Cull", 0); _material.SetInt("_ZWrite", 0); _material.SetInt("_ZTest", 4); } } } public sealed class DeterminismTrace { private const int MaxRows = 6000; private const int FlushEveryRows = 250; private const int MaxBodies = 12; private const int MaxCandidates = 300; private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; private StreamWriter _writer; private int _rows; private static Type _enemyType; public string FilePath { get; private set; } public void Row(int tick, GameBridge bridge) { //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0183: 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) if (tick == 0) { Begin(); } if (_writer == null || _rows >= 6000) { return; } bridge.TryGetPlayerPosition(out var position); bridge.TryGetPlayerVelocity(out var velocity); int num = 0; ulong num2 = 0uL; List list = new List(32); Object[] array = Object.FindObjectsOfType(typeof(Rigidbody)); foreach (Object obj in array) { Rigidbody val = (Rigidbody)(object)((obj is Rigidbody) ? obj : null); if (!((Object)(object)val == (Object)null)) { Vector3 position2 = val.position; Vector3 velocity2 = val.velocity; num++; ulong num3 = 1469598103934665603uL; num3 = (num3 ^ Bits(position2.x)) * 1099511628211L; num3 = (num3 ^ Bits(position2.y)) * 1099511628211L; num3 = (num3 ^ Bits(position2.z)) * 1099511628211L; num3 = (num3 ^ Bits(velocity2.x)) * 1099511628211L; num3 = (num3 ^ Bits(velocity2.y)) * 1099511628211L; num3 = (num3 ^ Bits(velocity2.z)) * 1099511628211L; num2 += num3; if (((Vector3)(ref velocity2)).sqrMagnitude > 0.0001f && list.Count < 300) { list.Add(((Object)val).name.Replace(';', '_').Replace('|', '_') + "@" + Vec(position2) + "v" + Vec(velocity2)); } } } list.Sort(StringComparer.Ordinal); int count; ulong num4 = EnemyChecksum(bridge, out count); StringBuilder stringBuilder = new StringBuilder(256); stringBuilder.Append(tick.ToString(Inv)).Append(';'); stringBuilder.Append(Time.time.ToString("R", Inv)).Append(';'); stringBuilder.Append(Time.fixedTime.ToString("R", Inv)).Append(';'); stringBuilder.Append(Vec(position)).Append(';'); stringBuilder.Append(Vec(velocity)).Append(';'); stringBuilder.Append(num.ToString(Inv)).Append(';'); stringBuilder.Append(num2.ToString("X16", Inv)).Append(';'); stringBuilder.Append(count.ToString(Inv)).Append(';'); stringBuilder.Append(num4.ToString("X16", Inv)).Append(';'); for (int j = 0; j < list.Count && j < 12; j++) { if (j > 0) { stringBuilder.Append('|'); } stringBuilder.Append(list[j]); } _writer.WriteLine(stringBuilder.ToString()); _rows++; if (_rows % 250 == 0 || _rows >= 6000) { _writer.Flush(); } } private static ulong EnemyChecksum(GameBridge bridge, out int count) { //IL_0099: 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_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0139: 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_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) count = 0; if (bridge == null) { return 0uL; } if (_enemyType == null) { _enemyType = bridge.FindType("EnemyIdentifier"); } if (_enemyType == null) { return 0uL; } Object[] array; try { array = Object.FindObjectsOfType(_enemyType, true); } catch { return 0uL; } count = array.Length; ulong num = 0uL; int num2 = Math.Min(array.Length, 64); for (int i = 0; i < num2; i++) { Object obj2 = array[i]; Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if (!((Object)(object)val == (Object)null)) { Transform transform = val.transform; ulong num3 = 1469598103934665603uL; num3 = (num3 ^ Bits(transform.position.x)) * 1099511628211L; num3 = (num3 ^ Bits(transform.position.y)) * 1099511628211L; num3 = (num3 ^ Bits(transform.position.z)) * 1099511628211L; num3 = (num3 ^ Bits(transform.rotation.x)) * 1099511628211L; num3 = (num3 ^ Bits(transform.rotation.y)) * 1099511628211L; num3 = (num3 ^ Bits(transform.rotation.z)) * 1099511628211L; num3 = (num3 ^ Bits(transform.rotation.w)) * 1099511628211L; num3 = (num3 ^ (ulong)(val.gameObject.activeSelf ? 1 : 0)) * 1099511628211L; Animator componentInChildren = val.GetComponentInChildren(true); if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.runtimeAnimatorController != (Object)null && componentInChildren.layerCount > 0) { AnimatorStateInfo currentAnimatorStateInfo = componentInChildren.GetCurrentAnimatorStateInfo(0); num3 = (num3 ^ (uint)((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash) * 1099511628211L; num3 = (num3 ^ Bits(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime)) * 1099511628211L; } num += num3; } } return num; } private void Begin() { Close(); try { string directoryName = Path.GetDirectoryName(typeof(DeterminismTrace).Assembly.Location); FilePath = Path.Combine(directoryName, "determinism_trace_" + DateTime.Now.ToString("yyyyMMdd_HHmmss", Inv) + ".csv"); _writer = new StreamWriter(FilePath, append: false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 65536) { AutoFlush = false }; _writer.WriteLine("tick;time;fixedTime;playerPos;playerVel;rigidbodies;checksum;enemies;enemyChecksum;movingBodies"); _rows = 0; } catch { _writer = null; } } public void Close() { if (_writer != null) { try { _writer.Dispose(); } catch { } _writer = null; } } private static ulong Bits(float value) { return BitConverter.ToUInt32(BitConverter.GetBytes(value), 0); } private static string Vec(Vector3 v) { return v.x.ToString("R", Inv) + "," + v.y.ToString("R", Inv) + "," + v.z.ToString("R", Inv); } } public sealed class EntityRegistry { public sealed class Entity { public int Id; public Component Component; public string TypeName = string.Empty; public string Category = string.Empty; public bool Spawned; } public sealed class EntityIdState { public int Id; public Component Component; public int ObjectId; public string TypeName = string.Empty; public string Category = string.Empty; public bool Spawned; } public sealed class EntityIdSnapshot { public int Revision; public EntityIdState[] Entries; } public const int FirstSpawnedId = 10000; private static readonly string[] EnemyTypeNames = new string[1] { "EnemyIdentifier" }; private static readonly string[] ProjectileTypeNames = new string[12] { "Projectile", "Coin", "Nail", "Harpoon", "Grenade", "Cannonball", "Magnet", "GasolineProjectile", "Landmine", "ThrownSword", "BlackHoleProjectile", "Chainsaw" }; private static readonly string[] ObjectTypeNames = new string[2] { "ItemIdentifier", "Breakable" }; private static readonly string[] StateLabels = new string[12] { "hp", "dead", "type", "dmg", "friendly", "player", "parried", "rocket", "exploded", "item", "picked", "broken" }; private static readonly string[][] StateCandidates = new string[12][] { new string[3] { "health", "hp", "currentHealth" }, new string[2] { "dead", "isDead" }, new string[1] { "enemyType" }, new string[1] { "damage" }, new string[1] { "friendly" }, new string[1] { "playerBullet" }, new string[1] { "parried" }, new string[1] { "rocket" }, new string[1] { "exploded" }, new string[1] { "itemType" }, new string[1] { "pickedUp" }, new string[1] { "broken" } }; private static readonly string[] EnemyLinkNames = new string[1] { "eid" }; private readonly Plugin _plugin; private readonly GameBridge _bridge; private readonly List _types = new List(16); private readonly List _typeCategories = new List(16); private readonly HashSet _warnedNames = new HashSet(StringComparer.Ordinal); private readonly Dictionary _categoryByType = new Dictionary(16); private bool _typesResolved; private Type _linkType; private bool _pickWarned; private readonly List _level = new List(256); private readonly List _spawned = new List(64); private readonly Dictionary _byObject = new Dictionary(256); private Scene _scene; private bool _built; private int _idRevision; private EntityIdSnapshot _idSnapshot; public Func RebuiltLookup; private readonly RaycastHit[] _hits = (RaycastHit[])(object)new RaycastHit[64]; private readonly StringBuilder _stateText = new StringBuilder(128); public int LevelCount => _level.Count; public EntityRegistry(Plugin plugin, GameBridge bridge) { _plugin = plugin; _bridge = bridge; } private Scene LevelScene() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) Transform playerTransform = _bridge.PlayerTransform; if ((Object)(object)playerTransform != (Object)null) { return ((Component)playerTransform).gameObject.scene; } return SceneManager.GetActiveScene(); } public void OnSceneLoaded(Scene scene, LoadSceneMode mode) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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_0052: Unknown result type (might be due to invalid IL or missing references) try { if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded) { Transform playerTransform = _bridge.PlayerTransform; int num; if ((Object)(object)playerTransform != (Object)null) { Scene scene2 = ((Component)playerTransform).gameObject.scene; num = ((((Scene)(ref scene2)).handle == ((Scene)(ref scene)).handle) ? 1 : 0); } else { num = 0; } bool flag = (byte)num != 0; if ((int)mode == 0 || flag) { Rebuild(scene); } } } catch (Exception ex) { _plugin.LogWarning("Entity IDs: rebuild failed: " + ex.Message); } } public void Poll() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) Scene scene = LevelScene(); if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded || (_built && ((Scene)(ref _scene)).IsValid() && ((Scene)(ref _scene)).isLoaded && ((Scene)(ref _scene)).handle == ((Scene)(ref scene)).handle)) { return; } try { Rebuild(scene); } catch (Exception ex) { _plugin.LogWarning("Entity IDs: rebuild failed: " + ex.Message); } } private void EnsureBuilt() { Poll(); } private void ResolveTypes() { if (!_typesResolved) { _types.Clear(); _typeCategories.Clear(); _categoryByType.Clear(); AddTypes(EnemyTypeNames, "enemy"); AddTypes(ProjectileTypeNames, "projectile"); AddTypes(ObjectTypeNames, "object"); _linkType = _bridge.FindType("EnemyIdentifierIdentifier"); if (_linkType == null && _warnedNames.Add("EnemyIdentifierIdentifier")) { _plugin.LogWarning("Entity IDs: game type 'EnemyIdentifierIdentifier' not found; enemy hitboxes are matched by hierarchy only."); } _typesResolved = _types.Count > 0; } } private void AddTypes(string[] names, string category) { for (int i = 0; i < names.Length; i++) { Type type = _bridge.FindType(names[i]); if (type == null) { if (_warnedNames.Add(names[i])) { _plugin.LogWarning("Entity IDs: game type '" + names[i] + "' not found; it is skipped."); } } else if (!_types.Contains(type)) { _types.Add(type); _typeCategories.Add(category); _categoryByType[type] = category; } } } private bool TryGetCategory(Type type, out string category) { if (_categoryByType.TryGetValue(type, out category)) { return true; } Type baseType = type.BaseType; while (baseType != null) { if (_categoryByType.TryGetValue(baseType, out category)) { return true; } baseType = baseType.BaseType; } category = string.Empty; return false; } private void Rebuild(Scene scene) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) _level.Clear(); _spawned.Clear(); _byObject.Clear(); InvalidateIds(); _scene = scene; _built = false; if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded) { return; } ResolveTypes(); if (_types.Count == 0) { return; } List list = new List(512); GameObject[] rootGameObjects; try { rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects(); } catch (Exception ex) { _plugin.LogWarning("Entity IDs: scene root scan failed: " + ex.Message); return; } foreach (GameObject val in rootGameObjects) { if (!((Object)(object)val == (Object)null)) { Component[] componentsInChildren; try { componentsInChildren = val.GetComponentsInChildren(true); } catch (Exception ex2) { _plugin.LogWarning("Entity IDs: scan of '" + ((Object)val).name + "' failed: " + ex2.Message); continue; } for (int j = 0; j < componentsInChildren.Length; j++) { list.Add(componentsInChildren[j]); } } } List> list2 = new List>(list.Count); for (int k = 0; k < list.Count; k++) { Component val2 = list[k]; if (!((Object)(object)val2 == (Object)null)) { Scene scene2 = val2.gameObject.scene; if (((Scene)(ref scene2)).handle == ((Scene)(ref scene)).handle && TryGetCategory(((object)val2).GetType(), out var category)) { Entity value = new Entity { Component = val2, TypeName = ((object)val2).GetType().Name, Category = category }; list2.Add(new KeyValuePair(SortKey(val2), value)); } } } list2.Sort((KeyValuePair a, KeyValuePair b) => string.CompareOrdinal(a.Key, b.Key)); for (int num = 0; num < list2.Count; num++) { Entity value2 = list2[num].Value; value2.Id = num + 1; _level.Add(value2); int instanceID = ((Object)value2.Component.gameObject).GetInstanceID(); if (!_byObject.ContainsKey(instanceID)) { _byObject.Add(instanceID, value2); } } _built = true; _plugin.LogInfo("Entity IDs: " + _level.Count + " entities in scene '" + ((Scene)(ref scene)).name + "' (IDs 1-" + _level.Count + "; objects spawned later get IDs from " + 10000 + ")."); } private static string SortKey(Component component) { StringBuilder stringBuilder = new StringBuilder(96); stringBuilder.Append(((object)component).GetType().Name).Append('\u0001'); List list = new List(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('/'); } int num2 = Array.IndexOf(component.gameObject.GetComponents(((object)component).GetType()), component); stringBuilder.Append('#').Append(num2.ToString("D3", CultureInfo.InvariantCulture)); return stringBuilder.ToString(); } public EntityIdSnapshot CaptureIds() { EnsureBuilt(); if (_idSnapshot != null && _idSnapshot.Revision == _idRevision) { return _idSnapshot; } List list = new List(_level.Count + _spawned.Count); for (int i = 0; i < _level.Count; i++) { AddIdState(list, _level[i]); } for (int j = 0; j < _spawned.Count; j++) { AddIdState(list, _spawned[j]); } _idSnapshot = new EntityIdSnapshot { Revision = _idRevision, Entries = list.ToArray() }; return _idSnapshot; } private static void AddIdState(List into, Entity entity) { if (entity != null) { into.Add(new EntityIdState { Id = entity.Id, Component = entity.Component, ObjectId = (((Object)(object)entity.Component != (Object)null) ? ((Object)entity.Component.gameObject).GetInstanceID() : 0), TypeName = entity.TypeName, Category = entity.Category, Spawned = entity.Spawned }); } } private void InvalidateIds() { _idRevision++; _idSnapshot = null; } public void RestoreIds(EntityIdSnapshot saved) { if (saved == null || saved.Entries == null || saved.Entries.Length == 0 || (_idSnapshot != null && _idSnapshot.Entries == saved.Entries)) { return; } EnsureBuilt(); _level.Clear(); _spawned.Clear(); _byObject.Clear(); EntityIdState[] entries = saved.Entries; foreach (EntityIdState entityIdState in entries) { if (entityIdState == null) { continue; } Component val = entityIdState.Component; if ((Object)(object)val == (Object)null && val != null && RebuiltLookup != null) { try { val = RebuiltLookup(entityIdState.ObjectId, ((object)val).GetType()); } catch { val = null; } } Entity entity = new Entity { Id = entityIdState.Id, Component = val, TypeName = entityIdState.TypeName, Category = entityIdState.Category, Spawned = entityIdState.Spawned }; if (entityIdState.Spawned) { while (_spawned.Count < entityIdState.Id - 10000) { _spawned.Add(new Entity { Id = 10000 + _spawned.Count }); } _spawned.Add(entity); } else { while (_level.Count < entityIdState.Id - 1) { _level.Add(new Entity { Id = _level.Count + 1 }); } _level.Add(entity); } if ((Object)(object)entity.Component != (Object)null && GameBridge.IsAlive(entity.Component)) { _byObject[((Object)entity.Component.gameObject).GetInstanceID()] = entity; } } _idSnapshot = new EntityIdSnapshot { Revision = ++_idRevision, Entries = entries }; } public Entity Find(int id) { EnsureBuilt(); if (id >= 1 && id <= _level.Count) { return _level[id - 1]; } int num = id - 10000; if (num >= 0 && num < _spawned.Count) { return _spawned[num]; } return null; } public bool TryGetPosition(int id, out Vector3 position) { //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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Entity entity = Find(id); if (entity == null || !GameBridge.IsAlive(entity.Component)) { position = Vector3.zero; return false; } position = entity.Component.transform.position; return true; } public bool TryGetAimPosition(int id, out Vector3 position) { return TryGetAimPosition(id, string.Empty, out position); } public bool TryGetAimPosition(int id, string hitbox, out Vector3 position) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) Entity entity = Find(id); if (entity == null || (Object)(object)entity.Component == (Object)null || !GameBridge.IsAlive(entity.Component) || !entity.Component.gameObject.activeInHierarchy) { position = Vector3.zero; return false; } return TryGetAimPoint(entity.Component, hitbox, out position); } private bool TryGetAimPoint(Component target, string hitbox, out Vector3 position) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0130: 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_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) position = target.transform.position; string text = NormalizeHitboxName(hitbox); if (text.Length != 0) { switch (text) { case "center": case "body": case "torso": case "chest": case "middle": break; case "head": case "weakpoint": { Transform val = LookAtTransformOf(_bridge.GetMember(target, new string[1] { "weakPoint" })); if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy && TryGetTransformPoint(val, out position)) { return true; } goto default; } default: { Collider[] array = null; try { array = target.GetComponentsInChildren(true); } catch { array = null; } if (array != null) { foreach (Collider val2 in array) { if (!((Object)(object)val2 == (Object)null) && val2.enabled && ((Component)val2).gameObject.activeInHierarchy && (HitboxNameMatches(((Object)val2).name, text) || HitboxNameMatches(((Object)((Component)val2).gameObject).name, text))) { Bounds bounds = val2.bounds; position = ((Bounds)(ref bounds)).center; return true; } } } Transform[] array2 = null; try { array2 = target.GetComponentsInChildren(true); } catch { array2 = null; } if (array2 != null) { foreach (Transform val3 in array2) { if (!((Object)(object)val3 == (Object)null) && ((Component)val3).gameObject.activeInHierarchy && HitboxNameMatches(((Object)val3).name, text) && TryGetTransformPoint(val3, out position)) { return true; } } } if (_bridge.GetMember(target, new string[1] { "limbs" }) is Array array3) { for (int k = 0; k < array3.Length; k++) { object? value = array3.GetValue(k); Component val4 = (Component)((value is Component) ? value : null); if (!((Object)(object)val4 == (Object)null) && val4.gameObject.activeInHierarchy && HitboxNameMatches(((Object)val4.gameObject).name, text) && TryGetTransformPoint(val4.transform, out position)) { return true; } } } return false; } } } return TryGetTargetCenter(target, out position); } private bool TryGetTargetCenter(Component target, out Vector3 position) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) Transform val = LookAtTransformOf(_bridge.GetMember(target, new string[1] { "overrideCenter" })); if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy && TryGetTransformPoint(val, out position)) { return true; } if (TryGetColliderCenter(target, out position)) { return true; } if (TryGetRendererCenter(target, out position)) { return true; } position = target.transform.position; return true; } private bool TryGetTransformPoint(Transform transform, out Vector3 position) { //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) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)transform == (Object)null) { position = Vector3.zero; return false; } if (TryGetColliderCenter((Component)(object)transform, out position)) { return true; } if (TryGetRendererCenter((Component)(object)transform, out position)) { return true; } position = transform.position; return true; } private static bool TryGetColliderCenter(Component target, out Vector3 center) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) center = Vector3.zero; Collider[] componentsInChildren; try { componentsInChildren = target.GetComponentsInChildren(true); } catch { return false; } bool flag = false; Bounds val = default(Bounds); foreach (Collider val2 in componentsInChildren) { if (!((Object)(object)val2 == (Object)null) && val2.enabled && ((Component)val2).gameObject.activeInHierarchy) { if (!flag) { val = val2.bounds; flag = true; } else { ((Bounds)(ref val)).Encapsulate(val2.bounds); } } } if (!flag) { return false; } center = ((Bounds)(ref val)).center; return true; } private static bool TryGetRendererCenter(Component target, out Vector3 center) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) center = Vector3.zero; Renderer[] componentsInChildren; try { componentsInChildren = target.GetComponentsInChildren(true); } catch { return false; } bool flag = false; Bounds val = default(Bounds); foreach (Renderer val2 in componentsInChildren) { if (!((Object)(object)val2 == (Object)null) && val2.enabled && ((Component)val2).gameObject.activeInHierarchy) { if (!flag) { val = val2.bounds; flag = true; } else { ((Bounds)(ref val)).Encapsulate(val2.bounds); } } } if (!flag) { return false; } center = ((Bounds)(ref val)).center; return true; } private static Transform LookAtTransformOf(object value) { Transform val = (Transform)((value is Transform) ? value : null); if ((Object)(object)val != (Object)null) { return val; } GameObject val2 = (GameObject)((value is GameObject) ? value : null); if ((Object)(object)val2 != (Object)null) { return val2.transform; } Component val3 = (Component)((value is Component) ? value : null); if (!((Object)(object)val3 != (Object)null)) { return null; } return val3.transform; } private static string NormalizeHitboxName(string text) { if (string.IsNullOrEmpty(text)) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(text.Length); foreach (char c in text) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(char.ToLowerInvariant(c)); } } return stringBuilder.ToString(); } private static bool HitboxNameMatches(string candidate, string wanted) { string text = NormalizeHitboxName(candidate); if (text.Length == 0) { return false; } if (text == wanted) { return true; } if (wanted.Length >= 3 && text.Length > wanted.Length) { return text.StartsWith(wanted, StringComparison.Ordinal); } return false; } public bool TryFindNearest(string name, Vector3 origin, out Entity nearest, out float distance) { //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_019c: 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) nearest = null; distance = float.MaxValue; if (string.IsNullOrEmpty(name)) { return false; } EnsureBuilt(); if (_types.Count == 0) { return false; } int num = -1; for (int i = 0; i < _types.Count; i++) { if (string.Equals(_types[i].Name, name, StringComparison.OrdinalIgnoreCase)) { num = i; break; } } bool flag = string.Equals(name, "enemy", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "projectile", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "object", StringComparison.OrdinalIgnoreCase); Transform playerTransform = _bridge.PlayerTransform; Component val = null; string category = null; int num2 = int.MaxValue; float num3 = float.MaxValue; HashSet hashSet = new HashSet(); for (int j = 0; j < _types.Count; j++) { if ((num >= 0 && j != num) || (num < 0 && flag && !string.Equals(_typeCategories[j], name, StringComparison.OrdinalIgnoreCase))) { continue; } Object[] array; try { array = Object.FindObjectsOfType(_types[j], false); } catch { continue; } string text = _typeCategories[j]; foreach (Object obj2 in array) { Component val2 = (Component)(object)((obj2 is Component) ? obj2 : null); if ((Object)(object)val2 == (Object)null || !GameBridge.IsAlive(val2) || !val2.gameObject.activeInHierarchy || !hashSet.Add(((Object)val2).GetInstanceID()) || ((Object)(object)playerTransform != (Object)null && val2.transform.IsChildOf(playerTransform))) { continue; } int num4 = MatchRank(val2, text, name); if (num4 >= 0) { Vector3 val3 = val2.transform.position - origin; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude; if (num4 < num2 || (num4 == num2 && sqrMagnitude < num3)) { num2 = num4; num3 = sqrMagnitude; val = val2; category = text; } } } } if ((Object)(object)val != (Object)null) { nearest = ResolveEntity(val, category); distance = Mathf.Sqrt(num3); } return nearest != null; } private int MatchRank(Component component, string category, string name) { if (string.Equals(((object)component).GetType().Name, name, StringComparison.OrdinalIgnoreCase)) { return 0; } if (string.Equals(category, "enemy", StringComparison.Ordinal)) { string text = EnemySubtype(component); if (text.Length > 0) { if (string.Equals(text, name, StringComparison.OrdinalIgnoreCase)) { return 1; } if (text.Length > name.Length && text.StartsWith(name, StringComparison.OrdinalIgnoreCase)) { return 2; } } } string name2 = ((Object)component.gameObject).name; if (!string.IsNullOrEmpty(name2) && string.Equals(name2, name, StringComparison.OrdinalIgnoreCase)) { return 1; } if (string.Equals(category, name, StringComparison.OrdinalIgnoreCase)) { return 3; } return -1; } public string EnemySubtype(Component component) { if ((Object)(object)component == (Object)null) { return string.Empty; } object member = _bridge.GetMember(component, new string[1] { "enemyType" }); string text = ((member != null) ? member.ToString() : string.Empty); if (string.IsNullOrEmpty(text)) { object member2 = _bridge.GetMember(component, new string[1] { "overrideFullName" }); if (member2 is string) { text = (string)member2; } } return text ?? string.Empty; } private Entity ResolveEntity(Component component, string category) { int instanceID = ((Object)component.gameObject).GetInstanceID(); if (_byObject.TryGetValue(instanceID, out var value) && GameBridge.IsAlive(value.Component)) { return value; } return RegisterSpawned(component, category); } public bool TryGetVelocity(Entity entity, out Vector3 velocity) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) velocity = Vector3.zero; if (entity == null || !GameBridge.IsAlive(entity.Component)) { return false; } Rigidbody component = entity.Component.GetComponent(); if ((Object)(object)component == (Object)null) { return false; } velocity = component.velocity; return true; } public Entity Pick(Vector3 origin, Vector3 direction, float maxDistance, out float hitDistance, out bool occluded) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0047: 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) EnsureBuilt(); hitDistance = 0f; occluded = false; float nearestSolid = float.MaxValue; Transform playerTransform = _bridge.PlayerTransform; Entity entity = null; try { int count = Physics.RaycastNonAlloc(origin, direction, _hits, maxDistance, -1, (QueryTriggerInteraction)2); entity = BestHit(count, playerTransform, ref hitDistance, ref nearestSolid); if (entity == null) { count = Physics.SphereCastNonAlloc(origin, 0.5f, direction, _hits, maxDistance, -1, (QueryTriggerInteraction)2); entity = BestHit(count, playerTransform, ref hitDistance, ref nearestSolid); } } catch (Exception ex) { if (!_pickWarned) { _pickWarned = true; _plugin.LogWarning("Entity inspector: pick failed: " + ex.Message); } return null; } occluded = entity != null && nearestSolid < hitDistance - 0.01f; return entity; } private Entity BestHit(int count, Transform player, ref float hitDistance, ref float nearestSolid) { Entity entity = null; float num = float.MaxValue; for (int i = 0; i < count && i < _hits.Length; i++) { Collider collider = ((RaycastHit)(ref _hits[i])).collider; if ((Object)(object)collider == (Object)null || ((Object)(object)player != (Object)null && ((Component)collider).transform.IsChildOf(player))) { continue; } float distance = ((RaycastHit)(ref _hits[i])).distance; Entity entity2 = FromCollider(collider); if (entity2 == null) { if (!collider.isTrigger && distance < nearestSolid) { nearestSolid = distance; } } else if (distance < num) { num = distance; entity = entity2; } } if (entity != null) { hitDistance = num; } return entity; } private Entity FromCollider(Collider collider) { Transform val = ((Component)collider).transform; Entity value; while ((Object)(object)val != (Object)null) { if (_byObject.TryGetValue(((Object)((Component)val).gameObject).GetInstanceID(), out value) && GameBridge.IsAlive(value.Component)) { return value; } val = val.parent; } Component val2 = ((_linkType != null) ? ((Component)collider).GetComponent(_linkType) : null); if ((Object)(object)val2 != (Object)null) { object member = _bridge.GetMember(val2, EnemyLinkNames); Component val3 = (Component)((member is Component) ? member : null); if ((Object)(object)val3 != (Object)null && _byObject.TryGetValue(((Object)val3.gameObject).GetInstanceID(), out value)) { return value; } if ((Object)(object)val3 != (Object)null) { return RegisterSpawned(val3, "enemy"); } } Transform val4 = ((Component)collider).transform; while ((Object)(object)val4 != (Object)null) { for (int i = 0; i < _types.Count; i++) { Component component = ((Component)val4).GetComponent(_types[i]); if ((Object)(object)component != (Object)null) { return RegisterSpawned(component, _typeCategories[i]); } } val4 = val4.parent; } return null; } private Entity RegisterSpawned(Component component, string category) { int instanceID = ((Object)component.gameObject).GetInstanceID(); if (_byObject.TryGetValue(instanceID, out var value) && GameBridge.IsAlive(value.Component)) { return value; } value = new Entity { Id = 10000 + _spawned.Count, Component = component, TypeName = ((object)component).GetType().Name, Category = category, Spawned = true }; _spawned.Add(value); _byObject[instanceID] = value; InvalidateIds(); return value; } public string DescribeState(Entity entity) { if (entity == null || !GameBridge.IsAlive(entity.Component)) { return string.Empty; } _stateText.Length = 0; for (int i = 0; i < StateLabels.Length; i++) { object member = _bridge.GetMember(entity.Component, StateCandidates[i]); if (member != null) { if (_stateText.Length > 0) { _stateText.Append(" "); } _stateText.Append(StateLabels[i]).Append(' '); if (member is float) { _stateText.Append(((float)member).ToString("0.##", CultureInfo.InvariantCulture)); } else if (member is bool) { _stateText.Append(((bool)member) ? "yes" : "no"); } else { _stateText.Append(member.ToString()); } } } return _stateText.ToString(); } } public static class FastForwardProfiler { private static readonly double StampToMs = 1000.0 / (double)Stopwatch.Frequency; private static readonly FrameTiming[] Timings = (FrameTiming[])(object)new FrameTiming[1]; private static long _lastFrameStamp; private static long _windowStart; private static int _frames; private static int _ticks; private static double _frameMs; private static double _updateMs; private static double _tickMs; private static double _traceMs; private static double _endMs; private static double _guiMs; private static double _cpuMs; private static double _gpuMs; private static double _presentMs; private static double _renderThreadMs; private static int _unitySamples; private static double _frameUpdate; private static double _frameTick; private static double _frameTrace; private static double _frameEnd; private static double _frameGui; private static bool _frameTicked; public static bool Enabled; private static int _lastFrame = int.MinValue; public static long Now() { return Stopwatch.GetTimestamp(); } public static double Ms(long start) { return (double)(Stopwatch.GetTimestamp() - start) * StampToMs; } public static void AddUpdate(double ms) { _frameUpdate += ms; } public static void AddTick(double ms) { _frameTick += ms; _frameTicked = true; } public static void AddTrace(double ms) { _frameTrace += ms; } public static void AddEnd(double ms) { _frameEnd += ms; } public static void AddGui(double ms) { _frameGui += ms; } public static void FrameStart(Plugin plugin, int frame) { //IL_03fa: Unknown result type (might be due to invalid IL or missing references) //IL_03ff: Unknown result type (might be due to invalid IL or missing references) if (frame == _lastFrame) { return; } _lastFrame = frame; long timestamp = Stopwatch.GetTimestamp(); if (!Enabled) { Reset(timestamp); return; } if (_lastFrameStamp != 0L) { _frames++; _frameMs += (double)(timestamp - _lastFrameStamp) * StampToMs; _updateMs += _frameUpdate; _tickMs += _frameTick; _traceMs += _frameTrace; _endMs += _frameEnd; _guiMs += _frameGui; if (_frameTicked) { _ticks++; } SampleUnity(); } _lastFrameStamp = timestamp; ClearFrame(); if (_windowStart == 0L) { _windowStart = timestamp; } if (!((double)(timestamp - _windowStart) * StampToMs < 1000.0) && _frames != 0) { double num = _frames; double num2 = _frameMs / num; double num3 = (_updateMs + _endMs + _guiMs) / num; double num4 = Math.Max(0.0, num2 - num3); string text = ((_unitySamples > 0) ? (" | unity cpu " + (_cpuMs / (double)_unitySamples).ToString("0.00") + " gpu " + (_gpuMs / (double)_unitySamples).ToString("0.00") + " render-thread " + (_renderThreadMs / (double)_unitySamples).ToString("0.00") + " present-wait " + (_presentMs / (double)_unitySamples).ToString("0.00") + " ms") : " | unity frame timings unavailable"); plugin?.LogInfo("FF profile: " + (num * 1000.0 / ((double)(timestamp - _windowStart) * StampToMs)).ToString("0") + " fps, " + _ticks + "/" + _frames + " frames ticked | frame " + num2.ToString("0.00") + " ms = tool " + num3.ToString("0.00") + " (update " + ((_updateMs - _tickMs) / num).ToString("0.00") + ", ticks " + ((_tickMs - _traceMs) / num).ToString("0.00") + ", trace " + (_traceMs / num).ToString("0.00") + ", end-frame " + (_endMs / num).ToString("0.00") + ", gui " + (_guiMs / num).ToString("0.00") + ") + game/physics/render/present " + num4.ToString("0.00") + " ms" + text + " | vsync " + QualitySettings.vSyncCount + " target " + Application.targetFrameRate + " queued " + QualitySettings.maxQueuedFrames + " fixedDt " + Time.fixedDeltaTime.ToString("0.####") + " capture " + Time.captureDeltaTime.ToString("0.####") + " screen " + ((object)Screen.fullScreenMode/*cast due to .constrained prefix*/).ToString()); Reset(timestamp); _lastFrameStamp = timestamp; _windowStart = timestamp; } } private static void SampleUnity() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) try { FrameTimingManager.CaptureFrameTimings(); if (FrameTimingManager.GetLatestTimings(1u, Timings) >= 1) { FrameTiming val = Timings[0]; if (!(val.cpuFrameTime <= 0.0)) { _cpuMs += val.cpuMainThreadFrameTime; _gpuMs += val.gpuFrameTime; _presentMs += val.cpuMainThreadPresentWaitTime; _renderThreadMs += val.cpuRenderThreadFrameTime; _unitySamples++; } } } catch (Exception) { } } private static void ClearFrame() { _frameUpdate = 0.0; _frameTick = 0.0; _frameTrace = 0.0; _frameEnd = 0.0; _frameGui = 0.0; _frameTicked = false; } private static void Reset(long now) { _lastFrameStamp = 0L; _windowStart = 0L; _frames = 0; _ticks = 0; _frameMs = (_updateMs = (_tickMs = (_traceMs = (_endMs = (_guiMs = 0.0))))); _cpuMs = (_gpuMs = (_presentMs = (_renderThreadMs = 0.0))); _unitySamples = 0; ClearFrame(); } } public static class FistHudDump { private static Harmony _traceHarmony; private static int _traceHits; public static string Write(GameBridge bridge) { //IL_003a: 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) StringBuilder stringBuilder = new StringBuilder(4096); try { stringBuilder.AppendLine("Dump time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)); Scene activeScene = SceneManager.GetActiveScene(); stringBuilder.AppendLine("Scene: " + ((Scene)(ref activeScene)).name); object fistControl = bridge.FistControl; stringBuilder.AppendLine("== FistControl (" + ((fistControl == null) ? "NULL" : "found") + ")"); if (fistControl != null) { stringBuilder.AppendLine("currentVarNum: " + Show(bridge.GetMember(fistControl, new string[1] { "currentVarNum" }))); stringBuilder.AppendLine("currentOrderNum: " + Show(bridge.GetMember(fistControl, new string[1] { "currentOrderNum" }))); stringBuilder.AppendLine("spawnedArmNums: " + Show(bridge.GetMember(fistControl, new string[1] { "spawnedArmNums" }))); IEnumerable enumerable = bridge.GetMember(fistControl, new string[1] { "spawnedArms" }) as IEnumerable; stringBuilder.AppendLine("spawnedArms:"); if (enumerable != null) { foreach (object item in enumerable) { stringBuilder.AppendLine(" " + DescribeObject(item)); } } stringBuilder.AppendLine("fistPanels:"); if (bridge.GetMember(fistControl, new string[1] { "fistPanels" }) is IEnumerable enumerable2) { int num = 0; foreach (object item2 in enumerable2) { stringBuilder.AppendLine(" [" + num + "] " + DescribeObject(item2)); num++; } } object member = bridge.GetMember(fistControl, new string[1] { "forcedLoadout" }); stringBuilder.AppendLine("forcedLoadout.arm: " + ((member == null) ? "NULL" : (Show(bridge.GetMember(bridge.GetMember(member, new string[1] { "arm" }), new string[1] { "blueVariant" })) + " / " + Show(bridge.GetMember(bridge.GetMember(member, new string[1] { "arm" }), new string[1] { "redVariant" })) + " / " + Show(bridge.GetMember(bridge.GetMember(member, new string[1] { "arm" }), new string[1] { "greenVariant" }))))); } stringBuilder.AppendLine("== PrefsManager"); Type type = bridge.FindType("PrefsManager"); if (type != null) { Object[] array = Resources.FindObjectsOfTypeAll(type); object obj = ((array != null && array.Length != 0) ? array[0] : null); if (obj != null) { MethodInfo method = type.GetMethod("GetBool", new Type[2] { typeof(string), typeof(bool) }); if (method != null) { stringBuilder.AppendLine("armIcons: " + method.Invoke(obj, new object[2] { "armIcons", false })); } else { stringBuilder.AppendLine("armIcons: GetBool not found"); } } else { stringBuilder.AppendLine("PrefsManager instance not found"); } } else { stringBuilder.AppendLine("PrefsManager type not found"); } stringBuilder.AppendLine("== HudController instances"); Type type2 = bridge.FindType("HudController"); if (type2 == null) { stringBuilder.AppendLine("HudController type not found"); } else { Object[] array2 = Resources.FindObjectsOfTypeAll(type2); stringBuilder.AppendLine("count: " + ((array2 != null) ? array2.Length : 0)); Object[] array3 = array2; foreach (Object val in array3) { stringBuilder.AppendLine("-- " + DescribeObject(val)); stringBuilder.AppendLine(" altHud: " + Show(bridge.GetMember(val, new string[1] { "altHud" }))); stringBuilder.AppendLine(" armIcon: " + DescribeObject(bridge.GetMember(val, new string[1] { "armIcon" }))); stringBuilder.AppendLine(" fistFill: " + DescribeObject(bridge.GetMember(val, new string[1] { "fistFill" }))); stringBuilder.AppendLine(" fistBackground: " + DescribeObject(bridge.GetMember(val, new string[1] { "fistBackground" }))); IEnumerable enumerable3 = bridge.GetMember(val, new string[1] { "fistIcons" }) as IEnumerable; stringBuilder.AppendLine(" fistIcons:"); if (enumerable3 == null) { continue; } int num2 = 0; foreach (object item3 in enumerable3) { stringBuilder.AppendLine(" [" + num2 + "] " + DescribeObject(item3)); num2++; } } } } catch (Exception ex) { stringBuilder.AppendLine("DUMP FAILED: " + ex); } string text = null; try { text = Path.Combine(Paths.BepInExRootPath, "uktas_fist_hud_dump.txt"); File.WriteAllText(text, stringBuilder.ToString()); } catch (Exception ex2) { text = "write failed: " + ex2.Message; } return text; } public static void InstallTrace() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown try { if (_traceHarmony == null) { _traceHarmony = new Harmony("com.tas.ultrakill.fisttrace"); MethodInfo method = typeof(GameObject).GetMethod("SetActive", new Type[1] { typeof(bool) }); MethodInfo method2 = typeof(FistHudDump).GetMethod("SetActivePrefix", BindingFlags.Static | BindingFlags.NonPublic); _traceHarmony.Patch((MethodBase)method, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); PatchLogger("FistControl", "Start"); PatchLogger("FistControl", "ResetFists"); PatchLogger("HudController", "Start"); } } catch (Exception ex) { File.WriteAllText(Path.Combine(Paths.BepInExRootPath, "uktas_fist_trace.txt"), "install failed: " + ex); } } private static void PatchLogger(string typeName, string methodName) { //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown try { Type type = AccessTools.TypeByName(typeName); MethodInfo methodInfo = ((type == null) ? null : type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); if (methodInfo == null) { Append("no method " + typeName + "." + methodName); return; } string name = null; if (typeName == "FistControl" && methodName == "Start") { name = "LogFistStart"; } else if (typeName == "FistControl" && methodName == "ResetFists") { name = "LogResetFists"; } else if (typeName == "HudController" && methodName == "Start") { name = "LogHudStart"; } MethodInfo method = typeof(FistHudDump).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic); _traceHarmony.Patch((MethodBase)methodInfo, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Append("patch failed " + typeName + "." + methodName + ": " + ex.Message); } } private static void LogFistStart() { Append("CALL FistControl.Start at " + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)); } private static void LogResetFists() { Append("CALL FistControl.ResetFists at " + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)); } private static void LogHudStart() { Append("CALL HudController.Start at " + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)); } private static void Append(string text) { try { File.AppendAllText(Path.Combine(Paths.BepInExRootPath, "uktas_fist_trace.txt"), text + "\n"); } catch { } } private static void SetActivePrefix(GameObject __instance, bool value) { if ((Object)(object)__instance == (Object)null || _traceHits >= 80) { return; } string name = ((Object)__instance).name; if (value) { if (name == "FistPanel") { Append("SetActive(true) on FistPanel at " + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)); } } else if (!name.EndsWith("(Clone)", StringComparison.Ordinal) && name.IndexOf("GreenArm", StringComparison.Ordinal) < 0 && name.IndexOf("_NewArm", StringComparison.Ordinal) < 0 && (name.IndexOf("Fist", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("Arm", StringComparison.Ordinal) >= 0)) { _traceHits++; try { string contents = "---- SetActive(false) on " + name + " at " + DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture) + "\n" + new StackTrace(1, fNeedFileInfo: false).ToString() + "\n"; File.AppendAllText(Path.Combine(Paths.BepInExRootPath, "uktas_fist_trace.txt"), contents); } catch { } } } private static string Show(object value) { if (value == null) { return "NULL"; } return value.ToString(); } private static string DescribeObject(object value) { if (value == null) { return "NULL"; } GameObject val = (GameObject)((value is GameObject) ? value : null); if ((Object)(object)val == (Object)null) { Component val2 = (Component)((value is Component) ? value : null); if ((Object)(object)val2 != (Object)null) { val = val2.gameObject; } } if ((Object)(object)val == (Object)null) { return value.GetType().Name + " = " + value; } string text = ((Object)val).name; Transform parent = val.transform.parent; while ((Object)(object)parent != (Object)null) { text = ((Object)parent).name + "/" + text; parent = parent.parent; } return text + " activeSelf=" + val.activeSelf + " activeInHierarchy=" + val.activeInHierarchy; } } public sealed class GameBridge { public sealed class LevelStatsInfo { public int Kills; public int Score; public float Seconds; public int Restarts; public string KillsRank = "--"; public string ScoreRank = "--"; public string TimeRank = "--"; public string TotalRank = "--"; public int KillsForS = -1; public int ScoreForS = -1; public int TimeForS = -1; public bool EndScreen; public int Challenge = -1; } public sealed class CoinInfo { public Component Component; public int Id; public string Name = string.Empty; public Vector3 Position; public bool Shot; public bool ShotByEnemy; public float Power; public int Ricochets; public Vector3 TargetPoint; public bool HasTargetPoint; } private readonly Plugin _plugin; private Type _newMovementType; private Type _cameraControllerType; private Type _gunControlType; private Type _inputManagerType; private Type _optionsManagerType; private Type _monoSingletonType; private Type _baseInputType; private Type _fistControlType; private Type _sceneHelperType; private bool _sceneHelperSearched; private object _newMovement; private object _cameraController; private object _gunControl; private object _inputManager; private object _optionsManager; private object _fistControl; private readonly Dictionary> _memberCache = new Dictionary>(); private readonly Dictionary _typeCache = new Dictionary(); private readonly Dictionary _typeMissTime = new Dictionary(); private int _lastResolveFrame = -1000; private string _sceneName = string.Empty; private Type _statsManagerType; private object _statsManager; private Type _challengeManagerType; private object _challengeManager; private static readonly string[] RankLetters = new string[5] { "D", "C", "B", "A", "S" }; private EntityRegistry _entities; private readonly Dictionary _singletonMissFrame = new Dictionary(); private Type _prefsManagerType; private object _prefsManager; private PropertyInfo _prefsInstanceProperty; private bool _prefsInstancePropertyLooked; private Type _gunSetterType; private object _gunSetter; private MethodInfo _checkGearMethod; private MethodInfo _prefsGetIntMethod; private static readonly string[] VariantMembers = new string[3] { "blueVariant", "redVariant", "greenVariant" }; private MethodInfo _layerMaskGet; private object _lmdEnvironment; private bool _layerMaskResolved; private Type _hookArmType; private object _hookArm; private Type _hookPointType; private Type _coinType; public static readonly string[] AimLockProjectileTypes = new string[4] { "Grenade", "Rocket", "Coin", "Cannonball" }; private bool _shotgunReadyWarned; public bool TypesResolved { get; private set; } public string LastError { get; private set; } public Type NewMovementType { get { ResolveTypes(); return _newMovementType; } } public Type CameraControllerType { get { ResolveTypes(); return _cameraControllerType; } } public Type GunControlType { get { ResolveTypes(); return _gunControlType; } } public Type InputManagerType { get { ResolveTypes(); return _inputManagerType; } } public Type OptionsManagerType { get { ResolveTypes(); return _optionsManagerType; } } public Type BaseInputType { get { ResolveTypes(); return _baseInputType; } } public object NewMovement => ResolveSingleton(ref _newMovement, _newMovementType ?? (_newMovementType = FindType("NewMovement"))); public object CameraController => ResolveSingleton(ref _cameraController, _cameraControllerType ?? (_cameraControllerType = FindType("CameraController"))); public object GunControl => ResolveSingleton(ref _gunControl, _gunControlType ?? (_gunControlType = FindType("GunControl"))); public object InputManager => ResolveSingleton(ref _inputManager, _inputManagerType ?? (_inputManagerType = FindType("InputManager"))); public object OptionsManager => ResolveSingleton(ref _optionsManager, _optionsManagerType ?? (_optionsManagerType = FindType("OptionsManager"))); public object FistControl => ResolveSingleton(ref _fistControl, _fistControlType ?? (_fistControlType = FindType("FistControl"))); public object StatsManager => ResolveSingleton(ref _statsManager, _statsManagerType ?? (_statsManagerType = FindType("StatsManager"))); public object ChallengeManager => ResolveSingleton(ref _challengeManager, _challengeManagerType ?? (_challengeManagerType = FindType("ChallengeManager"))); public EntityRegistry Entities => _entities ?? (_entities = new EntityRegistry(_plugin, this)); public Component PlayerComponent { get { object newMovement = NewMovement; return (Component)((newMovement is Component) ? newMovement : null); } } public Transform PlayerTransform { get { Component playerComponent = PlayerComponent; if (!((Object)(object)playerComponent != (Object)null)) { return null; } return playerComponent.transform; } } public bool PlayerControlActivated { get { object newMovement = NewMovement; if (newMovement == null) { return false; } object member = GetMember(newMovement, new string[4] { "activated", "active", "canMove", "movementEnabled" }); if (member != null) { return ToBool(member, fallback: true); } return true; } } public float PlayerY { get { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (!TryGetPlayerPosition(out var position)) { return 0f; } return position.y; } } public bool PlayerBelowKillPlane { get { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (TryGetPlayerPosition(out var position)) { return position.y < _plugin.KillPlaneY.Value; } return false; } } public string SceneName { get { //IL_000e: 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) if (string.IsNullOrEmpty(_sceneName)) { Scene activeScene = SceneManager.GetActiveScene(); _sceneName = ((Scene)(ref activeScene)).name; } return _sceneName; } } public Type SceneHelperType { get { if (!_sceneHelperSearched) { _sceneHelperSearched = true; _sceneHelperType = FindType("SceneHelper"); } return _sceneHelperType; } } public string CurrentLevelScene { get { string sceneName = SceneName; if (LevelIdFromScene(sceneName).Length > 0) { return sceneName; } string text = ReadStaticSceneHelperString("CurrentScene"); if (!string.IsNullOrEmpty(text)) { return text; } return sceneName; } } public string CurrentLevelId => LevelIdFromScene(CurrentLevelScene); public Rigidbody PlayerRigidbody { get { object newMovement = NewMovement; if (newMovement == null) { return null; } object member = GetMember(newMovement, new string[4] { "rb", "body", "rigidbody", "rigidBody" }); Rigidbody val = (Rigidbody)((member is Rigidbody) ? member : null); if ((Object)(object)val != (Object)null) { return val; } Component val2 = (Component)((newMovement is Component) ? newMovement : null); if (!((Object)(object)val2 != (Object)null)) { return null; } return val2.GetComponent(); } } public int GunSlot { get { object gunControl = GunControl; if (gunControl == null) { return -1; } return ToInt(GetMember(gunControl, new string[4] { "currentSlotIndex", "currentSlot", "slot", "weaponIndex" }), -1); } set { object gunControl = GunControl; if (gunControl != null) { SetMember(gunControl, new string[3] { "currentSlotIndex", "currentSlot", "slot" }, value); } } } public int GunVariation { get { object gunControl = GunControl; if (gunControl == null) { return -1; } return ToInt(GetMember(gunControl, new string[5] { "currentVariationIndex", "currentVariation", "variation", "currentVariant", "variant" }), -1); } set { object gunControl = GunControl; if (gunControl != null) { SetMember(gunControl, new string[3] { "currentVariationIndex", "currentVariation", "currentVariant" }, value); } } } public bool PrefsManagerRetryable { get; private set; } public object GunSetter => ResolveSingleton(ref _gunSetter, _gunSetterType ?? (_gunSetterType = FindType("GunSetter"))); public object InputSource { get { object inputManager = InputManager; if (inputManager == null) { return null; } return GetMember(inputManager, new string[4] { "InputSource", "inputSource", "inputs", "Inputs" }); } } public Dictionary InputBindings { get { object inputManager = InputManager; if (inputManager == null) { return null; } return GetMember(inputManager, new string[4] { "inputsDictionary", "inputDictionary", "bindings", "InputsDictionary" }) as Dictionary; } } public int EnemyCount { get { Type type = FindType("EnemyIdentifier"); if (type == null) { return 0; } Object[] array; try { array = Object.FindObjectsOfType(type, true); } catch { return 0; } int num = 0; for (int i = 0; i < array.Length; i++) { if (array[i] != (Object)null) { num++; } } return num; } } public bool IsMainMenu { get { object optionsManager = OptionsManager; if (optionsManager == null) { return false; } return ToBool(GetMember(optionsManager, new string[1] { "mainMenu" }), fallback: false); } } public GameBridge(Plugin plugin) { _plugin = plugin; } public bool TryGetLevelTime(out float seconds) { seconds = 0f; object statsManager = StatsManager; if (statsManager == null) { return false; } object member = GetMember(statsManager, new string[1] { "seconds" }); if (member == null) { return false; } seconds = ToFloat(member, 0f); return true; } private static int RankIndex(int[] thresholds, float value, bool reverse) { if (thresholds == null || thresholds.Length == 0) { return -1; } int i; for (i = 0; i < thresholds.Length && (reverse ? (value <= (float)thresholds[i]) : (value >= (float)thresholds[i])); i++) { } return Math.Min(i, 4); } private static string RankLetter(int index) { if (index < 0 || index >= RankLetters.Length) { return "--"; } return RankLetters[index]; } private string ReadScreenText(object owner, string field) { object member = GetMember(owner, new string[1] { field }); if (!IsAlive(member)) { return string.Empty; } string text = GetMember(member, new string[1] { "text" }) as string; if (string.IsNullOrEmpty(text)) { return string.Empty; } return Regex.Replace(text, "<[^>]*>", string.Empty).Trim(); } public bool TryGetLevelStats(out LevelStatsInfo info) { info = null; object statsManager = StatsManager; if (statsManager == null) { return false; } object member = GetMember(statsManager, new string[1] { "seconds" }); object member2 = GetMember(statsManager, new string[1] { "kills" }); object member3 = GetMember(statsManager, new string[1] { "stylePoints" }); if (member == null || member2 == null || member3 == null) { return false; } LevelStatsInfo levelStatsInfo = new LevelStatsInfo(); levelStatsInfo.Seconds = ToFloat(member, 0f); levelStatsInfo.Kills = ToInt(member2, 0); levelStatsInfo.Score = ToInt(member3, 0); levelStatsInfo.Restarts = ToInt(GetMember(statsManager, new string[1] { "restarts" }), 0); int[] array = GetMember(statsManager, new string[1] { "killRanks" }) as int[]; int[] array2 = GetMember(statsManager, new string[1] { "styleRanks" }) as int[]; int[] array3 = GetMember(statsManager, new string[1] { "timeRanks" }) as int[]; int num = RankIndex(array, levelStatsInfo.Kills, reverse: false); int num2 = RankIndex(array2, levelStatsInfo.Score, reverse: false); int num3 = RankIndex(array3, levelStatsInfo.Seconds, reverse: true); levelStatsInfo.KillsRank = RankLetter(num); levelStatsInfo.ScoreRank = RankLetter(num2); levelStatsInfo.TimeRank = RankLetter(num3); if (array != null && array.Length != 0) { levelStatsInfo.KillsForS = array[^1]; } if (array2 != null && array2.Length != 0) { levelStatsInfo.ScoreForS = array2[^1]; } if (array3 != null && array3.Length != 0) { levelStatsInfo.TimeForS = array3[^1]; } bool flag = false; object member4 = GetMember(statsManager, new string[1] { "asscon" }); if (IsAlive(member4)) { flag = ToBool(GetMember(member4, new string[1] { "cheatsEnabled" }), fallback: false); } if (flag) { levelStatsInfo.TotalRank = "_"; } else if (num >= 0 && num2 >= 0 && num3 >= 0) { int num4 = Math.Max(0, num + num2 + num3 - levelStatsInfo.Restarts); if (num4 == 12) { levelStatsInfo.TotalRank = "P"; } else { levelStatsInfo.TotalRank = RankLetter(Math.Min(4, Mathf.RoundToInt((float)num4 / 3f))); } } if (ToBool(GetMember(statsManager, new string[1] { "infoSent" }), fallback: false)) { object member5 = GetMember(statsManager, new string[1] { "fr" }); if (IsAlive(member5)) { string text = ReadScreenText(member5, "timeRank"); string text2 = ReadScreenText(member5, "killsRank"); string text3 = ReadScreenText(member5, "styleRank"); string text4 = ReadScreenText(member5, "totalRank"); if (text.Length > 0) { levelStatsInfo.TimeRank = text; } if (text2.Length > 0) { levelStatsInfo.KillsRank = text2; } if (text3.Length > 0) { levelStatsInfo.ScoreRank = text3; } if (text4.Length > 0) { levelStatsInfo.TotalRank = text4; } levelStatsInfo.EndScreen = true; } } object challengeManager = ChallengeManager; if (challengeManager != null) { bool flag2 = ToBool(GetMember(challengeManager, new string[1] { "challengeDone" }), fallback: false); bool flag3 = ToBool(GetMember(challengeManager, new string[1] { "challengeFailed" }), fallback: false); levelStatsInfo.Challenge = (flag3 ? 2 : (flag2 ? 1 : 0)); } info = levelStatsInfo; return true; } public bool TryGetPlayerPosition(out Vector3 position) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) Transform playerTransform = PlayerTransform; if ((Object)(object)playerTransform == (Object)null) { position = Vector3.zero; return false; } position = playerTransform.position; return true; } public static string LevelIdFromScene(string scene) { if (string.IsNullOrEmpty(scene)) { return string.Empty; } string text = scene.Trim(); if (text.EndsWith(".unity", StringComparison.OrdinalIgnoreCase)) { text = text.Substring(0, text.Length - ".unity".Length).Trim(); } if (text.StartsWith("Level ", StringComparison.OrdinalIgnoreCase)) { text = text.Substring("Level ".Length).Trim(); } if (text.Length < 3 || !char.IsDigit(text[0]) || text.IndexOf('-') < 0) { return string.Empty; } return text; } private string ReadStaticSceneHelperString(string propertyName) { try { Type sceneHelperType = SceneHelperType; if (sceneHelperType == null) { return null; } PropertyInfo property = sceneHelperType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (property == null) { return null; } return property.GetValue(null, null) as string; } catch { return null; } } public void InvalidateScene() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) Scene activeScene = SceneManager.GetActiveScene(); _sceneName = ((Scene)(ref activeScene)).name; _newMovement = null; _cameraController = null; _gunControl = null; _inputManager = null; _optionsManager = null; _fistControl = null; _gunSetter = null; _singletonMissFrame.Clear(); } private void ResolveTypes() { if (!TypesResolved && Time.frameCount - _lastResolveFrame >= 30) { _lastResolveFrame = Time.frameCount; _newMovementType = _newMovementType ?? FindType("NewMovement"); _cameraControllerType = _cameraControllerType ?? FindType("CameraController"); _gunControlType = _gunControlType ?? FindType("GunControl"); _inputManagerType = _inputManagerType ?? FindType("InputManager"); _optionsManagerType = _optionsManagerType ?? FindType("OptionsManager"); _monoSingletonType = _monoSingletonType ?? FindType("MonoSingleton`1"); _baseInputType = _baseInputType ?? FindType("BaseInput"); TypesResolved = _newMovementType != null && _cameraControllerType != null && _gunControlType != null && _inputManagerType != null; } } private object ResolveSingleton(ref object cache, Type type) { if (type == null) { return null; } if (IsAlive(cache)) { return cache; } cache = null; if (_singletonMissFrame.TryGetValue(type, out var value) && Time.frameCount - value < 20) { return null; } try { if (_monoSingletonType == null) { _monoSingletonType = FindType("MonoSingleton`1"); } if (_monoSingletonType != null) { PropertyInfo property = _monoSingletonType.MakeGenericType(type).GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (property != null) { object value2 = property.GetValue(null, null); if (IsAlive(value2)) { cache = value2; return cache; } } } Object val = Object.FindObjectOfType(type); if (val != (Object)null) { cache = val; } } catch (Exception ex) { LastError = "Singleton resolve failed for " + type.Name + ": " + ex.Message; } if (cache == null) { _singletonMissFrame[type] = Time.frameCount; } else { _singletonMissFrame.Remove(type); } return cache; } public static bool IsAlive(object value) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (value == null) { return false; } if (value is Object) { return (Object)value != (Object)null; } return true; } public Type FindType(string simpleName) { if (string.IsNullOrEmpty(simpleName)) { return null; } if (_typeCache.TryGetValue(simpleName, out var value) && value != null) { return value; } if (_typeMissTime.TryGetValue(simpleName, out var value2) && Time.unscaledTime - value2 < 5f) { return null; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); Array.Sort(assemblies, delegate(Assembly x, Assembly y) { int num3 = ((!x.GetName().Name.StartsWith("Assembly-CSharp", StringComparison.Ordinal)) ? 1 : 0); int value3 = ((!y.GetName().Name.StartsWith("Assembly-CSharp", StringComparison.Ordinal)) ? 1 : 0); return num3.CompareTo(value3); }); for (int num = 0; num < assemblies.Length; num++) { Type[] types; try { types = assemblies[num].GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } catch { continue; } if (types == null) { continue; } foreach (Type type in types) { if (type != null && type.Name == simpleName && !type.IsAbstract && !type.ContainsGenericParameters) { _typeCache[simpleName] = type; return type; } } } _typeMissTime[simpleName] = Time.unscaledTime; return null; } public MemberInfo FindMember(Type type, string name) { if (type == null || string.IsNullOrEmpty(name)) { return null; } if (!_memberCache.TryGetValue(type, out var value)) { value = new Dictionary(StringComparer.Ordinal); _memberCache[type] = value; } if (value.TryGetValue(name, out var value2)) { return value2; } Type type2 = type; while (type2 != null && type2 != typeof(MonoBehaviour) && type2 != typeof(object)) { FieldInfo field = type2.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { value[name] = field; return field; } PropertyInfo property = type2.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { value[name] = property; return property; } type2 = type2.BaseType; } value[name] = null; return null; } public MemberInfo FindMember(object target, string[] candidates) { if (target == null || candidates == null) { return null; } Type type = target.GetType(); for (int i = 0; i < candidates.Length; i++) { MemberInfo memberInfo = FindMember(type, candidates[i]); if (memberInfo != null) { return memberInfo; } } return null; } public object GetMemberValue(object target, MemberInfo member) { if (target == null || member == null) { return null; } try { FieldInfo fieldInfo = member as FieldInfo; if (fieldInfo != null) { return fieldInfo.GetValue(target); } PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null && propertyInfo.CanRead) { return propertyInfo.GetValue(target, null); } } catch (Exception ex) { LastError = "Get " + member.Name + " failed: " + ex.Message; } return null; } public object GetMember(object target, string[] candidates) { MemberInfo memberInfo = FindMember(target, candidates); if (!(memberInfo == null)) { return GetMemberValue(target, memberInfo); } return null; } public bool SetMemberValue(object target, MemberInfo member, object value) { if (target == null || member == null) { return false; } try { FieldInfo fieldInfo = member as FieldInfo; if (fieldInfo != null) { fieldInfo.SetValue(target, Coerce(value, fieldInfo.FieldType)); return true; } PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null && propertyInfo.CanWrite) { propertyInfo.SetValue(target, Coerce(value, propertyInfo.PropertyType), null); return true; } } catch (Exception ex) { LastError = "Set " + member.Name + " failed: " + ex.Message; } return false; } public bool SetMember(object target, string[] candidates, object value) { MemberInfo memberInfo = FindMember(target, candidates); if (memberInfo != null) { return SetMemberValue(target, memberInfo, value); } return false; } private static object Coerce(object value, Type targetType) { if (value == null) { return null; } if (targetType.IsInstanceOfType(value)) { return value; } if (targetType.IsEnum) { return Enum.ToObject(targetType, Convert.ToInt64(value)); } if (targetType == typeof(float)) { return Convert.ToSingle(value); } if (targetType == typeof(int)) { return Convert.ToInt32(value); } if (targetType == typeof(bool)) { return Convert.ToBoolean(value); } if (targetType == typeof(double)) { return Convert.ToDouble(value); } return value; } public static float ToFloat(object value, float fallback) { if (value == null) { return fallback; } try { return Convert.ToSingle(value); } catch { return fallback; } } public static int ToInt(object value, int fallback) { if (value == null) { return fallback; } try { return Convert.ToInt32(value); } catch { return fallback; } } public static bool ToBool(object value, bool fallback) { if (value == null) { return fallback; } try { return Convert.ToBoolean(value); } catch { return fallback; } } public bool TryGetPlayerVelocity(out Vector3 velocity) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) Rigidbody playerRigidbody = PlayerRigidbody; if ((Object)(object)playerRigidbody != (Object)null) { velocity = playerRigidbody.velocity; return true; } velocity = Vector3.zero; return false; } public bool SetPlayerVelocity(Vector3 velocity) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) Rigidbody playerRigidbody = PlayerRigidbody; if ((Object)(object)playerRigidbody == (Object)null || playerRigidbody.isKinematic) { return false; } playerRigidbody.velocity = velocity; return true; } public bool TryGetCameraAngles(out float pitch, out float yaw) { //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) pitch = 0f; yaw = 0f; object cameraController = CameraController; if (cameraController != null) { object member = GetMember(cameraController, new string[4] { "rotationX", "pitch", "xRot", "rotX" }); object member2 = GetMember(cameraController, new string[4] { "rotationY", "yaw", "yRot", "rotY" }); if (member != null && member2 != null) { pitch = 0f - ToFloat(member, 0f); yaw = ToFloat(member2, 0f); return true; } object member3 = GetMember(cameraController, new string[3] { "cam", "camera", "camTransform" }); Camera val = (Camera)((member3 is Camera) ? member3 : null); Transform val2 = (Transform)((member3 is Transform) ? member3 : null); if ((Object)(object)val != (Object)null) { val2 = ((Component)val).transform; } Transform playerTransform = PlayerTransform; if ((Object)(object)val2 != (Object)null && (Object)(object)playerTransform != (Object)null) { pitch = NormalizePitch(val2.eulerAngles.x); yaw = playerTransform.eulerAngles.y; return true; } } Transform playerTransform2 = PlayerTransform; if ((Object)(object)playerTransform2 != (Object)null) { pitch = 0f; yaw = playerTransform2.eulerAngles.y; return true; } return false; } public bool SetCameraAngles(float pitch, float yaw) { //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) pitch = Mathf.Clamp(pitch, -89.9f, 89.9f); bool flag = false; object cameraController = CameraController; if (cameraController != null) { MemberInfo memberInfo = FindMember(cameraController, new string[4] { "rotationX", "pitch", "xRot", "rotX" }); MemberInfo memberInfo2 = FindMember(cameraController, new string[4] { "rotationY", "yaw", "yRot", "rotY" }); if (memberInfo != null && memberInfo2 != null) { flag = SetMemberValue(cameraController, memberInfo, 0f - pitch); flag &= SetMemberValue(cameraController, memberInfo2, yaw); } } if (!flag) { if (TryGetCameraTransform(out var transform)) { transform.localEulerAngles = new Vector3(pitch, 0f, 0f); flag = true; } Transform playerTransform = PlayerTransform; if ((Object)(object)playerTransform != (Object)null) { playerTransform.rotation = Quaternion.Euler(0f, yaw, 0f); flag = true; } } return flag; } public bool ApplyCameraTransform(float pitch, float yaw) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) bool result = false; if (TryGetCameraTransform(out var transform)) { transform.localEulerAngles = new Vector3(Mathf.Clamp(pitch, -89.9f, 89.9f), 0f, 0f); result = true; } Transform playerTransform = PlayerTransform; if ((Object)(object)playerTransform != (Object)null) { playerTransform.rotation = Quaternion.Euler(0f, yaw, 0f); result = true; } return result; } public bool TryGetCameraTransform(out Transform transform) { transform = null; object cameraController = CameraController; if (cameraController == null) { return false; } object member = GetMember(cameraController, new string[3] { "cam", "camera", "camTransform" }); Camera val = (Camera)((member is Camera) ? member : null); if ((Object)(object)val != (Object)null) { transform = ((Component)val).transform; return true; } transform = (Transform)((member is Transform) ? member : null); return (Object)(object)transform != (Object)null; } private static float NormalizePitch(float eulerX) { float num = eulerX; if (num > 180f) { num -= 360f; } return Mathf.Clamp(num, -89.9f, 89.9f); } public bool SwitchWeaponSlot(int oneBasedSlot) { object gunControl = GunControl; if (gunControl == null) { return false; } string[] array = new string[5] { "SwitchWeapon", "ChangeWeapon", "SetWeapon", "SwitchGun", "ChangeGun" }; for (int i = 0; i < array.Length; i++) { MethodInfo methodInfo = FindMethod(gunControl.GetType(), array[i], 1); if (methodInfo == null) { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 1) { try { object obj = ((parameters[0].ParameterType == typeof(int)) ? ((object)(oneBasedSlot - 1)) : ((object)oneBasedSlot)); methodInfo.Invoke(gunControl, new object[1] { obj }); return true; } catch { } } } GunSlot = oneBasedSlot - 1; return true; } public bool SetGunVariation(int oneBasedVariation) { object gunControl = GunControl; if (gunControl == null) { return false; } return SetMember(gunControl, new string[4] { "currentVariation", "variation", "currentVariant", "variant" }, Math.Max(0, oneBasedVariation - 1)); } public bool EquipFist(int variant) { object fistControl = FistControl; if (fistControl == null) { LastError = "FistControl not found (no player loaded?)."; return false; } MethodInfo methodInfo = FindMethod(fistControl.GetType(), "ForceArm", 2); ParameterInfo[] array = ((methodInfo != null) ? methodInfo.GetParameters() : null); if (array == null || array[0].ParameterType != typeof(int) || array[1].ParameterType != typeof(bool)) { LastError = "FistControl.ForceArm(int, bool) not found in this game version."; return false; } try { object obj = methodInfo.Invoke(fistControl, new object[2] { variant, false }); if (obj is bool && !(bool)obj) { LastError = "that arm is not in the current loadout (not owned, or disabled in the arm settings)."; return false; } return true; } catch (Exception ex) { LastError = "FistControl.ForceArm failed: " + UnwrapMessage(ex); return false; } } private object GetPrefsManager(out string error) { //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) error = null; PrefsManagerRetryable = false; if (IsAlive(_prefsManager)) { return _prefsManager; } _prefsManager = null; if (_prefsManagerType == null) { _prefsManagerType = FindType("PrefsManager"); } if (_prefsManagerType == null) { error = "PrefsManager type not found"; return null; } string text = null; Scene val2; try { if (!_prefsInstancePropertyLooked) { _prefsInstancePropertyLooked = true; Type baseType = _prefsManagerType.BaseType; while (baseType != null) { if (baseType.IsGenericType && baseType.Name == "MonoSingleton`1") { _prefsInstanceProperty = baseType.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); break; } baseType = baseType.BaseType; } } if (_prefsInstanceProperty != null) { object value = _prefsInstanceProperty.GetValue(null, null); if (IsAlive(value)) { _prefsManager = value; } } if (_prefsManager == null) { Object[] array = Resources.FindObjectsOfTypeAll(_prefsManagerType); int num = 0; while (array != null && num < array.Length) { Object obj = array[num]; Component val = (Component)(object)((obj is Component) ? obj : null); if ((Object)(object)val != (Object)null) { val2 = val.gameObject.scene; if (((Scene)(ref val2)).IsValid()) { _prefsManager = val; break; } } num++; } } } catch (Exception ex) { text = UnwrapMessage(ex); _prefsManager = null; } if (_prefsManager == null) { string text2; try { val2 = SceneManager.GetActiveScene(); text2 = ((Scene)(ref val2)).name; } catch { text2 = "?"; } error = "PrefsManager instance not available yet (scene: " + (string.IsNullOrEmpty(text2) ? "?" : text2) + ")" + ((text != null) ? (": " + text) : string.Empty); PrefsManagerRetryable = true; } return _prefsManager; } public int GetDifficulty() { try { string error; object prefsManager = GetPrefsManager(out error); if (prefsManager == null) { LastError = error; return -1; } MethodInfo methodInfo = FindMethod(prefsManager.GetType(), "GetInt", 2); ParameterInfo[] array = ((methodInfo != null) ? methodInfo.GetParameters() : null); if (array == null || array[0].ParameterType != typeof(string) || array[1].ParameterType != typeof(int)) { LastError = "PrefsManager.GetInt not found"; return -1; } object obj = methodInfo.Invoke(prefsManager, new object[2] { "difficulty", 0 }); return (obj is int) ? ((int)obj) : (-1); } catch (Exception ex) { LastError = "PrefsManager.GetInt failed: " + UnwrapMessage(ex); return -1; } } public bool SetDifficulty(int difficulty) { try { string error; object prefsManager = GetPrefsManager(out error); if (prefsManager == null) { LastError = error; return false; } MethodInfo methodInfo = FindMethod(prefsManager.GetType(), "SetInt", 2); ParameterInfo[] array = ((methodInfo != null) ? methodInfo.GetParameters() : null); if (array == null || array[0].ParameterType != typeof(string) || array[1].ParameterType != typeof(int)) { LastError = "PrefsManager.SetInt not found"; return false; } methodInfo.Invoke(prefsManager, new object[2] { "difficulty", difficulty }); return true; } catch (Exception ex) { LastError = "PrefsManager.SetInt failed: " + UnwrapMessage(ex); return false; } } private static MethodInfo FindMethod(Type type, string name, int parameterCount) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { if (methods[i].Name == name && methods[i].GetParameters().Length == parameterCount) { return methods[i]; } } return null; } private int ReadGear(string key) { if (_checkGearMethod == null) { Type type = WeaponUnlock.FindGameType("GameProgressSaver"); if (type != null) { _checkGearMethod = type.GetMethod("CheckGear", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(string) }, null); } } if (_checkGearMethod == null) { return -1; } return ToInt(_checkGearMethod.Invoke(null, new object[1] { key }), -1); } private object FindPlayerLoadout() { try { Type type = FindType("PlayerLoadout"); if (type == null) { return null; } Object val = Object.FindObjectOfType(type); return (val != (Object)null) ? val : null; } catch { return null; } } public bool TryCaptureLoadout(out List weapons, out Dictionary loadout) { weapons = null; loadout = null; try { if (NewMovement == null) { LastError = "No player loaded."; return false; } string error; object prefsManager = GetPrefsManager(out error); if (prefsManager == null) { LastError = error; return false; } if (_prefsGetIntMethod == null) { _prefsGetIntMethod = FindMethod(prefsManager.GetType(), "GetInt", 2); } if (_prefsGetIntMethod == null) { LastError = "PrefsManager.GetInt not found"; return false; } List list = new List(); for (int i = 0; i < WeaponUnlock.GearKeys.Length; i++) { string text = WeaponUnlock.GearKeys[i]; int num = ReadGear(text); if (num < 0) { LastError = "GameProgressSaver.CheckGear(string) not found in this game version."; return false; } if (num != 0 && (text.EndsWith("alt", StringComparison.Ordinal) || ToInt(_prefsGetIntMethod.Invoke(prefsManager, new object[2] { "weapon." + text, 1 }), 1) != 0)) { list.Add(text); } } object gunSetter = GunSetter; object obj; if (gunSetter != null) { obj = GetMember(gunSetter, new string[1] { "forcedLoadout" }); } else { object obj2 = FindPlayerLoadout(); obj = ((obj2 != null) ? GetMember(obj2, new string[1] { "loadout" }) : null); } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); for (int j = 0; j < WeaponUnlock.LoadoutFields.Length; j++) { string text2 = WeaponUnlock.LoadoutFields[j]; object obj3 = ((obj != null) ? GetMember(obj, new string[1] { text2 }) : null); char[] array = new char[3]; for (int k = 0; k < array.Length; k++) { object value = ((obj3 != null) ? GetMember(obj3, new string[1] { VariantMembers[k] }) : null); array[k] = WeaponUnlock.OptionToChar(ToInt(value, 0)); } dictionary[text2] = new string(array); } weapons = list; loadout = dictionary; return true; } catch (Exception ex) { LastError = "Loadout capture failed: " + UnwrapMessage(ex); weapons = null; loadout = null; return false; } } public bool ApplyLoadout(Dictionary loadout) { if (loadout == null || loadout.Count == 0) { return true; } object gunSetter = GunSetter; if (gunSetter == null) { LastError = "No player loaded."; return false; } try { List list = new List(); object obj = GetMember(gunSetter, new string[1] { "forcedLoadout" }); if (obj == null) { obj = CreateForcedLoadout(); if (obj == null) { LastError = "ForcedLoadout could not be created in this game version."; return false; } SetMember(gunSetter, new string[1] { "forcedLoadout" }, obj); } list.Add(obj); object fistControl = FistControl; if (fistControl != null) { object member = GetMember(fistControl, new string[1] { "forcedLoadout" }); if (member == null) { SetMember(fistControl, new string[1] { "forcedLoadout" }, obj); } else if (!ContainsReference(list, member)) { list.Add(member); } } object obj2 = FindPlayerLoadout(); object obj3 = ((obj2 != null) ? GetMember(obj2, new string[1] { "loadout" }) : null); if (obj3 != null && !ContainsReference(list, obj3)) { list.Add(obj3); } for (int i = 0; i < list.Count; i++) { foreach (KeyValuePair item in loadout) { WriteVariantCode(list[i], item.Key, item.Value); } } return true; } catch (Exception ex) { LastError = "Applying the loadout failed: " + UnwrapMessage(ex); return false; } } private static bool ContainsReference(List list, object value) { for (int i = 0; i < list.Count; i++) { if (list[i] == value) { return true; } } return false; } private object CreateForcedLoadout() { Type type = FindType("ForcedLoadout"); if (type == null) { return null; } object obj = Activator.CreateInstance(type); FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { Type fieldType = fields[i].FieldType; if (fieldType.IsClass && fieldType.GetConstructor(Type.EmptyTypes) != null) { fields[i].SetValue(obj, Activator.CreateInstance(fieldType)); } } return obj; } private void WriteVariantCode(object forced, string field, string code) { if (forced == null || string.IsNullOrEmpty(code) || code.Length != 3) { return; } MemberInfo memberInfo = FindMember(forced.GetType(), field); if (memberInfo == null) { return; } object obj = GetMemberValue(forced, memberInfo); if (obj == null) { FieldInfo fieldInfo = memberInfo as FieldInfo; if (fieldInfo == null || fieldInfo.FieldType.GetConstructor(Type.EmptyTypes) == null) { return; } obj = Activator.CreateInstance(fieldInfo.FieldType); SetMemberValue(forced, memberInfo, obj); } for (int i = 0; i < VariantMembers.Length; i++) { if (WeaponUnlock.TryOptionFromChar(code[i], out var option)) { SetMember(obj, new string[1] { VariantMembers[i] }, option); } } } public bool ResetWeaponSlots() { object gunSetter = GunSetter; if (gunSetter == null) { LastError = "No player loaded."; return false; } try { MethodInfo methodInfo = FindMethod(gunSetter.GetType(), "ResetWeapons", 1); ParameterInfo[] array = ((methodInfo != null) ? methodInfo.GetParameters() : null); if (array == null || array[0].ParameterType != typeof(bool)) { LastError = "GunSetter.ResetWeapons(bool) not found in this game version."; return false; } methodInfo.Invoke(gunSetter, new object[1] { true }); } catch (Exception ex) { LastError = "GunSetter.ResetWeapons failed: " + UnwrapMessage(ex); return false; } RefreshArms(); return true; } private void RefreshArms() { object fistControl = FistControl; if (fistControl == null) { return; } MethodInfo methodInfo = FindMethod(fistControl.GetType(), "ResetFists", 0); if (methodInfo == null) { return; } try { List list = ReadSpawnedArmNumbers(fistControl); List list2 = WantedArmNumbers(fistControl); if (list == null || list2 == null) { return; } _plugin.LogInfo("Arms: spawned [" + string.Join(",", list.ToArray()) + "], wanted [" + string.Join(",", list2.ToArray()) + "]."); if (!SameArmNumbers(list, list2)) { if (!ArmPrefabsLoaded(fistControl, list2)) { _plugin.LogWarning("Arms left as they are: an arm prefab the game would spawn could not be loaded, and ResetFists would destroy the current arms first."); } else { methodInfo.Invoke(fistControl, null); } } } catch (Exception ex) { _plugin.LogWarning("FistControl.ResetFists failed: " + UnwrapMessage(ex)); } } private List ReadSpawnedArmNumbers(object fists) { try { if (!(GetMember(fists, new string[1] { "spawnedArmNums" }) is IEnumerable enumerable)) { return null; } List list = new List(4); foreach (object item in enumerable) { list.Add(ToInt(item, -1)); } return list; } catch (Exception ex) { LastError = "Spawned arms could not be read: " + UnwrapMessage(ex); return null; } } private List WantedArmNumbers(object fists) { try { object member = GetMember(fists, new string[1] { "forcedLoadout" }); int num = ((member != null) ? ReadArmVariant(member, "blueVariant") : 0); int num2 = ((member != null) ? ReadArmVariant(member, "redVariant") : 0); List list = new List(3); if ((ReadWeaponPref("arm0") == 1 && (member == null || num == 0)) || (member != null && num == 1)) { list.Add(0); } if (member != null && num2 == 1) { list.Add(1); } else if ((member == null || num2 != 2) && ReadWeaponPref("arm1") == 1 && ReadGear("arm1") == 1) { list.Add(1); } if (ReadWeaponPref("arm3") == 1 && ReadGear("arm3") == 1) { list.Add(3); } return list; } catch (Exception ex) { LastError = "Arm set could not be read: " + UnwrapMessage(ex); return null; } } private int ReadArmVariant(object forced, string variantName) { object member = GetMember(forced, new string[1] { "arm" }); return ToInt((member != null) ? GetMember(member, new string[1] { variantName }) : null, 0); } private int ReadWeaponPref(string key) { try { string error; object prefsManager = GetPrefsManager(out error); if (prefsManager == null) { return -1; } if (_prefsGetIntMethod == null) { _prefsGetIntMethod = FindMethod(prefsManager.GetType(), "GetInt", 2); } if (_prefsGetIntMethod == null) { return -1; } return ToInt(_prefsGetIntMethod.Invoke(prefsManager, new object[2] { "weapon." + key, 1 }), -1); } catch { return -1; } } private static bool SameArmNumbers(List left, List right) { if (left == null || right == null || left.Count != right.Count) { return false; } for (int i = 0; i < left.Count; i++) { if (left[i] != right[i]) { return false; } } return true; } private bool ArmPrefabsLoaded(object fists, List wanted) { if (wanted == null) { return false; } for (int i = 0; i < wanted.Count; i++) { string text = ((wanted[i] == 0) ? "blueArm" : ((wanted[i] == 1) ? "redArm" : "goldArm")); object member = GetMember(fists, new string[1] { text }); if (member == null) { return false; } if (LoadArmPrefab(member) == null) { return false; } } return true; } private object LoadArmPrefab(object reference) { try { Type type = WeaponUnlock.FindGameType("AssetHelper"); if (type == null) { return null; } MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { if (!(methods[i].Name != "LoadPrefab")) { ParameterInfo[] parameters = methods[i].GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsInstanceOfType(reference)) { object? obj = methods[i].Invoke(null, new object[1] { reference }); Object val = (Object)((obj is Object) ? obj : null); return (val != (Object)null) ? val : null; } } } } catch (Exception ex) { LastError = "Arm prefab load failed: " + UnwrapMessage(ex); } return null; } public object GetActionState(string actionName) { if (string.IsNullOrEmpty(actionName)) { return null; } object inputSource = InputSource; if (inputSource == null) { return null; } MemberInfo memberInfo = FindMember(inputSource.GetType(), actionName); if (memberInfo == null) { return null; } return GetMemberValue(inputSource, memberInfo); } public bool IsGamePaused() { object optionsManager = OptionsManager; if (optionsManager == null) { return false; } return ToBool(GetMember(optionsManager, new string[3] { "paused", "isPaused", "Paused" }), fallback: false); } public bool TryGetHealth(out float health, out float hardDamage) { health = 0f; hardDamage = 0f; object newMovement = NewMovement; if (newMovement == null) { return false; } object member = GetMember(newMovement, new string[4] { "hp", "health", "currentHealth", "hitPoints" }); object member2 = GetMember(newMovement, new string[4] { "antiHp", "antiHP", "hardDamage", "antiHealth" }); if (member == null) { return false; } health = ToFloat(member, 0f); hardDamage = ToFloat(member2, 0f); return true; } public bool TryGetStamina(out float stamina) { stamina = 0f; object newMovement = NewMovement; if (newMovement == null) { return false; } object member = GetMember(newMovement, new string[5] { "boostCharge", "stamina", "staminaMeter", "staminaPoints", "stam" }); if (member == null) { return false; } stamina = ToFloat(member, 0f); return true; } public bool TryGetPlayerHitboxBounds(out Vector3 center, out Vector3 size) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: 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_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) center = Vector3.zero; size = Vector3.zero; object newMovement = NewMovement; Component val = (Component)((newMovement is Component) ? newMovement : null); if ((Object)(object)val == (Object)null) { return false; } Vector3 position = val.transform.position; object member = GetMember(val, new string[1] { "playerCollider" }); Collider val2 = (Collider)((member is Collider) ? member : null); if ((Object)(object)val2 != (Object)null && val2.enabled && ((Component)val2).gameObject.activeInHierarchy) { Bounds bounds = val2.bounds; center = ((Bounds)(ref bounds)).center - position; size = ((Bounds)(ref bounds)).size; if (size.x > 0f && size.y > 0f) { return size.z > 0f; } return false; } Collider[] componentsInChildren; try { componentsInChildren = val.GetComponentsInChildren(true); } catch { return false; } bool flag = false; Bounds bounds2 = default(Bounds); ((Bounds)(ref bounds2))..ctor(Vector3.zero, Vector3.zero); for (int i = 0; i < 2; i++) { if (flag) { break; } bool flag2 = i == 1; foreach (Collider val3 in componentsInChildren) { if (!((Object)(object)val3 == (Object)null) && val3.enabled && ((Component)val3).gameObject.activeInHierarchy && (flag2 || !val3.isTrigger)) { if (!flag) { bounds2 = val3.bounds; flag = true; } else { ((Bounds)(ref bounds2)).Encapsulate(val3.bounds); } } } } if (!flag) { return false; } center = ((Bounds)(ref bounds2)).center - position; size = ((Bounds)(ref bounds2)).size; if (size.x > 0f && size.y > 0f) { return size.z > 0f; } return false; } public bool TryGetMovementState(out bool onGround, out bool sliding, out bool dashing, out bool jumping) { onGround = (sliding = (dashing = (jumping = false))); object newMovement = NewMovement; if (newMovement == null) { return false; } object member = GetMember(newMovement, new string[1] { "gc" }); if (member != null) { onGround = ToBool(GetMember(member, new string[1] { "onGround" }), fallback: false); } sliding = ToBool(GetMember(newMovement, new string[1] { "sliding" }), fallback: false); dashing = ToBool(GetMember(newMovement, new string[1] { "boost" }), fallback: false); jumping = ToBool(GetMember(newMovement, new string[1] { "jumping" }), fallback: false); return true; } public bool TryGetAutofuncState(out bool jumpCooldown, out float boostCharge) { jumpCooldown = false; boostCharge = 0f; object newMovement = NewMovement; if (newMovement == null) { return false; } jumpCooldown = ToBool(GetMember(newMovement, new string[1] { "jumpCooldown" }), fallback: false); boostCharge = ToFloat(GetMember(newMovement, new string[1] { "boostCharge" }), 0f); return true; } public bool TryGetSlamReady(out bool ready) { //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: 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_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: 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_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) ready = false; object newMovement = NewMovement; Component val = (Component)((newMovement is Component) ? newMovement : null); if ((Object)(object)val == (Object)null) { return false; } object member = GetMember(val, new string[1] { "gc" }); Component val2 = (Component)((member is Component) ? member : null); if ((Object)(object)val2 == (Object)null) { return false; } if (ToBool(GetMember(val2, new string[1] { "onGround" }), fallback: true) || ToBool(GetMember(val2, new string[1] { "heavyFall" }), fallback: true)) { return true; } if (ToFloat(GetMember(val, new string[1] { "fallTime" }), 0f) <= 0.5f || ToFloat(GetMember(val, new string[1] { "slamCooldown" }), 1f) != 0f) { return true; } if (!_layerMaskResolved) { _layerMaskResolved = true; Type type = FindType("LayerMaskDefaults"); Type type2 = FindType("LMD"); if (type != null && type2 != null) { _layerMaskGet = type.GetMethod("Get", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { type2 }, null); try { _lmdEnvironment = Enum.Parse(type2, "Environment"); } catch { _lmdEnvironment = null; } } } int num = 0; if (_layerMaskGet != null && _lmdEnvironment != null) { try { if (_layerMaskGet.Invoke(null, new object[1] { _lmdEnvironment }) is LayerMask val3) { num = ((LayerMask)(ref val3)).value; } } catch { num = 0; } } if (num == 0) { return false; } Vector3 up = val.transform.up; ready = !Physics.Raycast(val2.transform.position + up, -up, 3f, num, (QueryTriggerInteraction)1); return true; } public bool TryGetSlamming(out bool slamming) { slamming = false; object newMovement = NewMovement; if (newMovement == null) { return false; } object member = GetMember(newMovement, new string[1] { "gc" }); if (member == null) { return false; } object member2 = GetMember(member, new string[1] { "heavyFall" }); if (member2 == null) { member2 = GetMember(newMovement, new string[1] { "heavyFall" }); } if (member2 == null) { return false; } slamming = ToBool(member2, fallback: false); return true; } public bool TryGetTouchingWall(out bool onWall) { onWall = false; object newMovement = NewMovement; if (newMovement == null) { return false; } object member = GetMember(newMovement, new string[1] { "wcGroup" }); if (member == null) { return false; } if (!(GetMember(member, new string[3] { "instances", "checks", "walls" }) is IEnumerable enumerable)) { return false; } bool result = false; foreach (object item in enumerable) { Component val = (Component)((item is Component) ? item : null); if (!((Object)(object)val == (Object)null)) { result = true; if (ToBool(GetMember(val, new string[1] { "onWall" }), fallback: false)) { onWall = true; break; } } } return result; } public bool TryGetHookReady(out bool ready) { ready = false; object obj = ResolveSingleton(ref _hookArm, _hookArmType ?? (_hookArmType = FindType("HookArm"))); if (obj == null) { return false; } bool flag = ToBool(GetMember(obj, new string[1] { "equipped" }), fallback: false); int num = ToInt(GetMember(obj, new string[1] { "state" }), -1); bool flag2 = ToBool(GetMember(obj, new string[1] { "returning" }), fallback: true); float num2 = ToFloat(GetMember(obj, new string[1] { "cooldown" }), 1f); ready = flag && num == 0 && !flag2 && num2 <= 0f; return true; } public bool TryFindNearestCoin(Vector3 origin, out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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) point = Vector3.zero; Type type = _coinType ?? (_coinType = FindType("Coin")); if (type == null) { return false; } Object[] array; try { array = Object.FindObjectsOfType(type, false); } catch { return false; } float num = float.MaxValue; bool result = false; foreach (Object obj2 in array) { Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if (!((Object)(object)val == (Object)null) && val.gameObject.activeInHierarchy && !ToBool(GetMember(val, new string[1] { "shot" }), fallback: false)) { Vector3 position = val.transform.position; Vector3 val2 = position - origin; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; point = position; result = true; } } } return result; } public bool TryFindProjectile(string typeName, int preferredId, Vector3 origin, out Vector3 point, out int instanceId) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: 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_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) point = Vector3.zero; instanceId = 0; Type type = FindType(typeName); if (type == null) { return false; } Object[] array; try { array = Object.FindObjectsOfType(type, false); } catch { return false; } float num = float.MaxValue; bool result = false; foreach (Object obj2 in array) { Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if ((Object)(object)val == (Object)null || !val.gameObject.activeInHierarchy) { continue; } int instanceID = ((Object)val).GetInstanceID(); Vector3 position = val.transform.position; if (preferredId != 0 && instanceID == preferredId) { point = position; instanceId = instanceID; return true; } if (!string.Equals(typeName, "Coin", StringComparison.Ordinal) || !ToBool(GetMember(val, new string[1] { "shot" }), fallback: false)) { Vector3 val2 = position - origin; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; point = position; instanceId = instanceID; result = true; } } } return result; } public bool TryFindNearestAimLockProjectile(Vector3 origin, out string typeName, out int instanceId, out Vector3 point) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) typeName = string.Empty; instanceId = 0; point = Vector3.zero; float num = float.MaxValue; bool result = false; for (int i = 0; i < AimLockProjectileTypes.Length; i++) { if (TryFindProjectile(AimLockProjectileTypes[i], 0, origin, out var point2, out var instanceId2)) { Vector3 val = point2 - origin; float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; typeName = AimLockProjectileTypes[i]; instanceId = instanceId2; point = point2; result = true; } } } return result; } public int CollectCoins(List into) { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) if (into == null) { return 0; } into.Clear(); Type type = _coinType ?? (_coinType = FindType("Coin")); if (type == null) { return 0; } Object[] array; try { array = Object.FindObjectsOfType(type, false); } catch { return 0; } foreach (Object obj2 in array) { Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if (!((Object)(object)val == (Object)null) && val.gameObject.activeInHierarchy) { CoinInfo coinInfo = new CoinInfo(); coinInfo.Component = val; coinInfo.Id = ((Object)val.gameObject).GetInstanceID(); coinInfo.Name = ((Object)val.gameObject).name; coinInfo.Position = val.transform.position; coinInfo.Shot = ToBool(GetMember(val, new string[3] { "shot", "wasShot", "hasBeenShot" }), fallback: false); coinInfo.ShotByEnemy = ToBool(GetMember(val, new string[2] { "shotByEnemy", "wasShotByEnemy" }), fallback: false); coinInfo.Power = ToFloat(GetMember(val, new string[1] { "power" }), 1f); coinInfo.Ricochets = ToInt(GetMember(val, new string[3] { "ricochets", "ricochet", "bounceCount" }), 0); CoinInfo coinInfo2 = coinInfo; if (TryGetCoinTarget(val, out var point)) { coinInfo2.TargetPoint = point; coinInfo2.HasTargetPoint = true; } into.Add(coinInfo2); } } return into.Count; } public bool TryGetCoinTarget(Component coin, out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) point = Vector3.zero; object member = GetMember(coin, new string[4] { "target", "customTarget", "targetEnemy", "lockedTarget" }); if (member == null) { return false; } Transform val = (Transform)((member is Transform) ? member : null); if ((Object)(object)val == (Object)null) { Component val2 = (Component)((member is Component) ? member : null); if ((Object)(object)val2 != (Object)null) { val = val2.transform; } } if ((Object)(object)val != (Object)null) { point = val.position; return true; } object member2 = GetMember(member, new string[3] { "position", "targetPosition", "pos" }); if (member2 is Vector3) { point = (Vector3)member2; return true; } return false; } public bool TryGetCoinDrag(out float drag) { drag = 0f; Type type = _coinType ?? (_coinType = FindType("Coin")); if (type == null) { return false; } Object[] array; try { array = Object.FindObjectsOfType(type, true); } catch { return false; } foreach (Object obj2 in array) { Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if (!((Object)(object)val == (Object)null)) { Rigidbody component = val.GetComponent(); if (!((Object)(object)component == (Object)null)) { drag = component.drag; return true; } } } Type type2 = FindType("Revolver"); if (type2 != null) { Object[] array2; try { array2 = Object.FindObjectsOfType(type2, true); } catch { array2 = null; } if (array2 != null) { for (int j = 0; j < array2.Length; j++) { object member = GetMember(array2[j], new string[2] { "coin", "coinPrefab" }); GameObject val2 = (GameObject)((member is GameObject) ? member : null); if ((Object)(object)val2 == (Object)null) { Component val3 = (Component)((member is Component) ? member : null); if ((Object)(object)val3 != (Object)null) { val2 = val3.gameObject; } } if (!((Object)(object)val2 == (Object)null)) { Rigidbody component2 = val2.GetComponent(); if (!((Object)(object)component2 == (Object)null)) { drag = component2.drag; return true; } } } } } return false; } public bool TryGetCoinInheritedVelocity(out Vector3 velocity) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) object newMovement = NewMovement; object obj = ((newMovement != null) ? GetMember(newMovement, new string[1] { "ridingRocket" }) : null); Component val = (Component)((obj is Component) ? obj : null); if ((Object)(object)val != (Object)null) { object member = GetMember(obj, new string[3] { "rb", "body", "rigidbody" }); Rigidbody val2 = (Rigidbody)((member is Rigidbody) ? member : null); if ((Object)(object)val2 == (Object)null) { val2 = val.GetComponent(); } if ((Object)(object)val2 != (Object)null) { velocity = val2.velocity; return true; } } return TryGetPlayerVelocity(out velocity); } public bool TryGetGroundBelow(Vector3 origin, out float height) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) height = 0f; RaycastHit[] array = Physics.RaycastAll(origin + Vector3.up * 0.1f, Vector3.down, 1000f, -1, (QueryTriggerInteraction)1); Transform playerTransform = PlayerTransform; float num = float.MaxValue; bool result = false; for (int i = 0; i < array.Length; i++) { Transform transform = ((RaycastHit)(ref array[i])).transform; if (!((Object)(object)transform == (Object)null) && (!((Object)(object)playerTransform != (Object)null) || !transform.IsChildOf(playerTransform)) && ((RaycastHit)(ref array[i])).distance < num) { num = ((RaycastHit)(ref array[i])).distance; height = ((RaycastHit)(ref array[i])).point.y; result = true; } } return result; } public bool TryFindHookPoint(Vector3 origin, float range, out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0157: 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_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) point = Vector3.zero; Type type = _hookPointType ?? (_hookPointType = FindType("HookPoint")); if (type == null) { return false; } Object[] array; try { array = Object.FindObjectsOfType(type, false); } catch { return false; } int num = 0; object obj2 = ResolveSingleton(ref _hookArm, _hookArmType ?? (_hookArmType = FindType("HookArm"))); if (((obj2 != null) ? GetMember(obj2, new string[1] { "enviroMask" }) : null) is LayerMask val) { num = ((LayerMask)(ref val)).value; } float num2 = range * range; bool result = false; RaycastHit val4 = default(RaycastHit); foreach (Object obj3 in array) { Component val2 = (Component)(object)((obj3 is Component) ? obj3 : null); if (!((Object)(object)val2 == (Object)null) && val2.gameObject.activeInHierarchy && ToBool(GetMember(val2, new string[1] { "active" }), fallback: true)) { Vector3 position = val2.transform.position; Vector3 val3 = position - origin; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude; if (!(sqrMagnitude > num2) && (num == 0 || !Physics.Linecast(origin, position, ref val4, num, (QueryTriggerInteraction)1) || ((RaycastHit)(ref val4)).transform.IsChildOf(val2.transform))) { num2 = sqrMagnitude; point = position; result = true; } } } return result; } public bool TryGetWeapon(out string name, out int slot, out int variation) { name = string.Empty; slot = -1; variation = -1; object gunControl = GunControl; if (gunControl == null) { return false; } object member = GetMember(gunControl, new string[1] { "currentWeapon" }); GameObject val = (GameObject)((member is GameObject) ? member : null); if ((Object)(object)val != (Object)null) { name = CleanWeaponName(((Object)val).name); } slot = ToInt(GetMember(gunControl, new string[1] { "currentSlotIndex" }), -1); variation = ToInt(GetMember(gunControl, new string[1] { "currentVariationIndex" }), -1); if (name.Length <= 0) { return slot >= 0; } return true; } private static string CleanWeaponName(string raw) { string text = raw ?? string.Empty; int num = text.IndexOf("(Clone)", StringComparison.Ordinal); if (num > 0) { text = text.Substring(0, num).Trim(); } return text; } public bool TryPreviewWeaponSlot(int oneBasedSlot, out string name, out int slot, out int variation) { name = string.Empty; slot = -1; variation = -1; object gunControl = GunControl; if (gunControl == null) { return false; } if (!(GetMember(gunControl, new string[1] { "slots" }) is IList { Count: not 0 } list)) { return false; } int num = Mathf.Clamp(oneBasedSlot, 1, list.Count); if (!(list[num - 1] is IList { Count: not 0 } list2)) { return false; } int num2 = ToInt(GetMember(gunControl, new string[1] { "currentSlotIndex" }), -1); int num3 = ToInt(GetMember(gunControl, new string[1] { "currentVariationIndex" }), 0); int num4 = 0; if (num2 == num) { int num5 = 0; string error; object prefsManager = GetPrefsManager(out error); if (prefsManager != null) { if (_prefsGetIntMethod == null) { _prefsGetIntMethod = FindMethod(prefsManager.GetType(), "GetInt", 2); } if (_prefsGetIntMethod != null) { try { num5 = ToInt(_prefsGetIntMethod.Invoke(prefsManager, new object[2] { "WeaponRedrawBehaviour", 0 }), 0); } catch { num5 = 0; } } } switch (num5) { case 0: num4 = (num3 + 1) % list2.Count; break; case 2: num4 = num3; break; } } else { IDictionary dictionary = ((oneBasedSlot >= 6 || ToBool(GetMember(gunControl, new string[1] { "variationMemory" }), fallback: false)) ? (GetMember(gunControl, new string[1] { "retainedVariations" }) as IDictionary) : null); if (dictionary != null && dictionary.Contains(num - 1)) { int num6 = ToInt(dictionary[num - 1], 0); if (num6 >= 0 && num6 < list2.Count) { num4 = num6; } } } if (num4 < 0 || num4 >= list2.Count) { num4 = 0; } object? obj2 = list2[num4]; GameObject val = (GameObject)((obj2 is GameObject) ? obj2 : null); if ((Object)(object)val != (Object)null) { name = CleanWeaponName(((Object)val).name); } slot = num; variation = num4; return name.Length > 0; } public bool TryGetShotgunReady(out object shotgun, out bool ready) { shotgun = null; ready = false; object gunControl = GunControl; if (gunControl == null) { return false; } object member = GetMember(gunControl, new string[1] { "currentWeapon" }); GameObject val = (GameObject)((member is GameObject) ? member : null); Type type = FindType("Shotgun"); if ((Object)(object)val == (Object)null || type == null) { return false; } Component val2 = val.GetComponent(type); if ((Object)(object)val2 == (Object)null) { val2 = val.GetComponentInChildren(type); } if ((Object)(object)val2 == (Object)null) { return false; } object member2 = GetMember(val2, new string[1] { "gunReady" }); if (member2 == null) { if (!_shotgunReadyWarned) { _shotgunReadyWarned = true; _plugin.LogWarning("Shotgun.gunReady not found; the G1 shotgun swap cannot see shots."); } return false; } shotgun = val2; ready = ToBool(member2, fallback: false); return true; } public bool TryGetStyle(out float style) { style = 0f; string[] array = new string[4] { "StyleHUD", "StyleCalculator", "StyleManager", "StyleBonus" }; for (int i = 0; i < array.Length; i++) { Type type = FindType(array[i]); if (type == null) { continue; } Object val = Object.FindObjectOfType(type); if (!(val == (Object)null)) { object member = GetMember(val, new string[5] { "style", "stylePoints", "styleMeter", "points", "score" }); if (member != null) { style = ToFloat(member, 0f); return true; } } } return false; } public bool RestartMission() { //IL_004b: 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) try { Type sceneHelperType = SceneHelperType; if (sceneHelperType != null) { MethodInfo method = sceneHelperType.GetMethod("RestartScene", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy, null, Type.EmptyTypes, null); if (method != null) { method.Invoke(null, null); _plugin.LogInfo("Restarting mission through SceneHelper.RestartScene()."); return true; } } Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).buildIndex >= 0) { SceneManager.LoadScene(((Scene)(ref activeScene)).buildIndex); } else { if (string.IsNullOrEmpty(((Scene)(ref activeScene)).name)) { return false; } SceneManager.LoadScene(((Scene)(ref activeScene)).name); } return true; } catch (Exception ex) { LastError = "RestartMission failed: " + UnwrapMessage(ex); return false; } } public bool LoadLevel(string levelName) { if (string.IsNullOrEmpty(levelName)) { LastError = "No level name given."; return false; } string text = LevelIdFromScene(levelName); if (text.Length == 0) { LastError = "'" + levelName.Trim() + "' is not a level id (expected e.g. 1-4 or Level 1-4)."; return false; } string text2 = "Level " + text; if (LoadGameScene(text2)) { _plugin.LogInfo("Loading level scene '" + text2 + "'."); return true; } try { SceneManager.LoadScene(text2); return true; } catch (Exception ex) { LastError = "Could not load '" + text2 + "': " + UnwrapMessage(ex); _plugin.LogWarning(LastError); return false; } } public bool LoadMainMenu() { if (LoadGameScene("Main Menu")) { _plugin.LogInfo("Loading the main menu scene."); return true; } try { SceneManager.LoadScene("Main Menu"); return true; } catch (Exception ex) { LastError = "Could not load 'Main Menu': " + UnwrapMessage(ex); _plugin.LogWarning(LastError); return false; } } private bool LoadGameScene(string scene) { try { Type sceneHelperType = SceneHelperType; if (sceneHelperType == null) { return false; } MethodInfo methodInfo = null; MethodInfo[] methods = sceneHelperType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); for (int i = 0; i < methods.Length; i++) { if (!(methods[i].Name != "LoadScene")) { ParameterInfo[] parameters = methods[i].GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string)) { methodInfo = methods[i]; break; } if (parameters.Length == 2 && parameters[0].ParameterType == typeof(string) && parameters[1].ParameterType == typeof(bool) && methodInfo == null) { methodInfo = methods[i]; } } } if (methodInfo == null) { return false; } object[] parameters2 = ((methodInfo.GetParameters().Length != 2) ? new object[1] { scene } : new object[2] { scene, true }); methodInfo.Invoke(null, parameters2); _plugin.LogInfo("SceneHelper.LoadScene('" + scene + "') invoked; PendingScene now '" + (ReadStaticSceneHelperString("PendingScene") ?? string.Empty) + "'."); return true; } catch (Exception ex) { LastError = "SceneHelper.LoadScene('" + scene + "') failed: " + UnwrapMessage(ex); _plugin.LogWarning(LastError); return false; } } private static string UnwrapMessage(Exception ex) { if (ex is TargetInvocationException && ex.InnerException != null) { ex = ex.InnerException; } return ex.Message; } public string BuildReport() { ResolveTypes(); List list = new List(); list.Add("ULTRAKILL TAS Tool - game bridge report"); list.Add("Unity: " + Application.unityVersion); list.Add("Scene: " + SceneName); list.Add("Level id: " + ((CurrentLevelId.Length == 0) ? "(none)" : CurrentLevelId) + " SceneHelper.CurrentScene: " + (ReadStaticSceneHelperString("CurrentScene") ?? "(missing)")); list.Add("Types:"); list.Add(" NewMovement: " + DescribeType(_newMovementType)); list.Add(" CameraController: " + DescribeType(_cameraControllerType)); list.Add(" GunControl: " + DescribeType(_gunControlType)); list.Add(" InputManager: " + DescribeType(_inputManagerType)); list.Add(" OptionsManager: " + DescribeType(_optionsManagerType)); list.Add(" BaseInput (legacy UI): " + DescribeType(_baseInputType)); list.Add("Singletons:"); list.Add(" player: " + (((Object)(object)PlayerComponent != (Object)null) ? "ok" : "not present (menu?)")); list.Add(" camera: " + ((CameraController != null) ? "ok" : "missing")); list.Add(" gun control: " + ((GunControl != null) ? "ok" : "missing")); list.Add(" input manager: " + ((InputManager != null) ? "ok" : "missing")); list.Add(" options: " + ((OptionsManager != null) ? "ok" : "missing")); object cameraController = CameraController; list.Add("Camera members:"); list.Add(" rotationX: " + MemberStatus(cameraController, "rotationX")); list.Add(" rotationY: " + MemberStatus(cameraController, "rotationY")); list.Add(" cam: " + MemberStatus(cameraController, "cam")); object gunControl = GunControl; list.Add("Gun members:"); list.Add(" currentSlot: " + MemberStatus(gunControl, "currentSlot")); list.Add(" currentVariation: " + MemberStatus(gunControl, "currentVariation")); object newMovement = NewMovement; list.Add("Player members:"); list.Add(" rb: " + MemberStatus(newMovement, "rb")); list.Add(" hp: " + MemberStatus(newMovement, "hp")); list.Add(" antiHp: " + MemberStatus(newMovement, "antiHp")); list.Add(" stamina: " + MemberStatus(newMovement, "stamina")); object inputSource = InputSource; list.Add("Input:"); list.Add(" InputSource: " + ((inputSource != null) ? inputSource.GetType().Name : "missing")); string[] array = new string[17] { "W", "A", "S", "D", "Jump", "Slide", "Dodge", "Fire1", "Fire2", "Punch", "Hook", "Slot1", "Slot2", "Slot3", "Slot4", "Slot5", "Slot6" }; int num = 0; for (int i = 0; i < array.Length; i++) { if (inputSource != null && FindMember(inputSource.GetType(), array[i]) != null) { num++; } } list.Add(" action states resolved: " + num + "/" + array.Length); list.Add(" inputsDictionary: " + ((InputBindings != null) ? (InputBindings.Count + " bindings") : "missing")); list.Add("Misc:"); list.Add(" OptionsManager.paused: " + MemberStatus(OptionsManager, "paused")); list.Add(" savestate scope: player, living enemies, doors, projectiles/coins"); list.Add(" last error: " + (string.IsNullOrEmpty(LastError) ? "none" : LastError)); return string.Join("\n", list.ToArray()); } private static string DescribeType(Type type) { if (!(type == null)) { return type.FullName; } return "NOT FOUND"; } private static string MemberStatus(object target, string name) { if (target == null) { return "n/a (object missing)"; } Type type = target.GetType(); while (type != null && type != typeof(MonoBehaviour) && type != typeof(object)) { if (type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null) { return "field ok"; } if (type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null) { return "property ok"; } type = type.BaseType; } return "NOT FOUND"; } } public sealed class GuiManager { private struct MatrixCell { public string Label; public TasButtons Mask; public float Width; public bool GapBefore; public MatrixCell(string label, TasButtons mask, float width, bool gap) { Label = label; Mask = mask; Width = width; GapBefore = gap; } } private sealed class ShortcutGroup { public readonly string Name; public readonly string[][] Rows; public ShortcutGroup(string name, params string[][] rows) { Name = name; Rows = rows; } } private sealed class HitboxMarker { public Collider Collider; public bool IsPlayer; } private struct AtlasGlyph { public bool usable; public Texture texture; public Rect texCoords; public float width; public float height; public float bearingX; public float bearingY; public float advance; public float scale; } private sealed class TriggerMarker { public Component Owner; public Collider Collider; public string Label = string.Empty; } private readonly Plugin _plugin; private readonly TasEngine _engine; private readonly TimeController _time; private readonly SaveStateManager _states; private readonly GameBridge _bridge; private readonly InputPatcher _input; private readonly RngController _rng; private const float WindowWidth = 900f; private const float WindowHeight = 680f; private Rect _windowRect = new Rect(40f, 40f, 900f, 680f); private int _tab; private bool _visible = true; private bool _loggedDraw; private bool _loggedHudState; private bool _loggedHudDraw; private string _pathText; private string _statusText = string.Empty; private bool _statusIsError; private string _loadoutText = string.Empty; private string _frametimeText; private string _seedText; private string _authorText; private string _descriptionText; private string _autofuncsText = "----------"; private string _movementText = "------"; private string _actionsText = "------"; private string _ftOverrideText = string.Empty; private string _pitchText = "0.0"; private string _yawText = "90.0"; private string _framesText = "1"; private bool _liveEdit; private string _commandsText = string.Empty; private string _pauseAtTickText = "0"; private string _noRefreshTickText = "0"; private bool _autoSync = true; private int _lastSyncedTick = -1; private ConfigEntry _rebindEntry; private ConfigEntry _rebindKeyEntry; private string _rebindLabel = string.Empty; private string[] _files = new string[0]; private string[] _exampleFiles = new string[0]; private int _filesFrame = -1000; private Vector2 _fileScroll; private Vector2 _lineScroll; private Vector2 _diagnosticsScroll; private string _diagnostics = "Press Refresh to build a report."; private bool _diagnosticsRequested; private bool _diagnosticsLogRequested; private int _cacheFrame = -1000; private int _cachedEnemyCount; private int _enemyCountFrame = -1000; private string _cachedModeTag = "[IDLE]"; private string _cachedPointerText = string.Empty; private string _cachedWindowStatus = "status initializing..."; private string _cachedProgress = string.Empty; private string _cachedMode = string.Empty; private string _cachedStatusDetail = string.Empty; private string _cachedClock = string.Empty; private string _cachedInputDescription = string.Empty; private string _cachedRngDescription = string.Empty; private readonly List _cachedHudLines = new List(16); private string _cachedHudError = string.Empty; private static readonly string[] TabLabels = new string[10] { "General", "Script Editor", "Frame Editor", "Startup", "Keybinds", "Overlays", "Branches", "Recording", "Diagnostics", "Optimizer" }; private string _projectPathText = string.Empty; private string _projectAuthorText = string.Empty; private string _projectLevelText = string.Empty; private string _forkNameText = "Alt route"; private string _branchStatus = string.Empty; private Vector2 _branchScroll; private string _recordDirText; private string _recordFileText = "run.mp4"; private string _ffmpegText; private int _recordFpsIndex = 1; private int _recordSampleIndex = 2; private float _recordShutter = 0.5f; private const string ColumnHeader = "autofuncs |movem |action|frametime |yaw |pitch |frames|commands"; private string _toastText = string.Empty; private bool _toastError; private float _toastUntil; private GUIStyle _hudStyle; private GUIStyle _hudTitleStyle; private GUIStyle _noRefreshStyle; private GUIStyle _errorStyle; private GUIStyle _smallStyle; private GUIStyle _wrapStyle; private GUIStyle _matrixStyle; private GUISkin _styleSkin; private const int TabGeneral = 0; private const int TabScriptEditor = 1; private const int TabFrameEditor = 2; private const int TabStartup = 3; private const int TabKeybinds = 4; private const int TabOverlays = 5; private const int TabBranches = 6; private const int TabRecording = 7; private const int TabDiagnostics = 8; private const int TabOptimizer = 9; private static readonly string[] TabTips = new string[10] { "Transport, clock, startup behaviour and the script file: everything needed to play a run.", "Write and edit .uktas scripts as plain text with colours and Notepad++ style shortcuts.", "Edit the framebulk lines around the current tick, one input column at a time.", "What happens when you press Play: which level to load, weapons, autoload.", "Rebind the hotkeys used by the tool.", "HUD panel, speedometer, hitboxes, freecam and the PAUSED label.", "Keep several routes in one .uktasproj file and switch between them.", "Render the run to a video with motion blur (needs ffmpeg).", "Engine report for bug reports: what the tool sees in the game right now.", "Brute-force search for a better framebulk segment between two ticks." }; private readonly Vector2[] _tabScroll = (Vector2[])(object)new Vector2[10]; private static readonly double[] PlaybackSpeeds = new double[6] { 0.1, 0.25, 0.5, 1.0, 2.0, 4.0 }; private static readonly string[] StartLabels = new string[6] { "Script header", "Current state", "Restart level", "Load level", "Load savestate", "Main menu" }; private static readonly string[] StartValues = new string[6] { "script", "current", "restart", "level", "state", "menu" }; private static readonly string[] StartTips = new string[6] { "Use the start_type written in the script's header.", "Start from wherever the game is right now.", "Restart the current mission before frame 1.", "Load the level named below before frame 1.", "Restore a savestate slot before frame 1.", "Go to the title screen first (for scripts that click through the menus)." }; private static readonly int[] RecordSampleOptions = new int[5] { 1, 4, 8, 16, 32 }; private static readonly int[] RecordFpsOptions = new int[3] { 30, 60, 120 }; private const string UnbindHint = "Right-click to unbind."; private const string RebindTip = "Click, then press the new key. Escape cancels. Right-click to unbind."; private const TasButtons AnyFist = TasButtons.FistChange | TasButtons.FistFeedbacker | TasButtons.FistKnuckleblaster; private static readonly MatrixCell[] RowMove = new MatrixCell[12] { new MatrixCell("W", TasButtons.Forward, 18f, gap: false), new MatrixCell("A", TasButtons.Left, 18f, gap: false), new MatrixCell("S", TasButtons.Back, 18f, gap: false), new MatrixCell("D", TasButtons.Right, 18f, gap: false), new MatrixCell("JUMP", TasButtons.Jump, 34f, gap: true), new MatrixCell("SLIDE", TasButtons.Slide, 38f, gap: false), new MatrixCell("DASH", TasButtons.Dash, 34f, gap: false), new MatrixCell("F1", TasButtons.Fire1, 22f, gap: true), new MatrixCell("F2", TasButtons.Fire2, 22f, gap: false), new MatrixCell("PUNCH", TasButtons.Punch, 40f, gap: false), new MatrixCell("WHIP", TasButtons.Whiplash, 34f, gap: false), new MatrixCell("STATS", TasButtons.Stats, 38f, gap: true) }; private static readonly MatrixCell[] RowWeapons = new MatrixCell[17] { new MatrixCell("1", TasButtons.Slot1, 18f, gap: false), new MatrixCell("2", TasButtons.Slot2, 18f, gap: false), new MatrixCell("3", TasButtons.Slot3, 18f, gap: false), new MatrixCell("4", TasButtons.Slot4, 18f, gap: false), new MatrixCell("5", TasButtons.Slot5, 18f, gap: false), new MatrixCell("6", TasButtons.Slot6, 18f, gap: false), new MatrixCell("FIST", TasButtons.FistChange, 30f, gap: true), new MatrixCell("FEED", TasButtons.FistFeedbacker, 30f, gap: false), new MatrixCell("KNUK", TasButtons.FistKnuckleblaster, 30f, gap: false), new MatrixCell("WHL+", TasButtons.WeaponNext, 32f, gap: true), new MatrixCell("WHL-", TasButtons.WeaponPrev, 32f, gap: false), new MatrixCell("LAST", TasButtons.WeaponLast, 32f, gap: false), new MatrixCell("VAR<", TasButtons.VariationPrev, 32f, gap: true), new MatrixCell("VAR>", TasButtons.VariationNext, 32f, gap: false), new MatrixCell("V1", TasButtons.Variant1, 20f, gap: false), new MatrixCell("V2", TasButtons.Variant2, 20f, gap: false), new MatrixCell("V3", TasButtons.Variant3, 20f, gap: false) }; private readonly UktasEditorView _editor = new UktasEditorView(); private Font _editorFont; private bool _editorFontTried; private bool _editorInitialised; private bool _editorTabWasActive; private string _editorPath = string.Empty; private string _editorStatus = string.Empty; private bool _editorStatusError; private int _editorSeenVersion = -1; private int _editorCheckedVersion = -1; private float _editorChangeTime; private const string EditorShortcutHint = "Ctrl+S save Ctrl+K comment Ctrl+Shift+K uncomment Tab / Shift+Tab indent Ctrl+Z undo Ctrl+Y redo Ctrl+A / C / X / V Ctrl+D duplicate line Alt+Up/Down or Ctrl+Shift+Up/Down move line Ctrl+L select line Ctrl+F find Ctrl+G go to line Click Shortcuts for the full list."; private const int PromptNone = 0; private const int PromptFind = 1; private const int PromptGoTo = 2; private const string PromptControl = "UktasEditorPrompt"; private int _prompt; private string _promptText = string.Empty; private bool _promptFocus; private bool _findMatchCase; private bool _shortcutsOpen; private Vector2 _shortcutScroll; private GUIStyle _shortcutTitleStyle; private GUIStyle _shortcutKeyStyle; private GUIStyle _shortcutTextStyle; private static readonly ShortcutGroup[] ShortcutGroups = new ShortcutGroup[7] { new ShortcutGroup("File", Sc("Ctrl+S", "Save the file (asks before overwriting)")), new ShortcutGroup("Edit", Sc("Ctrl+Z", "Undo"), Sc("Ctrl+Y / Ctrl+Shift+Z", "Redo"), Sc("Ctrl+X", "Cut selection (the whole line if nothing is selected)"), Sc("Ctrl+C", "Copy selection (the whole line if nothing is selected)"), Sc("Ctrl+V", "Paste"), Sc("Ctrl+D", "Duplicate the selection, or the current line"), Sc("Ctrl+Shift+L", "Delete the current line(s)"), Sc("Alt+Up / Alt+Down", "Move the current line(s) up or down"), Sc("Ctrl+Shift+Up / Down", "Move the current line(s) up or down (same as Alt+Up / Alt+Down)"), Sc("Ctrl+Enter", "Insert an empty line below and move to it"), Sc("Ctrl+Shift+Enter", "Insert an empty line above and move to it"), Sc("Enter", "New line, keeps the indentation"), Sc("Backspace / Delete", "Delete a character (hold Ctrl for a whole word)")), new ShortcutGroup("Navigate", Sc("Arrow keys", "Move the caret"), Sc("Ctrl+Left / Ctrl+Right", "Jump by word"), Sc("Home / End", "Start (first text, then column 1) / end of the line"), Sc("Ctrl+Home / Ctrl+End", "Start / end of the file"), Sc("PageUp / PageDown", "Move one screen up / down"), Sc("Ctrl+G", "Go to line (type 12, or 12:5 for line and column)"), Sc("Ctrl+F", "Find in file: Enter = next, Shift+Enter = previous, Esc = close the bar")), new ShortcutGroup("Select", Sc("Shift + move keys", "Extend the selection"), Sc("Ctrl+A", "Select everything"), Sc("Ctrl+L", "Select the current line (again: add the next line)"), Sc("Double-click / Triple-click", "Select a word / a whole line")), new ShortcutGroup("Comment", Sc("Ctrl+K", "Comment the selected line(s) with //"), Sc("Ctrl+Shift+K", "Uncomment the selected line(s)")), new ShortcutGroup("Indent", Sc("Tab", "Indent the selected lines, or insert spaces up to the next stop"), Sc("Shift+Tab", "Outdent the selected lines")), new ShortcutGroup("Other", Sc("Esc", "Close this window (or the Find / Go to bar); the text is never touched"), Sc("Mouse wheel / Shift+wheel", "Scroll vertically / horizontally"), Sc("A- / A+ buttons", "Smaller / larger text")) }; private const string EditorTemplate = "// New .uktas script. Ctrl+K comments a line, Ctrl+S saves.\nversion 1\nhost_frametime 0.008\nseed 0\nstart_type restart_mission\nframes\n// autofuncs|movement|actions|frametime|yaw|pitch|frames|commands\n----------|------|------|-|0.0|0.0|60|\n----------|f-----|------|-|0.0|0.0|120|\n"; private string _lastFindText = string.Empty; private const int HitboxScanInterval = 20; private const int MaxHitboxMarkers = 512; private const float HitboxRange = 150f; private readonly List _hitboxes = new List(256); private readonly Vector3[] _hitboxCorners = (Vector3[])(object)new Vector3[8]; private int _hitboxScanFrame = -1000; private string _hudColorSource; private Color _hudColor = Color.white; private string _speedoColorSource; private Color _speedoColor = Color.white; private Font _gameFont; private Font _fallbackFont; private float _noFontSearchUntil; private float _nextFontTry; private int _fontTries; private GUIStyle _panelStyle; private GUIStyle _panelTitleStyle; private GUIStyle _panelSmallStyle; private GUIStyle _toastStyle; private GUIStyle _speedoStyle; private GUIStyle _speedoSubStyle; private GUISkin _hudStylesSkin; private readonly GUIContent _toastContent = new GUIContent(); private static float _hudAlpha = 1f; private Vector3 _velocity; private bool _hasPlayerData; private float _speedValue; private float _speedSampleBase; private float _speedNextSample; private int _speedTrend; private float _peakSpeed; private int _lastTickSeen; private int _speedKey = int.MinValue; private int _secondaryKey = int.MinValue; private string _speedText = string.Empty; private string _speedSecondary = string.Empty; private static readonly string[] DecimalFormats = new string[4] { "F0", "F1", "F2", "F3" }; private long _fpsStamp; private float _fpsSmoothed; private bool _hasPlayer; private string _playerNote = "not checked yet"; private long _rateStamp; private int _rateTick; private double _rateGameTime; private string _rateText = string.Empty; private bool _playerLogged; private bool _lastHasPlayer; private int _weaponPreviewSlot; private const float HitRange = 1000f; private readonly RaycastHit[] _crosshairHits = (RaycastHit[])(object)new RaycastHit[32]; private const float InspectorRange = 1000f; private const float HudTextMinWidth = 300f; private const float HudInputWidth = 560f; private float _panelLineHeight = 17f; private float _measuredTextWidth = 300f; private int _measuredVersion = -1; private Font _measuredFont; private int _hudLinesVersion; private readonly GUIContent _measureContent = new GUIContent(); private const float ToastSeconds = 5f; private const float ToastErrorSeconds = 8f; private static readonly string[] CornerValues = new string[4] { "topleft", "topright", "bottomleft", "bottomright" }; private static readonly string[] CornerLabels = new string[4] { "Top left", "Top right", "Bottom left", "Bottom right" }; private static readonly string[] CornerTips = new string[4] { "Anchor the info panel to the top left corner.", "Anchor the info panel to the top right corner.", "Anchor the info panel to the bottom left corner.", "Anchor the info panel to the bottom right corner." }; private static readonly string[] SpeedoModeValues = new string[3] { "horizontal", "total", "vertical" }; private static readonly string[] SpeedoModeLabels = new string[3] { "Horizontal (XZ)", "Total (3D)", "Vertical (Y)" }; private static readonly string[] SpeedoModeTips = new string[3] { "Speed along the ground plane only. What most speedrun tools show.", "Full 3D speed, including falling and rising.", "Only the up / down speed." }; private OptimConfig _optimConfig; private OptimBoxSet _optimBoxes; private TasOptimizer _optimizer; private string _optimStartText = "0"; private string _optimEndText = "0"; private string _optimConstraintValue = "0"; private int _optimConstraintIndex = -1; private readonly string[] _optimObjectiveLabels = new string[10] { "Reach Goal Box", "Position X", "Position Y", "Position Z", "Velocity X", "Velocity Y", "Velocity Z", "Speed XZ", "Speed 3D", "Distance to Point" }; private readonly OptimObjective[] _optimObjectives = new OptimObjective[10] { OptimObjective.ReachGoalFastest, OptimObjective.PosX, OptimObjective.PosY, OptimObjective.PosZ, OptimObjective.VelX, OptimObjective.VelY, OptimObjective.VelZ, OptimObjective.SpeedXZ, OptimObjective.Speed3D, OptimObjective.DistanceToGoal }; private int _optimBoxKind; private string _optimBoxStep = "0.5"; private readonly string[] _optimBoxKindLabels = new string[3] { "Goal (green)", "Keep-out (red)", "Waypoint (yellow)" }; private TasScript _optimMarkerScript; private bool _optimMarkerValid; private int _optimMarkerStart = -1; private int _optimMarkerEnd = -1; private float _optimMarkerNextScan; private const float OptimBestFlashSeconds = 4f; private const string OptimSegmentControlName = "UktasOptimBestSegment"; private TasOptimizer _optimTrackedFor; private bool _optimTrackReady; private double _optimLastSeenBest; private double _optimLastImprovement; private bool _optimHasImprovement; private float _optimBestChangedAt = -1000f; private bool _optimBestFlashing; private TasOptimizer _optimTextFor; private double _optimTextScore = double.NaN; private int _optimTextCount = -1; private string _optimSegmentText = string.Empty; private Vector2 _optimSegmentScroll; private GUIStyle _optimBestBoxStyle; private GUIStyle _optimBestFlashBoxStyle; private GUIStyle _optimBestHeadStyle; private GUIStyle _optimBestFlashHeadStyle; private GUIStyle _optimBestValueStyle; private GUIStyle _optimSegmentAreaStyle; private Texture2D _texOptimBest; private Texture2D _texOptimBestFlash; private float _optimStartedAt; private GUIStyle _pausedStyle; private static readonly Color ColAccent = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)140, (byte)60, byte.MaxValue)); private static readonly Color ColAccentHover = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)163, (byte)98, byte.MaxValue)); private static readonly Color ColAccentPressed = Color32.op_Implicit(new Color32((byte)214, (byte)108, (byte)36, byte.MaxValue)); private static readonly Color ColWindow = Color32.op_Implicit(new Color32((byte)22, (byte)25, (byte)31, (byte)250)); private static readonly Color ColHeader = Color32.op_Implicit(new Color32((byte)31, (byte)35, (byte)45, byte.MaxValue)); private static readonly Color ColWindowBorder = Color32.op_Implicit(new Color32((byte)58, (byte)66, (byte)84, byte.MaxValue)); private static readonly Color ColCard = Color32.op_Implicit(new Color32((byte)30, (byte)34, (byte)43, byte.MaxValue)); private static readonly Color ColCardBorder = Color32.op_Implicit(new Color32((byte)46, (byte)53, (byte)67, byte.MaxValue)); private static readonly Color ColButton = Color32.op_Implicit(new Color32((byte)46, (byte)53, (byte)68, byte.MaxValue)); private static readonly Color ColButtonHover = Color32.op_Implicit(new Color32((byte)60, (byte)69, (byte)88, byte.MaxValue)); private static readonly Color ColButtonPressed = Color32.op_Implicit(new Color32((byte)76, (byte)88, (byte)112, byte.MaxValue)); private static readonly Color ColField = Color32.op_Implicit(new Color32((byte)17, (byte)20, (byte)26, byte.MaxValue)); private static readonly Color ColFieldBorder = Color32.op_Implicit(new Color32((byte)55, (byte)63, (byte)80, byte.MaxValue)); private static readonly Color ColDanger = Color32.op_Implicit(new Color32((byte)176, (byte)58, (byte)58, byte.MaxValue)); private static readonly Color ColDangerHover = Color32.op_Implicit(new Color32((byte)206, (byte)76, (byte)76, byte.MaxValue)); private static readonly Color ColDangerPressed = Color32.op_Implicit(new Color32((byte)146, (byte)44, (byte)44, byte.MaxValue)); private static readonly Color ColText = Color32.op_Implicit(new Color32((byte)226, (byte)231, (byte)240, byte.MaxValue)); private static readonly Color ColMuted = Color32.op_Implicit(new Color32((byte)146, (byte)156, (byte)175, byte.MaxValue)); private static readonly Color ColError = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)125, (byte)118, byte.MaxValue)); private static readonly Color ColGood = Color32.op_Implicit(new Color32((byte)130, (byte)214, (byte)140, byte.MaxValue)); private GUISkin _skin; private GUISkin _skinBase; private Texture2D _texWindow; private Texture2D _texCard; private Texture2D _texButton; private Texture2D _texButtonHover; private Texture2D _texButtonPressed; private Texture2D _texPrimary; private Texture2D _texPrimaryHover; private Texture2D _texPrimaryPressed; private Texture2D _texDanger; private Texture2D _texDangerHover; private Texture2D _texDangerPressed; private Texture2D _texField; private Texture2D _texFieldHover; private Texture2D _texFieldFocus; private Texture2D _texTabHover; private Texture2D _texTabActive; private Texture2D _texSep; private Texture2D _texTrack; private Texture2D _texThumb; private Texture2D _texThumbHover; private Texture2D _texScrollTrack; private Texture2D _texScrollThumb; private Texture2D _texScrollThumbHover; private Texture2D _texCheckOff; private Texture2D _texCheckOn; private Texture2D _texCheckHover; private Texture2D _texTip; private Texture2D _texBanner; private GUIStyle _cardStyle; private GUIStyle _sectionStyle; private GUIStyle _hintStyle; private GUIStyle _sepStyle; private GUIStyle _primaryStyle; private GUIStyle _dangerStyle; private GUIStyle _selectedStyle; private GUIStyle _tabStyle; private GUIStyle _tabActiveStyle; private GUIStyle _toggleStyle; private GUIStyle _tipStyle; private GUIStyle _statusBarStyle; private GUIStyle _bannerStyle; private GUIStyle _bodyStyle; private string _tipText; private string _tipShown; private float _tipSince; private bool _tipClipActive; private Rect _tipClip; private Vector2 _tipWindowMouse; private Action _confirmAction; private string _confirmTitle = string.Empty; private string _confirmBody = string.Empty; private string _confirmYes = "Yes"; private bool _confirmOffersSkip; private bool _confirmSkipChecked; private bool _skipOverwriteConfirm; private Object _fontAtlas; private string _fontAtlasName = string.Empty; private Texture[] _fontAtlasTextures; private Texture[] _fontAtlasMasks; private IDictionary _fontAtlasLookup; private IEnumerable _fontAtlasCharacterTable; private float _fontAtlasPointSize = 90f; private float _fontAtlasScale = 1f; private float _nextFontAtlasTry; private int _fontAtlasTries; private readonly Dictionary _atlasGlyphs = new Dictionary(); private static readonly string[] TriggerExtraTypeNames = new string[10] { "ObjectActivator", "ActivateArena", "CheckPoint", "DoorOpener", "HurtZone", "DeathZone", "OutOfBounds", "PlayerActivator", "FinalPit", "SecretMissionPit" }; private static readonly string[] OverlayCameraNames = new string[2] { "cam", "camera" }; private static readonly int[] BoxEdges = new int[24] { 0, 1, 2, 3, 4, 5, 6, 7, 0, 2, 1, 3, 4, 6, 5, 7, 0, 4, 1, 5, 2, 6, 3, 7 }; private static readonly int[] BoxFaces = new int[24] { 0, 2, 6, 4, 1, 3, 7, 5, 0, 1, 5, 4, 2, 3, 7, 6, 0, 1, 3, 2, 4, 5, 7, 6 }; private const int TriggerScanInterval = 300; private const int MaxTriggerMarkers = 128; private const int MaxTriggerScan = 4000; private readonly List _triggerTypes = new List(64); private bool _triggerTypesResolved; private readonly List _triggerAll = new List(256); private readonly List _triggerVisible = new List(128); private readonly List _triggerColliders = new List(8); private readonly HashSet _triggerSeen = new HashSet(); private readonly Vector3[] _triggerCorners = (Vector3[])(object)new Vector3[8]; private int _triggerScanFrame = -100000; private int _triggerSceneHandle = int.MinValue; private Camera _overlayCamera; private Material _lineMaterial; private bool _lineMaterialTried; private GUIStyle _triggerLabelStyle; private bool _triggerWarned; private readonly Dictionary _viewmodelWasForcedOff = new Dictionary(); private readonly HashSet _viewmodelSeen = new HashSet(); private int _viewmodelScanFrame = -1000; public bool Visible { get { return _visible; } set { _visible = value; } } public bool IsRebinding { get { if (_rebindEntry == null) { return _rebindKeyEntry != null; } return true; } } public bool IsTextInputFocused => GUIUtility.keyboardControl != 0; public bool OwnsEscape { get { if (_visible) { if (!_shortcutsOpen && _prompt == 0 && !IsRebinding) { return IsTextInputFocused; } return true; } return false; } } public bool CapturesInput { get { if (!_visible || _plugin.CleanRecordingActive || !_plugin.BlockGameInputWhileGuiOpen.Value) { return false; } if (_engine != null && _engine.RenderSuppressed) { return false; } return true; } } public GuiManager(Plugin plugin, TasEngine engine, TimeController time, SaveStateManager states, GameBridge bridge, InputPatcher input, RngController rng) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0272: 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_0282: Expected O, but got Unknown //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Expected O, but got Unknown _plugin = plugin; _engine = engine; _time = time; _states = states; _bridge = bridge; _input = input; _rng = rng; _visible = plugin.GuiVisibleOnStart.Value; _pathText = (string.IsNullOrEmpty(plugin.LastScriptFile.Value) ? Path.Combine(plugin.ScriptDirectory, "run.uktas") : plugin.LastScriptFile.Value); _frametimeText = plugin.DefaultHostFrametime.Value.ToString("0.######", CultureInfo.InvariantCulture); _seedText = plugin.DefaultSeed.Value.ToString(CultureInfo.InvariantCulture); SyncEditor(force: true); _engine.ConfirmRecordingOverwrite = AskRecordingOverwrite; } private void RememberScriptPath() { if (!string.IsNullOrEmpty(_pathText) && !(_plugin.LastScriptFile.Value == _pathText)) { _plugin.LastScriptFile.Value = _pathText; _plugin.ConfigFile.Save(); } } public void ShowToast(string text, bool error) { _toastText = text; _toastError = error; _toastUntil = TimeController.RealTime + 4.5f; } public void UpdateCache() { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: 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_00d3: Unknown result type (might be due to invalid IL or missing references) if (_plugin == null || _time == null || _engine == null) { return; } int frameCount = SimulationFreeze.FrameCount; if (frameCount - _cacheFrame < 10) { return; } _cacheFrame = frameCount; bool renderSuppressed = _engine.RenderSuppressed; if (!renderSuppressed) { RefreshFileList(); } if (!renderSuppressed && frameCount - _enemyCountFrame >= 60 && (_visible || _plugin.ShowHud.Value)) { _enemyCountFrame = frameCount; try { _cachedEnemyCount = ((_bridge != null) ? _bridge.EnemyCount : 0); } catch { _cachedEnemyCount = 0; } } _cachedModeTag = BuildModeTag(); Vector2 val = ((_input != null) ? _input.LiveMousePosition : Vector2.zero); int num = (int)val.x; int num2 = (int)((float)Screen.height - val.y); _cachedPointerText = num + "," + num2 + " (" + ((float)num / (float)Mathf.Max(1, Screen.width)).ToString("0.000", CultureInfo.InvariantCulture) + " " + ((float)num2 / (float)Mathf.Max(1, Screen.height)).ToString("0.000", CultureInfo.InvariantCulture) + ")" + ((_input != null && _input.Pointer.Active) ? " [TAS]" : string.Empty); _cachedWindowStatus = _time.StatusLine() + " | " + _engine.Mode.ToString() + " | " + (_time.Paused ? "PAUSED" : "RUNNING") + " | tick " + _engine.CurrentTick + "/" + _engine.TotalTicks + " | enemies " + _cachedEnemyCount + " | seed " + _rng.CurrentSeed; _cachedProgress = "tick " + _engine.CurrentTick + " / " + _engine.TotalTicks + " time " + _engine.CurrentTime.ToString("0.000") + "s / " + _engine.TotalTime.ToString("0.000") + "s tpf " + ((_engine.LastFrametime > 0.0) ? _engine.LastFrametime.ToString("0.######") : "-") + " render " + _time.MeasuredFps.ToString("0") + " fps"; _cachedMode = "mode " + _engine.Mode.ToString() + " finished " + _engine.Finished + " steps queued " + _time.PendingSteps + " timeScale " + Time.timeScale.ToString("0.###") + " (game-owned, read only)"; _cachedStatusDetail = "status " + (_time.Paused ? "PAUSED" : "RUNNING") + " timer " + _engine.TimerText + " enemies " + _cachedEnemyCount + (_engine.StartupPending ? " STARTUP WAIT" : string.Empty); _cachedClock = "native physics step: " + _time.NativeFixedStep.ToString("0.########") + "s steps/tick: " + _time.StepsPerTick.ToString("0.###") + " (fixedDeltaTime stays " + Time.fixedDeltaTime.ToString("0.########") + ")"; _cachedInputDescription = ((_input != null) ? _input.Describe() : string.Empty); _cachedRngDescription = ((_rng != null) ? _rng.Describe() : string.Empty); BuildHudCache(); using (_plugin.ViewPose()) { RefreshTriggerOverlay(); RefreshHitboxOverlay(); } if (_diagnosticsRequested) { BuildDiagnostics(); } } private string BuildModeTag() { switch (_engine.Mode) { case EngineMode.Recording: return "[RECORDING]"; case EngineMode.Playing: if (!_engine.WaitingForControl) { return "[PLAYBACK]"; } return "[PLAYBACK - WAITING FOR CONTROL]"; case EngineMode.Starting: return "[STARTING]"; case EngineMode.Standalone: return "[STANDALONE]"; case EngineMode.Paused: { string text = (_engine.FreeLookActive ? "[PAUSED - FREE LOOK]" : "[PAUSED]"); if (!_plugin.StepRecord.Value) { return text; } return text + " [STEP RECORD]"; } default: return "[IDLE]"; } } private void RequestDiagnostics(bool log) { _diagnosticsRequested = true; _diagnosticsLogRequested = log; _statusText = "Collecting diagnostics outside OnGUI..."; _statusIsError = false; } private void BuildDiagnostics() { _diagnostics = _bridge.BuildReport() + "\n\n" + _time.StatusLine() + "\n" + _cachedInputDescription + "\n" + _cachedRngDescription + "\nScript: " + ((_engine.Script == null) ? "none" : (_engine.TotalTicks + " ticks, " + _engine.Script.Lines.Count + " lines")) + "\nFrametime: " + _time.HostFrametime.ToString("0.########") + "\nEnemies: " + _cachedEnemyCount + "\nKill plane Y: " + _plugin.KillPlaneY.Value.ToString("0.##") + " player Y: " + _bridge.PlayerY.ToString("0.##") + (_bridge.PlayerBelowKillPlane ? " OUT OF BOUNDS" : string.Empty) + "\nPlayer control: " + _bridge.PlayerControlActivated + "\nStartup mode: " + _plugin.PlayStartMode.Value + "\nStartup pending: " + _engine.StartupPending + "\nUnity captureDeltaTime: " + Time.captureDeltaTime.ToString("0.########") + "\nFixed deltaTime: " + Time.fixedDeltaTime.ToString("0.########") + "\nBepInEx config: " + Paths.ConfigPath; if (_diagnosticsLogRequested) { _plugin.LogInfo(_diagnostics); _diagnosticsLogRequested = false; } _diagnosticsRequested = false; _statusText = "Diagnostics refreshed."; _statusIsError = false; } public void OnGUI() { //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Expected O, but got Unknown //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) PushOptimizerOverlay(); bool flag = _engine != null && _engine.RenderSuppressed; if (!flag) { ApplyViewmodelVisibility(); } EnsureStyles(); HandleRebind(); if (_visible && !_plugin.CleanRecordingActive && !flag) { if (!_loggedDraw) { _loggedDraw = true; _plugin.LogInfo("TAS window drawing at " + ((Rect)(ref _windowRect)).x + "," + ((Rect)(ref _windowRect)).y + "."); } EnsureTheme(); float num = Mathf.Min(680f, Mathf.Max(420f, (float)Screen.height - 24f)); float num2 = Mathf.Min(900f, Mathf.Max(640f, (float)Screen.width - 24f)); GUISkin skin = GUI.skin; GUI.skin = _skin; try { _windowRect = GUILayout.Window(1431000129, _windowRect, new WindowFunction(DrawWindow), "ULTRAKILL TAS Tool v1.1.0 [Insert: hide]", (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(num2), GUILayout.Height(num) }); } finally { GUI.skin = skin; } Event current = Event.current; if ((int)current.type == 0 && !((Rect)(ref _windowRect)).Contains(current.mousePosition)) { GUIUtility.keyboardControl = 0; } } if (!_loggedHudState) { _loggedHudState = true; _plugin.LogInfo("HUD visible at startup: " + _plugin.ShowHud.Value + " (F12 toggles)."); } if (!flag) { using (_plugin.ViewPose()) { DrawTriggerOverlay(); DrawHitboxOverlay(); } } if (_plugin.ShowHud.Value && !flag) { DrawHud(); } DrawNoRefreshBanner(); if (!flag) { DrawSpeedometer(); DrawPausedLabel(); DrawToast(); } } private void EnsureStyles() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00b9: 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) //IL_00e4: Expected O, but got Unknown //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Expected O, but got Unknown //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Expected O, but got Unknown //IL_016b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)GUI.skin == (Object)(object)_styleSkin) || _hudStyle == null) { _styleSkin = GUI.skin; _hudStyle = new GUIStyle(GUI.skin.label); _hudStyle.fontSize = 12; _hudStyle.wordWrap = false; _hudStyle.richText = true; _hudTitleStyle = new GUIStyle(_hudStyle); _hudTitleStyle.fontStyle = (FontStyle)1; _hudTitleStyle.fontSize = 13; _errorStyle = new GUIStyle(GUI.skin.label); _errorStyle.normal.textColor = new Color(1f, 0.45f, 0.45f); _errorStyle.wordWrap = true; _smallStyle = new GUIStyle(GUI.skin.label); _smallStyle.fontSize = 10; _smallStyle.wordWrap = true; _wrapStyle = new GUIStyle(GUI.skin.label); _wrapStyle.wordWrap = true; _matrixStyle = new GUIStyle(GUI.skin.box); _matrixStyle.fontSize = 9; _matrixStyle.alignment = (TextAnchor)4; _matrixStyle.padding = new RectOffset(0, 0, 0, 0); _matrixStyle.normal.textColor = Color.white; } } private void DrawWindow(int id) { GUISkin skin = GUI.skin; if ((Object)(object)_skin != (Object)null) { GUI.skin = _skin; } try { DrawWindowContents(); } finally { GUI.skin = skin; } } private void DrawWindowContents() { //IL_0008: 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_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) Event current = Event.current; _tipWindowMouse = current.mousePosition; if ((int)current.type == 7) { _tipText = null; } bool enabled = GUI.enabled; if (_shortcutsOpen) { GUI.enabled = false; } DrawToolbar(); if ((int)current.type == 7) { Rect lastRect = GUILayoutUtility.GetLastRect(); _tipClip = new Rect(0f, ((Rect)(ref lastRect)).yMax, ((Rect)(ref _windowRect)).width, Mathf.Max(0f, ((Rect)(ref _windowRect)).height - ((Rect)(ref lastRect)).yMax - 30f)); } if (_confirmAction != null) { DrawConfirm(); } else { if (_tab != 1) { _editorTabWasActive = false; } bool flag = _tab != 1; if (flag) { _tabScroll[_tab] = GUILayout.BeginScrollView(_tabScroll[_tab], false, false, GUIStyle.none, GUI.skin.verticalScrollbar, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) }); _tipClipActive = true; } switch (_tab) { case 0: DrawGeneral(); break; case 1: DrawTextEditorTab(); break; case 2: DrawFrameEditorTab(); break; case 3: DrawStartup(); break; case 4: DrawKeybinds(); break; case 5: DrawOverlays(); DrawTrajectoryOptions(); DrawCoinPathOptions(); break; case 6: DrawBranches(); break; case 7: DrawRecording(); break; case 9: DrawOptimizerTab(); break; default: DrawDiagnostics(); break; } if (flag) { GUILayout.EndScrollView(); _tipClipActive = false; } } GUILayout.Label(_cachedWindowStatus, _statusBarStyle, Array.Empty()); GUI.enabled = enabled; if (_shortcutsOpen) { _tipText = null; DrawShortcutsPopup(); } DrawTooltip(); GUI.DragWindow(new Rect(0f, 0f, 10000f, 34f)); } private void DrawToolbar() { GUILayout.BeginHorizontal(Array.Empty()); for (int i = 0; i < TabLabels.Length; i++) { if (GUILayout.Button((i == 1 && _editor.Buffer.Modified) ? (TabLabels[i] + " *") : TabLabels[i], (i == _tab) ? _tabActiveStyle : _tabStyle, Array.Empty())) { _tab = i; } Tip(TabTips[i]); } GUILayout.FlexibleSpace(); if (Btn("Save config", "Write every plugin setting (keybinds, overlays, startup) to the BepInEx config file now.", GUILayout.Width(96f))) { _plugin.ConfigFile.Save(); } GUILayout.EndHorizontal(); GUILayout.Space(6f); } private int ChoiceRow(int selected, string[] labels, string[] tips, float width) { int result = selected; GUILayout.BeginHorizontal(Array.Empty()); for (int i = 0; i < labels.Length; i++) { if (BtnChoice(i == selected, labels[i], (tips != null && i < tips.Length) ? tips[i] : null, (width > 0f) ? GUILayout.Width(width) : GUILayout.ExpandWidth(true))) { result = i; } } GUILayout.EndHorizontal(); return result; } private void DrawGeneral() { DrawTransportCard(); DrawScriptFileCard(); DrawClockCard(); DrawStartupOnPlayCard(); DrawNoRefreshCard(); DrawBakingCard(); DrawSavestateCard(); } private void PressPlayPause() { if (_engine.Mode == EngineMode.Idle && _engine.Script == null) { ShowNoScriptMessage(); } else { _engine.TogglePause(); } } private void ShowNoScriptMessage() { _statusText = "No script is loaded, so there is nothing to play. Load one (Script file box below), write one in the Script Editor tab, or press Record. The game was not paused."; _statusIsError = true; _plugin.Toast("No script loaded: nothing to play. The game was not paused.", error: true); } private void DrawTransportCard() { BeginCard("Transport"); GUILayout.BeginHorizontal(Array.Empty()); string label = ((_engine.Mode == EngineMode.Playing) ? "Pause" : ((_engine.Mode != EngineMode.Standalone) ? "Play" : (_time.Paused ? "Resume" : "Pause"))); if (BtnPrimary(label, "Play starts the script from the start, or resumes if paused (F5). While it plays this button is Pause and stops at the current tick; after the script has finished, Play starts it again from the start. While recording, F5 runs / pauses the recording. With no script loaded this only shows a message.", GUILayout.Width(100f))) { PressPlayPause(); } GUI.enabled = _engine.IsActive; if (Btn("Step frame", "Advance exactly one tick while paused (F6).", GUILayout.Width(100f))) { _engine.Step(); } if (Btn("Rewind", "Go back to tick 0 and restore the state captured when Play started (F4).", GUILayout.Width(80f))) { _engine.Rewind(); } if (Btn("Stop", "Stop the run and give the game its own clock back (F11).", GUILayout.Width(70f))) { _engine.Stop(); } GUI.enabled = true; if ((_engine.Mode == EngineMode.Recording) ? BtnDanger("Stop recording", "Stop recording and save the script (F10). Asks first if that would overwrite an existing file.", GUILayout.Width(120f)) : Btn("Record", "Start recording what you do (F10; starts paused, F5 runs). With a script loaded it records into that script, otherwise into a new one.", GUILayout.Width(120f))) { _engine.ToggleRecording(); } if (BtnChoice(_engine.FastForward, _engine.FastForward ? "FF: on" : "FF: off", "Fast-forward: run the script as fast as the PC allows (hold F7 for a quick burst).", GUILayout.Width(80f))) { _engine.ToggleFastForward(); } GUILayout.EndHorizontal(); GUILayout.Space(4f); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Playback speed", "Wall-clock speed only. The tick length and the physics stay identical, so the run result never changes.", GUILayout.Width(100f)); for (int i = 0; i < PlaybackSpeeds.Length; i++) { bool selected = Math.Abs(_engine.PlaybackSpeed - PlaybackSpeeds[i]) < 0.001; if (BtnChoice(selected, PlaybackSpeeds[i].ToString("0.##") + "x", "Play at " + PlaybackSpeeds[i].ToString("0.##") + "x real time.", GUILayout.Width(56f))) { _engine.SetPlaybackSpeed(PlaybackSpeeds[i]); } } GUILayout.EndHorizontal(); EndCard(); DrawStudioCard(); } private void DrawScriptFileCard() { //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) BeginCard("Script file"); GUILayout.BeginHorizontal(Array.Empty()); _pathText = Field(_pathText, "Path of the .uktas / .hltas file. Relative names are looked up in the script folder."); if (Btn("Load", "Read this file into the tool. If the file does not exist, nothing happens and the game is not paused.", GUILayout.Width(65f))) { LoadScriptFromPath(_pathText); } if (Btn("Save", "Write the script in memory to this file (relative names go to the script folder). Asks before overwriting an existing file.", GUILayout.Width(65f))) { SaveScriptToPathText(); } if (Btn("New", "Create a fresh empty script in memory (nothing is written until you save). Relative names go to the script folder.", GUILayout.Width(60f))) { _engine.NewScript(_pathText); if (!string.IsNullOrEmpty(_engine.ScriptPath)) { _pathText = _engine.ScriptPath; } RememberScriptPath(); } GUILayout.EndHorizontal(); Lbl("Scripts in " + _plugin.ScriptDirectory, "Every .uktas and .hltas file in the script folder and its examples subfolder. Click a name to load it."); _fileScroll = GUILayout.BeginScrollView(_fileScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(92f) }); DrawFileButtons(_files); if (_files.Length == 0) { Hint("(no .uktas or .hltas files yet)"); } if (_exampleFiles.Length != 0) { Hint("examples"); DrawFileButtons(_exampleFiles); } GUILayout.EndScrollView(); StatusLine(); EndCard(); } private void DrawFileButtons(string[] files) { for (int i = 0; i < files.Length; i++) { GUILayout.BeginHorizontal(Array.Empty()); if (Btn(Path.GetFileName(files[i]), "Load " + files[i], GUILayout.Width(250f))) { _pathText = files[i]; LoadScriptFromPath(files[i]); } if (Btn("Edit", "Open this file in the Script Editor tab.", GUILayout.Width(50f))) { OpenInTextEditor(files[i]); } GUILayout.Label(files[i], _hintStyle, Array.Empty()); GUILayout.EndHorizontal(); } } private void SaveScriptToPathText() { string target = _plugin.ResolveScriptSavePath(_pathText); RequestOverwriteSave(target, delegate { if (_engine.SaveScript(target)) { _pathText = target; RememberScriptPath(); } }); } private string ResolveScriptPath(string path) { try { string text = (path ?? string.Empty).Trim().Trim(new char[1] { '"' }); if (text.Length == 0) { return null; } if (Path.IsPathRooted(text)) { return File.Exists(text) ? text : null; } string text2 = Path.Combine(_plugin.ScriptDirectory, text); if (File.Exists(text2)) { return text2; } if (!Path.HasExtension(text) && File.Exists(text2 + ".uktas")) { return text2 + ".uktas"; } if (File.Exists(text)) { return Path.GetFullPath(text); } } catch (Exception) { } return null; } private bool LoadScriptFromPath(string path) { string text = ResolveScriptPath(path); if (text == null) { string text2 = (string.IsNullOrEmpty(path) ? "(no path typed)" : path); _statusText = "No script file found at: " + text2 + " Nothing was loaded and the game was not paused."; _statusIsError = true; _plugin.Toast("No script file found: " + text2 + ". Nothing was loaded; the game was not paused.", error: true); return false; } _pathText = text; if (!_engine.LoadScript(text, announce: true)) { return false; } _lastSyncedTick = -1; RememberScriptPath(); return true; } private void DrawClockCard() { BeginCard("Clock"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("host_frametime", "Virtual seconds per tick. 0.008 is 125 ticks per second, ULTRAKILL's native physics step.", GUILayout.Width(100f)); _frametimeText = Field(_frametimeText, "Seconds per tick, for example 0.008.", GUILayout.Width(100f)); if (Btn("Apply", "Use the typed value as the tick length.", GUILayout.Width(60f))) { ApplyFrametime(_frametimeText); } if (Btn("125 fps (native)", "0.008 s per tick: one native physics step. The default.", GUILayout.Width(115f))) { ApplyFrametime("0.008"); } if (Btn("250 fps", "0.004 s per tick.", GUILayout.Width(70f))) { ApplyFrametime("0.004"); } if (Btn("500 fps", "0.002 s per tick.", GUILayout.Width(70f))) { ApplyFrametime("0.002"); } if (Btn("1000 fps", "0.001 s per tick.", GUILayout.Width(75f))) { ApplyFrametime("0.001"); } GUILayout.EndHorizontal(); float num = Slide((float)_time.HostFrametime, 0.001f, 0.05f, "Drag to change the tick length (0.001 to 0.05 seconds)."); num = Mathf.Round(num * 100000f) / 100000f; if (Math.Abs(num - (float)_time.HostFrametime) > 1E-06f) { _time.SetHostFrametime(num); _plugin.DefaultHostFrametime.Value = num; _frametimeText = num.ToString("0.######", CultureInfo.InvariantCulture); if (_engine.Script != null) { _engine.Script.Properties.HostFrametime = _time.HostFrametime; _engine.Script.InvalidateTimeline(); } } Hint(_cachedClock); GUILayout.Space(2f); GUILayout.Label(_cachedProgress, Array.Empty()); Hint(_cachedMode); Hint(_cachedStatusDetail); EndCard(); } private void DrawStartupOnPlayCard() { BeginCard("Startup on Play"); int num = 0; string text = (_plugin.PlayStartMode.Value ?? "script").Trim().ToLowerInvariant(); for (int i = 0; i < StartValues.Length; i++) { if (StartValues[i] == text) { num = i; } } int num2 = ChoiceRow(num, StartLabels, StartTips, 0f); if (num2 != num) { _plugin.PlayStartMode.Value = StartValues[num2]; } _plugin.RestartLevelOnPlay.Value = Tog(_plugin.RestartLevelOnPlay.Value, "Restart Level on Play (overrides the choice above)", "Every Play reloads the current mission first, whatever the buttons above say."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("level", "Scene name used by 'Load level', for example 1-1. Empty uses the script header.", GUILayout.Width(40f)); _plugin.PlayStartLevel.Value = Field(_plugin.PlayStartLevel.Value, "Scene to load before frame 1 when 'Load level' is chosen.", GUILayout.Width(220f)); Lbl("state slot", "Savestate slot restored before frame 1 when 'Load savestate' is chosen.", GUILayout.Width(65f)); _plugin.PlayStartStateSlot.Value = Mathf.Clamp(IntField(_plugin.PlayStartStateSlot.Value, 40, "Savestate slot restored before frame 1 when Load savestate is chosen."), 0, 9); GUILayout.EndHorizontal(); EndCard(); } private void DrawNoRefreshCard() { BeginCard("Fast-forward (NoRefresh)"); _plugin.UseNorefresh.Value = Tog(_plugin.UseNorefresh.Value, "Use norefresh checkpoints (Play resumes from the last valid norefresh line)", "When a cached checkpoint exists for this level, Play skips straight to it instead of replaying everything before."); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Clear norefresh cache", "Forget every cached checkpoint.", GUILayout.Width(170f))) { _engine.ClearNorefreshCache(); } GUILayout.Label("cached checkpoints: " + _states.NorefreshCount, _hintStyle, Array.Empty()); GUILayout.EndHorizontal(); Separator(); _plugin.NoRefreshFastForward.Value = Tog(_plugin.NoRefreshFastForward.Value, "Enable FFF NoRefresh Fast-Forward (run FFF segments with no 3D rendering)", "Segments before an FFF marker run with all cameras off at uncapped speed. Rendering returns right after the marker."); _plugin.PauseAtNoRefreshBreak.Value = Tog(_plugin.PauseAtNoRefreshBreak.Value, "Pause at the FFF breakpoint instead of continuing with rendering", "Stop on the exact tick where the fast-forward ends."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("NoRefresh to tick", "Fast-forward headless to this tick, then show the game again.", GUILayout.Width(110f)); _noRefreshTickText = Field(_noRefreshTickText, "Target tick number.", GUILayout.Width(80f)); if (Btn("Run", "Fast-forward to the typed tick.", GUILayout.Width(60f))) { if (int.TryParse(_noRefreshTickText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { _engine.RunNoRefreshToTick(result); } else { _statusText = "NoRefresh tick must be an integer."; _statusIsError = true; } } GUI.enabled = _engine.NoRefreshActive; if (Btn("Abort", "Stop the fast-forward at the current tick (F5 or F11 also work).", GUILayout.Width(70f))) { _engine.AbortNoRefresh(); } GUI.enabled = true; GUILayout.EndHorizontal(); int num = ((_engine.Script != null) ? _engine.Script.NoRefreshBreakTicks.Count : 0); int num2 = ((num > 0) ? _engine.Script.NextNoRefreshBreakTick(_engine.CurrentTick) : (-1)); Hint(_engine.NoRefreshActive ? ("NOREFRESH " + _engine.CurrentTick + " -> " + _engine.NoRefreshTargetTick + " " + _engine.NoRefreshTicksPerSecond.ToString("0", CultureInfo.InvariantCulture) + " ticks/s (" + _engine.SuspendedCameraCount + " cameras off)") : ((num == 0) ? "no FFF markers in this script" : ((num2 > 0) ? (num + " FFF breakpoint(s); next at tick " + num2) : (num + " FFF breakpoint(s); none ahead of this tick")))); EndCard(); } private void DrawBakingCard() { BakeManager bake = _time.Bake; if (bake != null) { BeginCard("Baking"); GUILayout.Label("WARNING: BAKED PLAYBACK IS NOT LEGITIMATE. It replays stored state instead of pure inputs. Runs using it are not valid TAS runs.", _errorStyle, Array.Empty()); GUILayout.BeginHorizontal(Array.Empty()); bake.EnableBakedPlayback.Value = Tog(bake.EnableBakedPlayback.Value, "Enable Baked Playback (.ukbake)", "NOT LEGITIMATE. Inside a bake_start/bake_end block with a valid .ukbake, the inputs still run and the baked world state is written over the game after every tick. Can be switched at any time. A run that uses it cannot be submitted.", GUILayout.Width(250f)); GUILayout.Label("WARNING: BAKED PLAYBACK IS NOT LEGITIMATE. It replays stored state instead of pure inputs. Runs using it are not valid TAS runs.", _errorStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); GUILayout.EndHorizontal(); bake.VerifyRawPlayback.Value = Tog(bake.VerifyRawPlayback.Value, "Verify Raw Playback Against Bake (Drift Detector)", "With baked playback off, compare the live player and coin positions to the bake every tick and report the first divergence in each block."); bake.SkipBakedBlocks.Value = Tog(bake.SkipBakedBlocks.Value, "Skip Baked Blocks to End", "When a block has a valid bake, jump straight to its last baked frame and continue live on the first tick after bake_end."); GUILayout.BeginHorizontal(Array.Empty()); TasScript script = _engine.Script; GUI.enabled = script != null && script.HasBakeBlocks && !string.IsNullOrEmpty(_engine.ScriptPath); if (Btn("Force Re-Bake All Blocks", "Delete this script's .ukbake files; the next run records every block fresh.", GUILayout.Width(190f))) { int num = bake.ForceRebake(script, _engine.ScriptPath); _plugin.Toast("Force re-bake: " + num + " .ukbake file(s) deleted; the next run records every block.", error: false); } GUI.enabled = true; bool flag = bake.EnableBakedPlayback.Value || bake.Mode == BakeBlockMode.Enforced || (object)bake.StatusText == "[BAKED - SKIPPED TO END - NOT LEGIT]"; GUILayout.Label(bake.StatusText, flag ? _errorStyle : _hintStyle, Array.Empty()); GUILayout.EndHorizontal(); if (bake.EnableBakedPlayback.Value) { GUILayout.Label("STATUS: NON-LEGIT - baked playback is ON. This run replays stored state and is not a valid TAS run.", _errorStyle, Array.Empty()); } if (BakeManager.RunIsSubmittable) { Hint("Run status: real inputs only, no baked state applied in this run (submittable)."); } else { GUILayout.Label("Run submission: BLOCKED - NOT SUBMITTABLE (" + BakeManager.NotSubmittableReason + "). Start a fresh run from tick 0 with baked playback off.", _errorStyle, Array.Empty()); } int num2 = script?.BakeBlocks.Count ?? 0; Hint((num2 == 0) ? "no bake_start / bake_end blocks in this script" : (num2 + " bake block(s), " + bake.CachedBlockCount(script) + " with a valid bake in memory" + ((bake.DetailText.Length > 0) ? (" " + bake.DetailText) : string.Empty))); string correctionText = bake.CorrectionText; if (correctionText.Length > 0) { Hint(correctionText); } EndCard(); } } private void DrawSavestateCard() { BeginCard("Savestates"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Active slot", "Slot used by the quick save / load hotkeys (F8 / F9). 0 to " + 9 + ".", GUILayout.Width(80f)); if (int.TryParse(Field(_plugin.ActiveStateSlot.Value.ToString(), "Slot number.", GUILayout.Width(40f)), out var result)) { _plugin.ActiveStateSlot.Value = Mathf.Clamp(result, 0, 9); } if (Btn("Save slot", "Store the whole game state in this slot (F8).", GUILayout.Width(80f))) { _states.Save(_plugin.ActiveStateSlot.Value); } if (Btn("Load slot", "Restore the game state saved in this slot (F9).", GUILayout.Width(80f))) { _engine.LoadStateSlot(_plugin.ActiveStateSlot.Value); } GUILayout.Label(_states.SlotSummary(_plugin.ActiveStateSlot.Value), _hintStyle, Array.Empty()); GUILayout.EndHorizontal(); EndCard(); } private void DrawStudioCard() { BeginCard("Step studio"); DrawStudioControls(); EndCard(); } private void DrawStudioControls() { GUILayout.BeginHorizontal(Array.Empty()); Lbl("Pause at tick", "Play until this tick, then pause there.", GUILayout.Width(88f)); _pauseAtTickText = Field(_pauseAtTickText, "Tick number to stop at.", GUILayout.Width(80f)); if (Btn("Play to Tick", "Play from here and pause on the typed tick.", GUILayout.Width(100f))) { if (int.TryParse(_pauseAtTickText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { _engine.PlayToTick(result); } else { _statusText = "Pause-at-tick must be an integer."; _statusIsError = true; } } if (Btn("Overwrite from Here", "Throw away every frame after the current tick so you can record new input from here.", GUILayout.Width(140f))) { _engine.BranchFromCurrentTick(); } if (Btn("Undo Step", "Go back one tick and remove the last step-recorded frame (Ctrl+Z).", GUILayout.Width(85f))) { _engine.UndoStep(); } if (Btn("Restore Branch", "Bring back the frames removed by the last 'Overwrite from Here'.", GUILayout.Width(110f))) { _engine.RestoreBranch(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); _plugin.StepRecord.Value = Tog(_plugin.StepRecord.Value, "Step-record staged input (F6 writes one tick)", "While paused, each F6 writes the keys you are holding as one new frame."); _plugin.AutoSaveToDisk.Value = Tog(_plugin.AutoSaveToDisk.Value, "Auto-save to disk", "Write the script file after every edit and when recording stops."); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Undo history (ticks)", "How many ticks Undo Step (Ctrl+Z) can go back: one snapshot per F6 step is kept in memory (1 - 1000, default " + 120 + "). Changing it clears the stored history.", GUILayout.Width(130f)); _plugin.RollingHistoryTicks.Value = Mathf.Clamp(IntField(_plugin.RollingHistoryTicks.Value, 60, "Rolling history length in ticks (1 - 1000)."), 1, 1000); _plugin.HistoryDuringPlayback.Value = Tog(_plugin.HistoryDuringPlayback.Value, "Also keep history while playing", "Snapshot every tick of continuous playback too, not only F6 steps. Costs one capture per tick."); GUILayout.EndHorizontal(); string text = TasInputColumns.FormatCompact(_engine.StagedButtons); Hint("free-look " + (_engine.FreeLookActive ? "ON" : "off") + " staged " + text + " pitch/yaw " + _engine.StagedPitch.ToString("0.00") + "/" + NumYaw(_engine.StagedYaw)); if (_engine.PauseAtTick >= 0) { Hint("seeking to tick " + _engine.PauseAtTick); } if (_engine.BranchTick >= 0) { Hint("branch point: tick " + _engine.BranchTick); } } private void ApplyFrametime(string text) { if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || result < 0.0001 || result > 1.0) { _statusText = "Frametime must be " + 0.0001 + " - " + 1.0 + " seconds."; _statusIsError = true; return; } _time.SetHostFrametime(result); _plugin.DefaultHostFrametime.Value = (float)result; _frametimeText = result.ToString("0.########", CultureInfo.InvariantCulture); if (_engine.Script != null) { _engine.Script.Properties.HostFrametime = result; _engine.Script.InvalidateTimeline(); } _statusText = "host_frametime = " + _frametimeText + " (" + (1.0 / result).ToString("0.##") + " ticks/s, " + _time.StepsPerTick.ToString("0.###") + " native steps per tick)"; _statusIsError = false; _engine.AutoSaveIfEnabled(); } private void RefreshFileList() { int frameCount = SimulationFreeze.FrameCount; if (frameCount - _filesFrame >= 120 || (_files.Length == 0 && _exampleFiles.Length == 0)) { _filesFrame = frameCount; _files = ScriptFilesIn(_plugin.ScriptDirectory); _exampleFiles = ScriptFilesIn(Path.Combine(_plugin.ScriptDirectory, "examples")); } } private static string[] ScriptFilesIn(string folder) { try { if (!Directory.Exists(folder)) { return new string[0]; } string[] files = Directory.GetFiles(folder, "*.uktas"); string[] files2 = Directory.GetFiles(folder, "*.hltas"); string[] array = new string[files.Length + files2.Length]; Array.Copy(files, 0, array, 0, files.Length); Array.Copy(files2, 0, array, files.Length, files2.Length); Array.Sort(array, (IComparer?)StringComparer.OrdinalIgnoreCase); return array; } catch { return new string[0]; } } private void DrawFrameEditorTab() { //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) if (_engine.Script == null) { BeginCard("No script loaded"); GUILayout.Label("There is no script in memory yet.", _bodyStyle, Array.Empty()); Hint("Load one from the General tab, write one in the Script Editor tab, or record a run."); GUILayout.BeginHorizontal(Array.Empty()); if (BtnPrimary("Create new script", "Start an empty script in memory.", GUILayout.Width(180f))) { _engine.NewScript(_pathText); } GUILayout.EndHorizontal(); EndCard(); return; } TasScript script = _engine.Script; BeginCard("Script"); GUILayout.Label(string.IsNullOrEmpty(_engine.ScriptPath) ? "(unsaved)" : _engine.ScriptPath, Array.Empty()); Hint("lines " + script.Lines.Count + " ticks " + script.TotalTicks + " duration " + script.TotalTime.ToString("0.###") + "s seed " + script.Properties.Seed); EndCard(); DrawStudioCard(); BeginCard("Around the current tick"); Hint("autofuncs |movem |action|frametime |yaw |pitch |frames|commands"); int num = _engine.CurrentLineIndex; if (num < 0) { num = 0; } int num2 = Math.Max(0, num - 5); int num3 = Math.Min(script.Lines.Count - 1, num + 5); _lineScroll = GUILayout.BeginScrollView(_lineScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(160f) }); for (int i = num2; i <= num3; i++) { TasFrameLine tasFrameLine = script.Lines[i]; bool num4 = i == num; if (num4) { GUI.color = new Color(1f, 0.74f, 0.45f); } GUILayout.Label((num4 ? "> " : " ") + i.ToString().PadLeft(5) + " " + tasFrameLine.ToDisplayLine(), _hudStyle, Array.Empty()); GUI.color = Color.white; } GUILayout.EndScrollView(); GUILayout.BeginHorizontal(Array.Empty()); _autoSync = Tog(_autoSync, "Follow playback", "Keep the fields below on the frame that is playing.", GUILayout.Width(130f)); if (Btn("Sync to current frame", "Reload the fields below from the frame at the current tick.", GUILayout.Width(150f))) { SyncEditor(force: true); } if (Btn("Split Bulk", "Cut the current framebulk into two halves (commands stay on the first).", GUILayout.Width(90f))) { if (script.SplitBulkInHalf(_engine.CurrentLineIndex)) { _lastSyncedTick = -1; _statusText = "Split the framebulk in half; commands stayed on the first half."; _statusIsError = false; _engine.AutoSaveIfEnabled(); } else { _statusText = "That line has no bulk range to split (frames must be 2 or more)."; _statusIsError = true; } } if (Btn("Duplicate", "Copy the current framebulk right below itself.", GUILayout.Width(85f))) { script.Duplicate(_engine.CurrentLineIndex); _lastSyncedTick = -1; _engine.AutoSaveIfEnabled(); } if (Btn("Merge identical", "Join neighbouring lines that hold the same input into one bulk.", GUILayout.Width(110f))) { script.MergeAdjacent(); _lastSyncedTick = -1; _engine.AutoSaveIfEnabled(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Insert Framebulk", "Add an empty framebulk after the current one.", GUILayout.Width(120f))) { script.InsertAfter(_engine.CurrentLineIndex); _lastSyncedTick = -1; _engine.AutoSaveIfEnabled(); } if (BtnDanger("Delete Framebulk", "Remove the current framebulk from the script.", GUILayout.Width(125f))) { script.RemoveAt(_engine.CurrentLineIndex); _lastSyncedTick = -1; _engine.AutoSaveIfEnabled(); } GUILayout.FlexibleSpace(); if (Btn("Save to Disk", "Write the script to the path in the General tab. Asks before overwriting an existing file.", GUILayout.Width(110f))) { SaveScriptToPathText(); } GUILayout.EndHorizontal(); EndCard(); if (_autoSync && _engine.CurrentTick != _lastSyncedTick) { SyncEditor(force: false); } BeginCard("Current framebulk"); Hint("Edits are live during playback. autofuncs |movem |action|frametime |yaw |pitch |frames|commands"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("autofuncs", "Automatic helpers on this line: j autojump, s autoslide, d autodash, c coin assist, g ground slam, w whiplash assist, t coin throw (once per bulk), e deadcoin (when a coin is airborne: aim one frame, fire the next, then the aim is yours again).", GUILayout.Width(70f)); _autofuncsText = Field(_autofuncsText, "Ten characters, '-' for off.", GUILayout.Width(104f)); Lbl("movement", "Movement keys held: f forward, l left, r right, b back, d dash, s slide.", GUILayout.Width(66f)); _movementText = Field(_movementText, "Six characters, '-' for off.", GUILayout.Width(64f)); Lbl("actions", "Actions: j jump, 1 fire, 2 alt fire, p punch, v whiplash, wN weapon slot, x change fist, and more (see the guide).", GUILayout.Width(52f)); _actionsText = Field(_actionsText, "Action tokens, '-' for none.", GUILayout.Width(80f)); Lbl("frames", "How many ticks this line lasts.", GUILayout.Width(48f)); _framesText = Field(_framesText, "A whole number, 1 or more.", GUILayout.Width(56f)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("frametime", "Tick length for just this line. Leave empty to use the script's host_frametime.", GUILayout.Width(70f)); _ftOverrideText = Field(_ftOverrideText, "Seconds, or empty.", GUILayout.Width(104f)); Lbl("yaw", "Horizontal look angle. Absolute (90.0), relative (d+2.0) or '-' to keep.", GUILayout.Width(66f)); _yawText = Field(_yawText, "Yaw value.", GUILayout.Width(64f)); Lbl("pitch", "Vertical look angle. Absolute (0.0), relative (d-1.0) or '-' to keep.", GUILayout.Width(52f)); _pitchText = Field(_pitchText, "Pitch value.", GUILayout.Width(80f)); Hint("(- keeps / inherits)"); GUILayout.EndHorizontal(); Hint("autofuncs: a j s d c g w t e movement: f l r b d s actions: j 1 2 p v wN x F K N P T < > yN S (see spec)"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("commands", "Console-style commands for this line, separated by ';'. Prefix one with once: to run it on the first tick only.", GUILayout.Width(70f)); _commandsText = Field(_commandsText, "Example: once:echo hello; click"); GUILayout.EndHorizontal(); Hint("Commands run on every tick of the bulk; prefix one with once: to run it on the first tick only."); _liveEdit = Tog(_liveEdit, "Live apply during playback", "Apply every change to the running script immediately.", GUILayout.Width(220f)); if (_liveEdit && GUI.changed) { ApplyLineEdits(); } GUILayout.BeginHorizontal(Array.Empty()); if (BtnPrimary("Apply to this line", "Write the fields above into the current framebulk.", GUILayout.Width(140f))) { ApplyLineEdits(); } if (Btn("Append framebulk", "Add an empty framebulk at the very end of the script.", GUILayout.Width(130f))) { script.InsertAfter(script.Lines.Count - 1); _lastSyncedTick = -1; _statusText = "Appended a new framebulk at the end of the script."; _statusIsError = false; _engine.AutoSaveIfEnabled(); } if (Btn("Rewind to start", "Go back to tick 0.", GUILayout.Width(120f))) { _engine.Rewind(); } GUILayout.EndHorizontal(); StatusLine(); EndCard(); BeginCard("Properties"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("seed", "Random seed applied when the script starts. Same seed, same run.", GUILayout.Width(38f)); _seedText = Field(_seedText, "A 32-bit whole number.", GUILayout.Width(90f)); Lbl("host_frametime", "Default tick length for the whole script.", GUILayout.Width(100f)); _frametimeText = Field(_frametimeText, "Seconds per tick.", GUILayout.Width(90f)); Lbl("author", "Who made the script (saved in the header).", GUILayout.Width(48f)); _authorText = Field(_authorText, "Your name.", GUILayout.Width(150f)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("description", "A note about the run (saved in the header).", GUILayout.Width(75f)); _descriptionText = Field(_descriptionText, "Free text."); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (BtnPrimary("Apply properties", "Write seed, frametime, author and description into the script header.", GUILayout.Width(140f))) { ApplyProperties(); } string text = _bridge.CurrentLevelId ?? string.Empty; GUI.enabled = !string.IsNullOrEmpty(text); if (Btn(string.IsNullOrEmpty(text) ? "Load current level" : ("Load current level (" + text + ")"), "Make Play load the level you are standing in before frame 1 (writes start_type load_level).", GUILayout.Width(230f))) { script.Properties.StartType = TasStartType.LoadLevel; script.Properties.LoadLevelName = text; _statusText = "Play now loads level " + text + " first (header: start_type load_level " + text + ")."; _statusIsError = false; _engine.AutoSaveIfEnabled(); } GUI.enabled = true; GUILayout.EndHorizontal(); if (string.IsNullOrEmpty(text)) { Hint("Load current level needs a loaded campaign scene."); } if (script.Warnings.Count > 0) { GUILayout.Space(4f); Hint("Parser warnings (" + script.Warnings.Count + "):"); GUILayout.Label(script.Warnings[script.Warnings.Count - 1], _errorStyle, Array.Empty()); } EndCard(); } private void SyncEditor(bool force) { TasFrameLine tasFrameLine = _engine.CurrentLine; if (tasFrameLine == null && _engine.Script != null && _engine.Script.Lines.Count > 0) { int index = Mathf.Clamp(_engine.CurrentLineIndex, 0, _engine.Script.Lines.Count - 1); tasFrameLine = _engine.Script.Lines[index]; } if (tasFrameLine != null) { _autofuncsText = TasInputColumns.FormatAutofuncs(tasFrameLine.Autofuncs); _movementText = TasInputColumns.FormatMovement(tasFrameLine.Buttons); _actionsText = TasInputColumns.FormatActions(tasFrameLine.Buttons); _framesText = tasFrameLine.Count.ToString(CultureInfo.InvariantCulture); _yawText = tasFrameLine.Yaw.Raw; _pitchText = tasFrameLine.Pitch.Raw; _ftOverrideText = (tasFrameLine.HasFrametimeOverride ? TasScript.FormatFrametime(tasFrameLine.FrametimeOverride) : string.Empty); _commandsText = string.Join("; ", tasFrameLine.Commands.ToArray()); if (_engine.Script != null) { _seedText = _engine.Script.Properties.Seed.ToString(CultureInfo.InvariantCulture); _frametimeText = _engine.Script.Properties.HostFrametime.ToString("0.######", CultureInfo.InvariantCulture); _authorText = _engine.Script.Properties.Author; _descriptionText = _engine.Script.Properties.Description; } _lastSyncedTick = _engine.CurrentTick; if (force) { _statusText = "Editor synced to frame " + _engine.CurrentTick + "."; } } } private void ApplyLineEdits() { if (_engine.Script == null) { return; } int currentLineIndex = _engine.CurrentLineIndex; if (currentLineIndex < 0 || currentLineIndex >= _engine.Script.Lines.Count) { _statusText = "No current line to edit."; _statusIsError = true; return; } TasFrameLine tasFrameLine = _engine.Script.Lines[currentLineIndex]; if (!int.TryParse(_framesText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result < 1) { _statusText = "The frames column (field 7) must be a positive integer."; _statusIsError = true; return; } try { TasAutofuncs autofuncs = TasInputColumns.ParseAutofuncs(_autofuncsText, 0, _autofuncsText); TasButtons buttons = TasInputColumns.ParseMovement(_movementText, 0, _movementText) | TasInputColumns.ParseActions(_actionsText, 0, _actionsText); AngleToken angleToken = AngleToken.Parse(_pitchText, "pitch", 0, _pitchText); AngleToken angleToken2 = AngleToken.Parse(_yawText, "yaw", 0, _yawText); bool flag = !string.IsNullOrEmpty(_ftOverrideText.Trim()); double result2 = 0.0; if (flag && (!double.TryParse(_ftOverrideText, NumberStyles.Float, CultureInfo.InvariantCulture, out result2) || result2 < 0.0001 || result2 > 1.0)) { _statusText = "Frame frametime must be " + 0.0001 + " - " + 1.0 + "."; _statusIsError = true; return; } if (tasFrameLine.Kind == TasFrameKind.ChangeYaw && (angleToken2.Unchanged || angleToken2.IsDelta)) { _statusText = "change yaw needs an absolute yaw value."; _statusIsError = true; return; } if (tasFrameLine.Kind == TasFrameKind.ChangePitch && (angleToken.Unchanged || angleToken.IsDelta)) { _statusText = "change pitch needs an absolute pitch value."; _statusIsError = true; return; } if (tasFrameLine.Kind == TasFrameKind.TargetYaw && (angleToken2.Unchanged || angleToken2.IsDelta)) { _statusText = "target_yaw needs an absolute yaw value."; _statusIsError = true; return; } tasFrameLine.Count = Math.Min(result, 1000000); tasFrameLine.Autofuncs = autofuncs; tasFrameLine.Buttons = buttons; tasFrameLine.Pitch = angleToken; tasFrameLine.Yaw = angleToken2; if (tasFrameLine.Kind == TasFrameKind.TargetYaw) { tasFrameLine.TargetYaw = angleToken2; } tasFrameLine.HasFrametimeOverride = flag; tasFrameLine.FrametimeOverride = (flag ? result2 : 0.0); tasFrameLine.Commands.Clear(); string[] array = _commandsText.Split(new char[1] { ';' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length > 0) { tasFrameLine.Commands.Add(text); } } _engine.Script.InvalidateTimeline(); _statusText = "Applied line " + currentLineIndex + " (" + tasFrameLine.Count + " frames)."; _statusIsError = false; _lastSyncedTick = -1; _engine.AutoSaveIfEnabled(); } catch (Exception ex) { _statusText = ex.Message; _statusIsError = true; } } private void ApplyProperties() { if (_engine.Script != null) { double result2; if (!int.TryParse(_seedText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { _statusText = "Seed must be a 32-bit integer."; _statusIsError = true; } else if (!double.TryParse(_frametimeText, NumberStyles.Float, CultureInfo.InvariantCulture, out result2) || result2 < 0.0001 || result2 > 1.0) { _statusText = "host_frametime must be " + 0.0001 + " - " + 1.0 + "."; _statusIsError = true; } else { _engine.Script.Properties.Seed = result; _engine.Script.Properties.HostFrametime = result2; _engine.Script.Properties.Author = _authorText; _engine.Script.Properties.Description = _descriptionText; _engine.Script.InvalidateTimeline(); _time.SetHostFrametime(result2); _plugin.DefaultHostFrametime.Value = (float)result2; _statusText = "Properties applied. Seed takes effect on the next play/rewind."; _statusIsError = false; _engine.AutoSaveIfEnabled(); } } } private void DrawStartup() { BeginCard("Script startup behavior"); Hint("The header start_type is used only when On Play is Script header. Restart Level on Play overrides every choice."); _plugin.WaitForPlayerControl.Value = Tog(_plugin.WaitForPlayerControl.Value, "Wait for Player Control (NewMovement.activated) before tick 1", "Hold tick 1 until V1 can actually move (elevator rides and intros)."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Scene settle frames", "Rendered frames to wait after control is granted, so triggers and occlusion culling settle.", GUILayout.Width(130f)); _plugin.SceneSettleFrames.Value = Mathf.Clamp(IntField(_plugin.SceneSettleFrames.Value, 40, "Rendered frames to wait after control is granted (0 to 30)."), 0, 30); GUILayout.EndHorizontal(); string[] labels = new string[6] { "Script header", "Current state", "Restart level", "Load level", "Load savestate", "Main menu (title screen)" }; int num = 0; string text = (_plugin.PlayStartMode.Value ?? "script").Trim().ToLowerInvariant(); for (int i = 0; i < StartValues.Length; i++) { if (StartValues[i] == text) { num = i; } } int num2 = ChoiceRow(num, labels, StartTips, 0f); if (num2 != num) { _plugin.PlayStartMode.Value = StartValues[num2]; } _plugin.RestartLevelOnPlay.Value = Tog(_plugin.RestartLevelOnPlay.Value, "Restart Level on Play (overrides the selection above)", "Every Play reloads the current mission first, whatever is selected above."); if (_plugin.RestartLevelOnPlay.Value) { Hint("Restart is active. The current mission scene will reload before frame 1."); } GUILayout.Space(4f); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Load level scene", "Scene name used by 'Load level', for example 1-1.", GUILayout.Width(120f)); _plugin.PlayStartLevel.Value = Field(_plugin.PlayStartLevel.Value, "Scene to load before frame 1.", GUILayout.Width(260f)); GUILayout.EndHorizontal(); Hint("Empty uses the script header's load_level scene."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Startup savestate slot", "Slot restored before frame 1 when 'Load savestate' is chosen.", GUILayout.Width(150f)); _plugin.PlayStartStateSlot.Value = Mathf.Clamp(IntField(_plugin.PlayStartStateSlot.Value, 45, "Savestate slot restored before frame 1 when Load savestate is chosen."), 0, 9); Hint("(0-" + 9 + ")"); GUILayout.EndHorizontal(); if (_engine.Script != null) { TasProperties properties = _engine.Script.Properties; string text2 = ((properties.StartType == TasStartType.LoadLevel) ? ("load_level " + properties.LoadLevelName) : ((properties.StartType == TasStartType.LoadState) ? ("load_state " + properties.LoadStateSlot) : properties.StartType.ToString().ToLowerInvariant())); Hint("Loaded script header: start_type " + text2); } else { Hint("No script loaded; header start_type is unavailable."); } EndCard(); BeginCard("Workflow"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("autoload", "A script loaded automatically when the game starts. Absolute, or relative to the script folder.", GUILayout.Width(70f)); _plugin.Autoload.Value = Field(_plugin.Autoload.Value, "Path of the script to load at boot. Empty = none."); GUILayout.EndHorizontal(); _plugin.Autoplay.Value = Tog(_plugin.Autoplay.Value, "Autoplay loaded script on boot", "Start playing the autoload script as soon as the game boots."); Hint("Path may be absolute or relative to " + _plugin.ScriptDirectory); GUILayout.BeginHorizontal(Array.Empty()); Lbl("default seed", "Seed written into new scripts.", GUILayout.Width(85f)); _plugin.DefaultSeed.Value = IntField(_plugin.DefaultSeed.Value, 90, "Seed written into new scripts."); Hint("native step " + _time.NativeFixedStep.ToString("0.####") + "s (fixed)"); GUILayout.EndHorizontal(); _plugin.GuiVisibleOnStart.Value = Tog(_plugin.GuiVisibleOnStart.Value, "Show this window on game start", "Open the TAS window as soon as the game starts. Insert toggles it any time."); EndCard(); DrawLoadout(); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Save config", "Write every plugin setting to the BepInEx config file now.", GUILayout.Width(120f))) { _plugin.ConfigFile.Save(); } GUILayout.EndHorizontal(); } private void DrawLoadout() { BeginCard("Weapons and loadout"); bool flag = Tog(_plugin.UnlockAllWeapons.Value, "Unlock all weapons and arms (in-memory, save files untouched)", "Report every weapon and arm as owned. Your save file is never changed."); if (flag != _plugin.UnlockAllWeapons.Value) { _plugin.UnlockAllWeapons.Value = flag; } if (WeaponUnlock.UnlockAll != flag) { WeaponUnlock.UnlockAll = flag; } if (WeaponUnlock.OwnedOverride != null) { Hint("A script's weapons header is active and takes priority over the unlock."); } GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Give all weapons", "Unlock and equip every weapon and arm right now (in memory only).", GUILayout.Width(140f))) { GiveAllWeapons(); } if (Btn("DUMP fist HUD (temp)", "Temporary diagnostic: write the fist / arm HUD state to a file.", GUILayout.Width(160f))) { DumpFistHud(); } if (Btn("Copy loadout", "Copy the weapons you own and your loadout settings as two script header lines.", GUILayout.Width(110f))) { CopyLoadout(); } GUI.enabled = _engine.Script != null; if (Btn("Write to script header", "Store the current weapons and loadout in the loaded script's header.", GUILayout.Width(160f))) { WriteLoadoutToScript(); } GUI.enabled = true; GUILayout.EndHorizontal(); Hint("Copy loadout captures the weapons you own and your loadout settings as two script header lines."); if (_loadoutText.Length > 0) { GUILayout.TextArea(_loadoutText, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(48f) }); Tip("The captured header lines. Select and copy them into your script."); } StatusLine(); EndCard(); } private void GiveAllWeapons() { if ((Object)(object)_bridge.PlayerComponent == (Object)null || _bridge.GunSetter == null) { _statusText = "No player loaded."; _statusIsError = true; return; } _plugin.UnlockAllWeapons.Value = true; WeaponUnlock.UnlockAll = true; if (!_bridge.ResetWeaponSlots()) { _statusText = "Unlock is on, but the weapon slots were not refreshed: " + _bridge.LastError; _statusIsError = true; } else { _statusText = ((WeaponUnlock.OwnedOverride != null) ? "Unlock is on, but a script's weapons header is active and takes priority." : "All weapons and arms given (in memory only). Untick the unlock to go back to your real weapons."); _statusIsError = WeaponUnlock.OwnedOverride != null; } } private bool TryBuildLoadoutText(out string text) { if (!_bridge.TryCaptureLoadout(out var weapons, out var loadout)) { text = (string.IsNullOrEmpty(_bridge.LastError) ? "Loadout capture failed." : _bridge.LastError); return false; } text = "weapons " + TasScript.FormatWeapons(weapons) + "\nloadout " + TasScript.FormatLoadout(loadout); return true; } private void DumpFistHud() { string text = FistHudDump.Write(_bridge); _statusText = "Fist HUD dump written: " + text; _statusIsError = false; } private void CopyLoadout() { if (!TryBuildLoadoutText(out var text)) { _statusText = text; _statusIsError = true; return; } _loadoutText = text; GUIUtility.systemCopyBuffer = text; _statusText = "Loadout copied: paste into the script header."; _statusIsError = false; } private void WriteLoadoutToScript() { if (!_engine.CaptureLoadoutIntoScript(out var error)) { _statusText = error; _statusIsError = true; return; } TasProperties properties = _engine.Script.Properties; _loadoutText = "weapons " + TasScript.FormatWeapons(properties.Weapons) + "\nloadout " + TasScript.FormatLoadout(properties.Loadout); _statusText = "Loadout written to the script header."; _statusIsError = false; _engine.AutoSaveIfEnabled(); } private void DrawTrajectoryOptions() { TrajectoryManager trajectory = _plugin.Trajectory; BeginCard("Player trajectory (SAR style)"); Hint("Sampled once per simulation tick. Hold freecam (F2), release the cursor with Left Alt, hover a node for its tick, click to scrub."); _plugin.TrajectoryEnabled.Value = Tog(_plugin.TrajectoryEnabled.Value, "Record and draw the path", "Draw the line V1 has travelled in the world."); _plugin.TrajectoryHoverHitbox.Value = Tog(_plugin.TrajectoryHoverHitbox.Value, "Show player hitbox on hover", "Draw the same box as Show player hitbox, at the tick under the path cursor."); _plugin.TrajectoryGradient.Value = Tog(_plugin.TrajectoryGradient.Value, "Colour by speed (green slow, yellow medium, magenta fast)", "Colour the line by how fast you were going. Off uses the single colour below."); GUILayout.Label("Visibility", Array.Empty()); int value = ChoiceRow(Mathf.Clamp(_plugin.TrajectoryVisibilityMode.Value, 0, 2), new string[3] { "Always", "Freecam only", "Hidden" }, new string[3] { "Always draw the path.", "Draw it only while the freecam is on.", "Never draw it." }, 0f); _plugin.TrajectoryVisibilityMode.Value = value; GUILayout.BeginHorizontal(Array.Empty()); Lbl("Line thickness", "How many parallel lines make the path (1 to 6).", GUILayout.Width(150f)); _plugin.TrajectoryThickness.Value = Mathf.Round(Slide(_plugin.TrajectoryThickness.Value, 1f, 6f, "Line thickness.", GUILayout.Width(180f))); GUILayout.Label(_plugin.TrajectoryThickness.Value.ToString("0"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Opacity", "How see-through the path is.", GUILayout.Width(150f)); _plugin.TrajectoryOpacity.Value = Slide(_plugin.TrajectoryOpacity.Value, 0.1f, 1f, "Path opacity.", GUILayout.Width(180f)); GUILayout.Label(Mathf.RoundToInt(_plugin.TrajectoryOpacity.Value * 100f) + "%", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Marker every N ticks", "Draw a small cross on the path every N ticks. 0 turns markers off.", GUILayout.Width(150f)); _plugin.TrajectoryMarkerEvery.Value = Mathf.RoundToInt(Slide(_plugin.TrajectoryMarkerEvery.Value, 0f, 60f, "Marker spacing in ticks.", GUILayout.Width(180f))); GUILayout.Label((_plugin.TrajectoryMarkerEvery.Value == 0) ? "off" : _plugin.TrajectoryMarkerEvery.Value.ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Single colour (hex)", "Path colour when the speed gradient is off, as #RRGGBB.", GUILayout.Width(150f)); _plugin.TrajectoryColor.Value = Field(_plugin.TrajectoryColor.Value, "Hex colour such as #40FF60.", GUILayout.Width(90f)); GUILayout.EndHorizontal(); if (trajectory != null) { Hint("Nodes recorded: " + trajectory.Count); } EndCard(); } private void DrawCoinPathOptions() { CoinPathManager coinPaths = _plugin.CoinPaths; BeginCard("Coin paths"); Hint("Every coin is recorded once per simulation tick. Yellow: in flight. Green: punched. Cyan: shot. Red: shot back by an enemy. Magenta: tracking an enemy. Write 'clearcoinpaths' in field 8 to wipe the paths."); _plugin.CoinPathEnabled.Value = Tog(_plugin.CoinPathEnabled.Value, "Record and draw coin paths", "Draw where every coin has flown. Off stops recording and drawing."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Opacity", "How see-through the coin paths are.", GUILayout.Width(150f)); _plugin.CoinPathOpacity.Value = Slide(_plugin.CoinPathOpacity.Value, 0.1f, 1f, "Coin path opacity.", GUILayout.Width(180f)); GUILayout.Label(Mathf.RoundToInt(_plugin.CoinPathOpacity.Value * 100f) + "%", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Line thickness", "How many parallel lines make a coin path (1 to 6).", GUILayout.Width(150f)); _plugin.CoinPathThickness.Value = Mathf.Round(Slide(_plugin.CoinPathThickness.Value, 1f, 6f, "Coin path line thickness.", GUILayout.Width(180f))); GUILayout.Label(_plugin.CoinPathThickness.Value.ToString("0"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Clear coin paths", "Forget every recorded coin trail now.", GUILayout.Width(160f))) { coinPaths?.Clear(); } GUILayout.EndHorizontal(); if (coinPaths != null) { Hint("Trails recorded: " + coinPaths.Count); } EndCard(); } private void DrawBranches() { //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0376: Unknown result type (might be due to invalid IL or missing references) //IL_037b: Unknown result type (might be due to invalid IL or missing references) BranchProject project = _plugin.Project; if (_projectPathText == string.Empty) { _projectPathText = ((_plugin.ScriptDirectory != null) ? Path.Combine(_plugin.ScriptDirectory, "route.uktasproj") : "route.uktasproj"); } BeginCard("Route projects (.uktasproj)"); Hint("One project file holds many routes. The active route is compiled to -bridged.uktas, which the TAS player loads."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Path", "Where the .uktasproj project file lives.", GUILayout.Width(60f)); _projectPathText = Field(_projectPathText, "Project file path.", GUILayout.ExpandWidth(true)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Author", "Who made the project.", GUILayout.Width(60f)); _projectAuthorText = Field(_projectAuthorText, "Your name.", GUILayout.Width(160f)); Lbl("Target level", "The level this project is for.", GUILayout.Width(90f)); _projectLevelText = Field(_projectLevelText, "Level name.", GUILayout.Width(160f)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("New project from current script", "Create a project file whose first route is the script in memory.", GUILayout.Width(220f))) { CreateProject(); } if (Btn("Open project", "Open the project at the path above.", GUILayout.Width(110f))) { OpenProject(); } if (Btn("Save project", "Write the project file and refresh the bridged script. Asks before overwriting an existing file.", GUILayout.Width(110f)) && project != null) { BranchProject toSave = project; RequestOverwriteSave(toSave.ProjectPath, delegate { toSave.SyncActive(_engine.Script); toSave.Save(); toSave.WriteBridged(); _branchStatus = "Saved " + toSave.ProjectPath + "."; }); } GUILayout.EndHorizontal(); if (project == null) { Hint("No project open."); if (_branchStatus.Length > 0) { Hint(_branchStatus); } EndCard(); return; } UktasBranch active = project.Active; Hint("Project " + project.Data.Name + " | active route: " + ((active != null) ? active.Name : "none") + " | bridged: " + Path.GetFileName(project.BridgedPath)); EndCard(); BeginCard("Routes"); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("Route", _sectionStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label("Ticks", _sectionStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); GUILayout.Label("Time (s)", _sectionStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); GUILayout.Label("vs active", _sectionStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUILayout.EndHorizontal(); _branchScroll = GUILayout.BeginScrollView(_branchScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(170f) }); IList branches = project.Branches; for (int num = 0; num < branches.Count; num++) { UktasBranch uktasBranch = branches[num]; bool flag = active != null && uktasBranch.Id == active.Id; GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label((flag ? "> " : " ") + uktasBranch.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(uktasBranch.TotalTicks.ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); GUILayout.Label(uktasBranch.TotalSeconds.ToString("0.000000", CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); GUILayout.Label(flag ? "active" : BranchProject.FormatDelta(project.DeltaAgainstActive(uktasBranch)), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); if (!flag && Btn("Switch to", "Make this the active route and reload the bridged script.", GUILayout.Width(90f))) { SwitchBranch(uktasBranch.Id); } GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); EndCard(); BeginCard("Fork"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Fork name", "Name of the new route.", GUILayout.Width(80f)); _forkNameText = Field(_forkNameText, "Route name.", GUILayout.Width(180f)); if (Btn("Fork at current time", "Start a new route that keeps every frame before this tick and continues from the live game state.", GUILayout.Width(170f))) { ForkAtCurrentTime(); } GUILayout.EndHorizontal(); Hint("Current tick " + _engine.CurrentTick + " (t = " + _engine.CurrentTime.ToString("0.000000", CultureInfo.InvariantCulture) + " s). Forking keeps frames before this tick and continues from the live state."); if (_branchStatus.Length > 0) { Hint(_branchStatus); } EndCard(); } private void CreateProject() { TasScript script = _engine.Script; if (script == null) { _branchStatus = "Load or record a script before creating a project."; return; } string text = ResolveProjectPath(_projectPathText); try { int seed = script.Properties.Seed; _plugin.Project = BranchProject.Create(text, Path.GetFileNameWithoutExtension(text), _projectAuthorText, seed, _projectLevelText, script); _engine.SetScript(TasScript.Parse(_plugin.Project.Active.Script, "bridged"), _plugin.Project.BridgedPath); _branchStatus = "Created " + _plugin.Project.ProjectPath + "."; } catch (Exception ex) { _branchStatus = "Create failed: " + ex.Message; } } private void OpenProject() { string text = ResolveProjectPath(_projectPathText); try { _plugin.Project = BranchProject.Open(text); _engine.SetScript(TasScript.Load(_plugin.Project.BridgedPath), _plugin.Project.BridgedPath); _branchStatus = "Opened " + text + "."; } catch (Exception ex) { _branchStatus = "Open failed: " + ex.Message; } } private void SwitchBranch(string branchId) { BranchProject project = _plugin.Project; if (project == null) { return; } try { TasScript script = project.SwitchTo(branchId, _engine.Script); _engine.SetScript(script, project.BridgedPath); _branchStatus = "Active route: " + project.Active.Name + ". Bridged script reloaded."; } catch (Exception ex) { _branchStatus = "Switch failed: " + ex.Message; } } private void ForkAtCurrentTime() { BranchProject project = _plugin.Project; if (project == null) { _branchStatus = "Create or open a project first."; return; } try { int currentTick = _engine.CurrentTick; TasScript forkedScript; UktasBranch uktasBranch = project.Fork(_forkNameText, _engine.Script, currentTick, out forkedScript); _engine.SetScriptKeepPosition(forkedScript, project.BridgedPath); _branchStatus = "Forked '" + uktasBranch.Name + "' at tick " + currentTick + ". Continue recording or stepping from here."; } catch (Exception ex) { _branchStatus = "Fork failed: " + ex.Message; } } private string ResolveProjectPath(string text) { string text2 = (text ?? string.Empty).Trim(); if (text2.Length == 0) { text2 = "route.uktasproj"; } if (!text2.EndsWith(".uktasproj", StringComparison.OrdinalIgnoreCase)) { text2 += ".uktasproj"; } if (!Path.IsPathRooted(text2)) { text2 = Path.Combine(_plugin.ScriptDirectory, text2); } return text2; } private void DrawRecording() { VideoRecorder video = _plugin.Video; if (_recordDirText == null) { _recordDirText = _plugin.RecordingDirectory.Value; } if (_ffmpegText == null) { _ffmpegText = _plugin.FfmpegPath.Value; } BeginCard("Offline video renderer"); Hint("Each frame averages sub-frame renders across the shutter. Physics is not advanced, so jumps and timings match the live run. The HUD is not in the video."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Output folder", "Folder the video is written to. Empty uses the script folder's Recordings directory.", GUILayout.Width(110f)); _recordDirText = Field(_recordDirText, "Folder path.", GUILayout.ExpandWidth(true)); if (_recordDirText != _plugin.RecordingDirectory.Value) { _plugin.RecordingDirectory.Value = _recordDirText; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("File name", "Name of the video file, for example run.mp4.", GUILayout.Width(110f)); _recordFileText = Field(_recordFileText, "File name with extension.", GUILayout.Width(260f)); GUILayout.EndHorizontal(); GUILayout.Label("Target video FPS", Array.Empty()); _recordFpsIndex = ChoiceRow(_recordFpsIndex, new string[3] { "30", "60", "120" }, new string[3] { "30 frames per second.", "60 frames per second.", "120 frames per second." }, 0f); GUILayout.Label("Motion blur samples", Array.Empty()); _recordSampleIndex = ChoiceRow(_recordSampleIndex, new string[5] { "1x (no blur)", "4x", "8x", "16x", "32x" }, new string[5] { "No motion blur: one render per video frame.", "4 sub-frames per tick. Light blur, fast.", "8 sub-frames per tick (1000 fps virtual). A good default.", "16 sub-frames per tick. Smooth blur, slower.", "32 sub-frames per tick. Smoothest, slowest." }, 0f); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Shutter angle", "How much of each frame the virtual shutter stays open. 180 degrees is the film look.", GUILayout.Width(110f)); _recordShutter = Slide(_recordShutter, 0.1f, 1f, "Shutter angle in degrees (36 to 360).", GUILayout.Width(200f)); GUILayout.Label(Mathf.RoundToInt(_recordShutter * 360f) + " deg", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUILayout.EndHorizontal(); Hint("Motion blur samples = rendered sub-frames per 0.008 s tick, with the camera interpolated between ticks (8x = 1000 fps virtual). Frames inside the shutter are averaged. 1x = no blur."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("ffmpeg path", "Where ffmpeg.exe is. Empty searches the game folder, then PATH.", GUILayout.Width(110f)); _ffmpegText = Field(_ffmpegText, "Full path to ffmpeg.exe.", GUILayout.ExpandWidth(true)); if (_ffmpegText != _plugin.FfmpegPath.Value) { _plugin.FfmpegPath.Value = _ffmpegText; } GUILayout.EndHorizontal(); string text = VideoRecorder.LocateFfmpeg(_plugin.FfmpegPath.Value, Paths.GameRootPath); Hint("ffmpeg: " + ((text != null) ? ("Found (" + text + ")") : "Missing. Install ffmpeg or set the path above.")); _plugin.RecordAudio.Value = Tog(_plugin.RecordAudio.Value, "Record audio (game sound follows game time; speakers are silent while recording)", "Capture the game's sound into the video. The speakers stay silent while rendering."); _plugin.RecordCleanRender.Value = Tog(_plugin.RecordCleanRender.Value, "Clean render while recording (hide TAS HUD, hitboxes, triggers, trajectory; show viewmodels)", "Hide every TAS overlay while the video renders, so only the game is filmed."); EndCard(); BeginCard("Render"); if (video != null && video.IsRecording) { GUILayout.Label("Frames encoded: " + video.FramesEncoded + " (" + video.Fps + " fps, " + video.Samples + " samples)", _bodyStyle, Array.Empty()); if (BtnDanger("Stop Recording", "Stop rendering and finish the video file.", GUILayout.Width(160f))) { video.Stop("stopped from the GUI"); } } else if (BtnPrimary("Start Recording", "Start rendering the run to a video with the settings above.", GUILayout.Width(160f)) && video != null) { string text2 = _plugin.RecordingDirectory.Value; if (string.IsNullOrEmpty(text2)) { text2 = Path.Combine(_plugin.ScriptDirectory, "Recordings"); } string path = (string.IsNullOrEmpty(_recordFileText) ? "run.mp4" : _recordFileText); if (!video.Start(Path.Combine(text2, path), RecordFpsOptions[_recordFpsIndex], RecordSampleOptions[_recordSampleIndex], _recordShutter)) { _plugin.Toast(video.LastError, error: true); } } if (video != null && video.Status != null && video.Status.Length > 0) { Hint(video.Status); } Hint("From a script: header lines record_video , record_fps, blend_samples, shutter_angle (recording ends with the script). Commands: bxt_rec start [file], bxt_rec stop."); EndCard(); } private void DrawKeybinds() { //IL_0031: 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_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0181: 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_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0253: 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_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) BeginCard("Hotkeys"); Hint("Click Rebind, then press a key; Escape cancels; right-click a row or its Rebind button to unbind it. These keys are read through legacy Input and never appear in the TAS."); KeybindRow("Toggle GUI", _plugin.KeyToggleGui, new KeyboardShortcut((KeyCode)277, Array.Empty()), "Show or hide this window."); KeybindRow("Play / Pause", _plugin.KeyPlayPause, new KeyboardShortcut((KeyCode)286, Array.Empty()), "Play starts the script from the start, or resumes if paused; while it plays, pauses at the current tick."); KeybindRow("Step one frame", _plugin.KeyStep, new KeyboardShortcut((KeyCode)287, Array.Empty()), "Advance exactly one tick while paused."); KeybindRow("Fast forward (hold)", _plugin.KeyFastForward, new KeyboardShortcut((KeyCode)288, Array.Empty()), "Hold to run the script at full speed."); KeybindRow("Quick savestate", _plugin.KeySaveState, new KeyboardShortcut((KeyCode)289, Array.Empty()), "Save the game state into the active slot."); KeybindRow("Quick loadstate", _plugin.KeyLoadState, new KeyboardShortcut((KeyCode)290, Array.Empty()), "Restore the game state from the active slot."); KeybindRow("Start / stop recording", _plugin.KeyRecord, new KeyboardShortcut((KeyCode)291, Array.Empty()), "Start or stop recording your input."); KeybindRow("Stop and release clock", _plugin.KeyStop, new KeyboardShortcut((KeyCode)292, Array.Empty()), "Stop the run and hand the clock back to the game."); KeybindRow("Rewind to tick 0", _plugin.KeyRewind, new KeyboardShortcut((KeyCode)285, Array.Empty()), "Go back to the start of the run."); KeybindRow("Reload script from disk and play", _plugin.KeyReloadPlay, new KeyboardShortcut((KeyCode)284, Array.Empty()), "Read the script file again, then play it from the start. Shows a message if the file is missing."); KeybindRow("Toggle HUD", _plugin.KeyToggleHud, new KeyboardShortcut((KeyCode)293, Array.Empty()), "Show or hide the on-screen info panel."); KeybindRow("Toggle freecam", _plugin.KeyToggleFreecam, new KeyboardShortcut((KeyCode)283, Array.Empty()), "Fly a free camera around the level."); KeybindRow("Cycle camera mode", _plugin.KeyCameraMode, new KeyboardShortcut((KeyCode)282, Array.Empty()), "Switch between first person, third person and freecam."); KeybindRow("Reset camera", _plugin.KeyCameraReset, new KeyboardShortcut((KeyCode)278, Array.Empty()), "Put the camera back behind V1."); KeybindRow("Freecam cursor toggle", _plugin.KeyFreecamCursor, new KeyboardShortcut((KeyCode)308, Array.Empty()), "Free the mouse cursor while the freecam is on."); KeybindRow("Freecam speed up", _plugin.KeyFreecamFaster, new KeyboardShortcut((KeyCode)61, Array.Empty()), "Fly faster."); KeybindRow("Freecam speed down", _plugin.KeyFreecamSlower, new KeyboardShortcut((KeyCode)45, Array.Empty()), "Fly slower."); KeybindRow("Undo last step", _plugin.KeyUndo, new KeyboardShortcut((KeyCode)122, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), "Go back one tick and remove the last step-recorded frame."); EndCard(); BeginCard("Menu injection keys"); Hint("Used by the uppercase field 3 tokens U / D / L / R / C / B (up, down, left, right, confirm, cancel) to drive ULTRAKILL's menus from a script."); KeyCodeRow("Menu up", _plugin.MenuUpKey, (KeyCode)273, "Key pressed for the U token."); KeyCodeRow("Menu down", _plugin.MenuDownKey, (KeyCode)274, "Key pressed for the D token."); KeyCodeRow("Menu left", _plugin.MenuLeftKey, (KeyCode)276, "Key pressed for the L token."); KeyCodeRow("Menu right", _plugin.MenuRightKey, (KeyCode)275, "Key pressed for the R token."); KeyCodeRow("Confirm", _plugin.MenuConfirmKey, (KeyCode)13, "Key pressed for the C token."); KeyCodeRow("Cancel", _plugin.MenuCancelKey, (KeyCode)27, "Key pressed for the B token."); EndCard(); BeginCard("Input injection"); _plugin.InjectDeviceState.Value = Tog(_plugin.InjectDeviceState.Value, "Inject bound keys into the Input System (recommended; blocks physical input)", "Feed the script's keys to the game as if pressed on a keyboard. Your real keys are ignored during a run."); _plugin.EnforceCameraAngles.Value = Tog(_plugin.EnforceCameraAngles.Value, "Enforce camera pitch/yaw before CameraController runs", "Write the scripted look angles right before the game reads them, so aim is exact."); _plugin.BlockGameInputWhileGuiOpen.Value = Tog(_plugin.BlockGameInputWhileGuiOpen.Value, "Block gameplay input while this window is open", "Typing in this window cannot move V1 or turn the view."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("PerformedFrame offset", "Added to the frame counter for one-shot actions. Raise to +1 if jumps or fire clicks do not register.", GUILayout.Width(170f)); if (int.TryParse(Field(_plugin.PerformedFrameOffset.Value.ToString(), "Whole number from -2 to 4.", GUILayout.Width(50f)), out var result)) { _plugin.PerformedFrameOffset.Value = Mathf.Clamp(result, -2, 4); } Hint("(raise to +1 if one-shot actions do not fire)"); GUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(_rebindLabel)) { GUILayout.Label("Waiting for a key for: " + _rebindLabel + " ...", _sectionStyle, Array.Empty()); } EndCard(); } private bool RebindBtn(ConfigEntry entry) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Rect rect = GUILayoutUtility.GetRect(new GUIContent("Rebind"), GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); if (RightClickedRebind(rect)) { entry.Value = KeyboardShortcut.Empty; _plugin.ConfigFile.Save(); if (_rebindEntry == entry) { _rebindEntry = null; _rebindLabel = string.Empty; } return false; } bool result = GUI.Button(rect, "Rebind"); TipAt(rect, "Click, then press the new key. Escape cancels. Right-click to unbind."); return result; } private bool RebindBtn(ConfigEntry entry) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) Rect rect = GUILayoutUtility.GetRect(new GUIContent("Rebind"), GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); if (RightClickedRebind(rect)) { entry.Value = (KeyCode)0; _plugin.ConfigFile.Save(); if (_rebindKeyEntry == entry) { _rebindKeyEntry = null; _rebindLabel = string.Empty; } return false; } bool result = GUI.Button(rect, "Rebind"); TipAt(rect, "Click, then press the new key. Escape cancels. Right-click to unbind."); return result; } private static bool RightClickedRebind(Rect rect) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Event current = Event.current; if (current == null || (int)current.type != 0 || current.button != 1 || !((Rect)(ref rect)).Contains(current.mousePosition)) { return false; } current.Use(); return true; } private void TipAt(Rect rect, string text) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(text) && (int)Event.current.type == 7 && !_shortcutsOpen && (!_tipClipActive || ((Rect)(ref _tipClip)).Contains(_tipWindowMouse)) && ((Rect)(ref rect)).Contains(Event.current.mousePosition)) { _tipText = text; } } private bool RightClickedRow(Rect row) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) Event current = Event.current; if (current == null || (int)current.type != 0 || current.button != 1) { return false; } if (!((Rect)(ref row)).Contains(current.mousePosition) || !((Rect)(ref _tipClip)).Contains(_tipWindowMouse)) { return false; } current.Use(); return true; } private unsafe void KeybindRow(string label, ConfigEntry entry, KeyboardShortcut fallback, string tip) { //IL_0033: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(Array.Empty()); string text = tip + " Right-click to unbind."; Lbl(label, text, GUILayout.Width(220f)); KeyboardShortcut value = entry.Value; bool flag = (int)((KeyboardShortcut)(ref value)).MainKey == 0; object obj; if (_rebindEntry != entry) { if (!flag) { value = entry.Value; obj = ((object)(*(KeyboardShortcut*)(&value))/*cast due to .constrained prefix*/).ToString(); } else { obj = "Unbound"; } } else { obj = "[PRESS KEYBIND]"; } GUILayout.Label((string)obj, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); Tip(text); if (RebindBtn(entry)) { _rebindEntry = entry; _rebindKeyEntry = null; _rebindLabel = label; } if (Btn("Reset", "Go back to the default key.", GUILayout.Width(70f))) { entry.Value = fallback; _plugin.ConfigFile.Save(); } GUILayout.EndHorizontal(); if (RightClickedRow(GUILayoutUtility.GetLastRect())) { entry.Value = KeyboardShortcut.Empty; _plugin.ConfigFile.Save(); if (_rebindEntry == entry) { _rebindEntry = null; _rebindLabel = string.Empty; } } } private void KeyCodeRow(string label, ConfigEntry entry, KeyCode fallback, string tip) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: 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_00cd: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(Array.Empty()); string text = tip + " Right-click to unbind."; Lbl(label, text, GUILayout.Width(220f)); bool flag = (int)entry.Value == 0; GUILayout.Label((_rebindKeyEntry == entry) ? "[PRESS KEYBIND]" : (flag ? "Unbound" : ((object)entry.Value/*cast due to .constrained prefix*/).ToString()), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); Tip(text); if (RebindBtn(entry)) { _rebindKeyEntry = entry; _rebindEntry = null; _rebindLabel = label; } if (Btn("Reset", "Go back to the default key.", GUILayout.Width(70f))) { entry.Value = fallback; _plugin.ConfigFile.Save(); } GUILayout.EndHorizontal(); if (RightClickedRow(GUILayoutUtility.GetLastRect())) { entry.Value = (KeyCode)0; _plugin.ConfigFile.Save(); if (_rebindKeyEntry == entry) { _rebindKeyEntry = null; _rebindLabel = string.Empty; } } } private void HandleRebind() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Invalid comparison between Unknown and I4 //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Invalid comparison between Unknown and I4 //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Invalid comparison between Unknown and I4 //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Invalid comparison between Unknown and I4 //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Invalid comparison between Unknown and I4 //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Invalid comparison between Unknown and I4 //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Invalid comparison between Unknown and I4 //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) if (_rebindEntry == null && _rebindKeyEntry == null) { return; } Event current = Event.current; if (current == null) { return; } KeyCode val; if ((int)current.type == 0 && current.button >= 2 && current.button <= 4) { val = (KeyCode)(325 + current.button - 2); } else { if ((int)current.type != 4) { return; } val = current.keyCode; } if ((int)val == 0) { return; } if ((int)val == 27) { _rebindEntry = null; _rebindKeyEntry = null; _rebindLabel = string.Empty; current.Use(); } else { if ((int)val == 304 || (int)val == 303 || (int)val == 306 || (int)val == 305 || (int)val == 308 || (int)val == 307) { return; } if (_rebindEntry != null) { List list = new List(3); if (current.control) { list.Add((KeyCode)306); } if (current.shift) { list.Add((KeyCode)304); } if (current.alt) { list.Add((KeyCode)308); } _rebindEntry.Value = new KeyboardShortcut(val, list.ToArray()); _plugin.ConfigFile.Save(); } else if (_rebindKeyEntry != null) { _rebindKeyEntry.Value = val; _plugin.ConfigFile.Save(); } _rebindEntry = null; _rebindKeyEntry = null; _rebindLabel = string.Empty; current.Use(); } } private int IntField(int value, int width, string tip = null) { string s = GUILayout.TextField(value.ToString(CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width((float)width) }); Tip(tip); if (!int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return value; } return result; } private void DrawDiagnostics() { //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_010d: 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) BeginCard("Diagnostics"); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Refresh report", "Rebuild the report below from the live game.", GUILayout.Width(120f))) { RequestDiagnostics(log: false); } if (Btn("Write report to log", "Also copy the report into the BepInEx log file.", GUILayout.Width(150f))) { RequestDiagnostics(log: true); } if (Btn("Save report", "Write the report to diagnostics.txt in the script folder.", GUILayout.Width(110f))) { try { string text = Path.Combine(_plugin.ScriptDirectory, "diagnostics.txt"); File.WriteAllText(text, _diagnostics); _statusText = "Report saved to " + text; _statusIsError = false; } catch (Exception ex) { _statusText = ex.Message; _statusIsError = true; } } GUILayout.EndHorizontal(); GUILayout.Space(4f); _diagnosticsScroll = GUILayout.BeginScrollView(_diagnosticsScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(360f) }); GUILayout.Label(_diagnostics, _wrapStyle, Array.Empty()); GUILayout.EndScrollView(); GUILayout.Space(4f); Hint(_cachedInputDescription); Hint(_cachedRngDescription); if (!string.IsNullOrEmpty(_engine.LastError)) { GUILayout.Label("Last engine error: " + _engine.LastError, _errorStyle, Array.Empty()); } StatusLine(); EndCard(); } private void DrawMatrixRow(float x, float y, string caption, MatrixCell[] cells, TasButtons held, Color lit) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) Color color = GUI.color; GUI.color = Color.white; GUI.Label(new Rect(x + 4f, y, 44f, 18f), caption, _panelSmallStyle); float num = x + 46f; for (int i = 0; i < cells.Length; i++) { if (cells[i].GapBefore) { num += 8f; } GUI.color = (((held & cells[i].Mask) != TasButtons.None) ? new Color(lit.r, lit.g, lit.b, _hudAlpha) : new Color(1f, 1f, 1f, 0.35f * _hudAlpha)); GUI.Box(new Rect(num, y, cells[i].Width, 18f), cells[i].Label, _matrixStyle); num += cells[i].Width + 2f; } GUI.color = color; } private void DrawPointerRow(float x, float y, Color lit) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: 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_00aa: 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_00c0: 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_010f: 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_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) Color color = GUI.color; GUI.color = Color.white; GUI.Label(new Rect(x + 4f, y, 44f, 18f), "mouse", _panelSmallStyle); float num = x + 46f; GUI.Label(new Rect(num, y, 210f, 18f), _cachedPointerText, _panelSmallStyle); float num2 = num + 212f; GUI.color = (_input.LiveMouseLeft ? new Color(lit.r, lit.g, lit.b, _hudAlpha) : new Color(1f, 1f, 1f, 0.35f * _hudAlpha)); GUI.Box(new Rect(num2, y, 30f, 18f), "LMB", _matrixStyle); float num3 = num2 + 32f; GUI.color = (_input.LiveMouseRight ? new Color(lit.r, lit.g, lit.b, _hudAlpha) : new Color(1f, 1f, 1f, 0.35f * _hudAlpha)); GUI.Box(new Rect(num3, y, 30f, 18f), "RMB", _matrixStyle); float num4 = num3 + 32f; GUI.color = (_input.LiveMouseMiddle ? new Color(lit.r, lit.g, lit.b, _hudAlpha) : new Color(1f, 1f, 1f, 0.35f * _hudAlpha)); GUI.Box(new Rect(num4, y, 30f, 18f), "MMB", _matrixStyle); GUI.color = color; } private static string[] Sc(string keys, string action) { return new string[2] { keys, action }; } private void EnsureEditorFont() { if (_editorFontTried) { return; } _editorFontTried = true; try { _editorFont = Font.CreateDynamicFontFromOSFont(new string[3] { "Consolas", "Lucida Console", "Courier New" }, 14); } catch (Exception ex) { _plugin.LogWarning("Script editor: could not create a monospace font (" + ex.Message + ")."); } } private void InitialiseEditor() { _editorInitialised = true; string text = ResolveScriptPath(_pathText); if (text == null || !LoadIntoEditor(text, announce: false)) { if (_engine.Script != null) { SetEditorText(_engine.Script.Serialize(), string.IsNullOrEmpty(_engine.ScriptPath) ? _pathText : _engine.ScriptPath); _editorStatus = "Showing the script that is loaded in the tool. Comments are not kept in memory, so none appear here."; _editorStatusError = false; } else { SetEditorText("// New .uktas script. Ctrl+K comments a line, Ctrl+S saves.\nversion 1\nhost_frametime 0.008\nseed 0\nstart_type restart_mission\nframes\n// autofuncs|movement|actions|frametime|yaw|pitch|frames|commands\n----------|------|------|-|0.0|0.0|60|\n----------|f-----|------|-|0.0|0.0|120|\n", _pathText); _editorStatus = "A starter script. Edit it, then press Save."; _editorStatusError = false; } } } private void SetEditorText(string text, string path) { _editor.Buffer.SetText(text); _editor.ErrorLine = -1; _editorPath = path ?? string.Empty; _editorSeenVersion = -1; _editorCheckedVersion = -1; _editor.Focus(); } private bool LoadIntoEditor(string path, bool announce) { try { SetEditorText(File.ReadAllText(path), path); _editorStatus = "Opened " + path + "."; _editorStatusError = false; if (announce) { _plugin.Toast("Opened " + Path.GetFileName(path) + " in the Script Editor.", error: false); } return true; } catch (Exception ex) { _editorStatus = "Could not open " + path + ": " + ex.Message; _editorStatusError = true; return false; } } private void OpenInTextEditor(string path) { string resolved = ResolveScriptPath(path); if (resolved == null) { _editorStatus = "No file found at: " + path; _editorStatusError = true; _tab = 1; return; } _tab = 1; _editorInitialised = true; GuardUnsaved("Open another file?", delegate { LoadIntoEditor(resolved, announce: true); }); } private void GuardUnsaved(string title, Action action) { if (!_editor.Buffer.Modified) { action(); } else { AskConfirm(title, "The text in the Script Editor has changes that were not saved. They will be lost.", "Discard changes", offerSkip: false, action); } } private string EditorSavePath() { return _plugin.ResolveScriptSavePath(_editorPath); } private void SaveEditor() { string path = EditorSavePath(); RequestOverwriteSave(path, delegate { WriteEditorFile(path); }); } private void WriteEditorFile(string path) { try { string directoryName = Path.GetDirectoryName(Path.GetFullPath(path)); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } string text = _editor.Buffer.GetText(Environment.NewLine); string text2 = path + ".tmp"; try { File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); if (File.Exists(path)) { File.Replace(text2, path, null); } else { File.Move(text2, path); } } catch { try { if (File.Exists(text2)) { File.Delete(text2); } } catch { } throw; } _editor.Buffer.MarkSaved(); _editorPath = path; _pathText = path; RememberScriptPath(); _editorStatus = "Saved " + path + ". Press Play (F5) to run it; the tool reloads a changed file by itself."; _editorStatusError = false; _plugin.Toast("Saved " + Path.GetFileName(path) + ".", error: false); } catch (Exception ex) { _editorStatus = "Could not save: " + ex.Message; _editorStatusError = true; _plugin.Toast("Could not save: " + ex.Message, error: true); } } private TasScript CheckEditorText() { _editorCheckedVersion = _editor.Buffer.Version; try { TasScript tasScript = TasScript.Parse(_editor.Buffer.GetText("\n"), _editorPath); _editor.ErrorLine = -1; _editorStatus = "Syntax OK: " + tasScript.Lines.Count + " lines, " + tasScript.TotalTicks + " ticks, " + tasScript.TotalTime.ToString("0.###", CultureInfo.InvariantCulture) + " s" + ((tasScript.Warnings.Count > 0) ? (" (" + tasScript.Warnings.Count + " warning(s): " + tasScript.Warnings[0] + ")") : string.Empty); _editorStatusError = false; return tasScript; } catch (TasParseException ex) { _editor.ErrorLine = ex.LineNumber - 1; _editorStatus = ex.Message; _editorStatusError = true; return null; } catch (Exception ex2) { _editor.ErrorLine = -1; _editorStatus = "Check failed: " + ex2.Message; _editorStatusError = true; return null; } } private void UseEditorInTas() { TasScript tasScript = CheckEditorText(); if (tasScript == null) { _plugin.Toast("Fix the highlighted line first: " + _editorStatus, error: true); return; } string path = EditorSavePath(); _engine.SetScript(tasScript, path); _lastSyncedTick = -1; _plugin.Toast("Script from the editor is loaded (" + tasScript.TotalTicks + " ticks). Press Play to run it.", error: false); if (_editor.Buffer.Modified) { _editorStatus += " Loaded without saving: use Save to keep it on disk."; } } private void NewEditorFile() { GuardUnsaved("Start a new script?", delegate { string scriptDirectory = _plugin.ScriptDirectory; string path = "new_script.uktas"; int num = 1; while (File.Exists(Path.Combine(scriptDirectory, path)) && num < 1000) { int num2 = ++num; path = "new_script_" + num2 + ".uktas"; } SetEditorText("// New .uktas script. Ctrl+K comments a line, Ctrl+S saves.\nversion 1\nhost_frametime 0.008\nseed 0\nstart_type restart_mission\nframes\n// autofuncs|movement|actions|frametime|yaw|pitch|frames|commands\n----------|------|------|-|0.0|0.0|60|\n----------|f-----|------|-|0.0|0.0|120|\n", Path.Combine(scriptDirectory, path)); _editorStatus = "A starter script. Edit it, then press Save."; _editorStatusError = false; }); } private void LoadEngineScriptIntoEditor() { if (_engine.Script == null) { _editorStatus = "No script is loaded in the tool yet."; _editorStatusError = true; return; } GuardUnsaved("Replace the editor text?", delegate { SetEditorText(_engine.Script.Serialize(), string.IsNullOrEmpty(_engine.ScriptPath) ? _editorPath : _engine.ScriptPath); _editorStatus = "Loaded the tool's current script. Comments are not kept in memory, so none appear here."; _editorStatusError = false; }); } private void DrawTextEditorTab() { //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Invalid comparison between Unknown and I4 if (!_editorInitialised) { InitialiseEditor(); } EnsureEditorFont(); _editor.Font = (((Object)(object)_editorFont != (Object)null) ? _editorFont : GameFont()); if (!_editorTabWasActive) { _editorTabWasActive = true; _editor.Focus(); } GUILayout.BeginHorizontal(Array.Empty()); Lbl("File", "The .uktas file this text is saved to. A name without a folder is saved in the script folder.", GUILayout.Width(28f)); _editorPath = Field(_editorPath, "Path of the file being edited.", GUILayout.ExpandWidth(true)); if (Btn("Open", "Load this file into the editor (asks first if you have unsaved changes).", GUILayout.Width(58f))) { OpenInTextEditor(_editorPath); } if (BtnPrimary("Save", "Write the text to the file (Ctrl+S). Asks before overwriting an existing file.", GUILayout.Width(62f))) { SaveEditor(); } if (Btn("New", "Start a fresh script from a small template.", GUILayout.Width(50f))) { NewEditorFile(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Check syntax", "Run the real script parser on the text and mark the first broken line.", GUILayout.Width(100f))) { CheckEditorText(); } if (Btn("Use in TAS", "Load this text into the tool without saving, so Play runs it right away.", GUILayout.Width(90f))) { UseEditorInTas(); } if (Btn("From loaded script", "Replace the text with the script currently loaded in the tool (comments are not kept in memory).", GUILayout.Width(130f))) { LoadEngineScriptIntoEditor(); } GUILayout.FlexibleSpace(); Lbl("Text size", "Editor font size.", GUILayout.Width(62f)); if (Btn("A-", "Smaller text.", GUILayout.Width(30f))) { _editor.FontSize = Mathf.Max(10, _editor.FontSize - 1); } if (Btn("A+", "Larger text.", GUILayout.Width(30f))) { _editor.FontSize = Mathf.Min(24, _editor.FontSize + 1); } if (Btn("Shortcuts", "Show every keyboard shortcut of the editor in a pop-up window.", GUILayout.Width(80f))) { _shortcutsOpen = true; } GUILayout.EndHorizontal(); _editor.Draw(250f); Tip("Type here. Colours: comments grey, numbers amber, header keys cyan, commands blue, |, ; pipes grey."); int prompt = _prompt; if (prompt != 0) { DrawEditorPrompt(prompt); } if (_editor.SaveRequested) { _editor.SaveRequested = false; SaveEditor(); } if ((int)Event.current.type == 7) { UktasTextBuffer buffer = _editor.Buffer; float realTime = TimeController.RealTime; if (buffer.Version != _editorSeenVersion) { _editorSeenVersion = buffer.Version; _editorChangeTime = realTime; } else if (_editorCheckedVersion != buffer.Version && realTime - _editorChangeTime > 0.9f && buffer.LineCount <= 30000) { CheckEditorText(); } } GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label(_editor.StatusText(), _statusBarStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUILayout.Label(_editor.Buffer.Modified ? "unsaved changes" : "saved", _editor.Buffer.Modified ? _sectionStyle : _statusBarStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); GUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(_editorStatus)) { GUILayout.Label(_editorStatus, _editorStatusError ? _errorStyle : _hintStyle, Array.Empty()); } Hint("Ctrl+S save Ctrl+K comment Ctrl+Shift+K uncomment Tab / Shift+Tab indent Ctrl+Z undo Ctrl+Y redo Ctrl+A / C / X / V Ctrl+D duplicate line Alt+Up/Down or Ctrl+Shift+Up/Down move line Ctrl+L select line Ctrl+F find Ctrl+G go to line Click Shortcuts for the full list."); Tip("Keyboard shortcuts of the editor. They work while the text area has the keyboard (click into it first)."); if (_editor.FindRequested) { _editor.FindRequested = false; OpenEditorPrompt(1); } if (_editor.GoToRequested) { _editor.GoToRequested = false; OpenEditorPrompt(2); } } private void OpenEditorPrompt(int mode) { UktasTextBuffer buffer = _editor.Buffer; if (mode == 1) { string selectedText = buffer.GetSelectedText(); if (selectedText.Length > 0 && selectedText.Length <= 120 && selectedText.IndexOf('\n') < 0) { _promptText = selectedText; } else if (_prompt != 1) { _promptText = _lastFindText; } } else { _promptText = (buffer.CaretLine + 1).ToString(CultureInfo.InvariantCulture); } _prompt = mode; _promptFocus = true; } private void CloseEditorPrompt() { if (_prompt == 1) { _lastFindText = _promptText; } _prompt = 0; _promptFocus = false; _editor.Focus(); } private void RunEditorFind(bool forward, bool stayOnCurrent) { if (!string.IsNullOrEmpty(_promptText)) { if (_editor.Buffer.Find(_promptText, forward, _findMatchCase, stayOnCurrent)) { _editor.ScrollToCaret(); _editorStatus = "Found \"" + _promptText + "\" at line " + (_editor.Buffer.CaretLine + 1) + "."; _editorStatusError = false; } else { _editorStatus = "Not found: \"" + _promptText + "\"."; _editorStatusError = true; } } } private void RunEditorGoTo() { string[] array = (_promptText ?? string.Empty).Trim().Split(new char[3] { ':', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length == 0 || !int.TryParse(array[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { _editorStatus = "Type a line number (or line:column) to jump to."; _editorStatusError = true; return; } int result2 = 1; if (array.Length > 1) { int.TryParse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out result2); } int lineCount = _editor.Buffer.LineCount; result = Mathf.Clamp(result, 1, lineCount); _editor.Buffer.SetCaret(result - 1, Mathf.Max(1, result2) - 1, extend: false); _editor.ScrollToCaret(); _editorStatus = "Jumped to line " + result + " of " + lineCount + "."; _editorStatusError = false; CloseEditorPrompt(); } private void DrawEditorPrompt(int mode) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Invalid comparison between Unknown and I4 //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Invalid comparison between Unknown and I4 //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Invalid comparison between Unknown and I4 Event current = Event.current; if (GUI.GetNameOfFocusedControl() == "UktasEditorPrompt" && (int)current.type == 4) { if ((int)current.keyCode == 27) { current.Use(); CloseEditorPrompt(); } else if ((int)current.keyCode == 13 || (int)current.keyCode == 271) { bool shift = current.shift; current.Use(); if (mode == 1) { RunEditorFind(!shift, stayOnCurrent: false); } else { RunEditorGoTo(); } } } GUILayout.BeginHorizontal(Array.Empty()); if (mode == 1) { Lbl("Find", "Text to look for in the file.", GUILayout.Width(34f)); GUI.SetNextControlName("UktasEditorPrompt"); string text = Field(_promptText, "Type the text; Enter = next match, Shift+Enter = previous, Esc = close.", GUILayout.ExpandWidth(true)); if (text != _promptText) { _promptText = text; RunEditorFind(forward: true, stayOnCurrent: true); } if (Btn("Prev", "Previous match (Shift+Enter).", GUILayout.Width(52f))) { RunEditorFind(forward: false, stayOnCurrent: false); } if (BtnPrimary("Next", "Next match (Enter).", GUILayout.Width(52f))) { RunEditorFind(forward: true, stayOnCurrent: false); } _findMatchCase = Tog(_findMatchCase, "Match case", "Only match the same upper / lower case.", GUILayout.Width(110f)); } else { Lbl("Go to line", "Line number to jump to, or line:column.", GUILayout.Width(66f)); GUI.SetNextControlName("UktasEditorPrompt"); _promptText = Field(_promptText, "Line number (or line:column), then Enter.", GUILayout.Width(120f)); if (BtnPrimary("Go", "Jump to that line (Enter).", GUILayout.Width(52f))) { RunEditorGoTo(); } GUILayout.FlexibleSpace(); } if (Btn("Close", "Close this bar (Esc) and return to the text.", GUILayout.Width(58f))) { CloseEditorPrompt(); } GUILayout.EndHorizontal(); if (_promptFocus && (int)current.type == 7) { _promptFocus = false; GUI.FocusControl("UktasEditorPrompt"); } } private void CloseShortcuts() { _shortcutsOpen = false; _editor.Focus(); } private void EnsureShortcutStyles() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0074: 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_00b7: Expected O, but got Unknown if (_shortcutTitleStyle == null) { _shortcutTitleStyle = new GUIStyle(_sectionStyle); _shortcutTitleStyle.fontSize = 14; _shortcutTitleStyle.margin = new RectOffset(0, 0, 0, 0); _shortcutKeyStyle = new GUIStyle(GUI.skin.label); _shortcutKeyStyle.fontStyle = (FontStyle)1; _shortcutKeyStyle.fontSize = 12; _shortcutKeyStyle.normal.textColor = ColAccentHover; _shortcutKeyStyle.wordWrap = false; _shortcutKeyStyle.clipping = (TextClipping)1; _shortcutKeyStyle.alignment = (TextAnchor)3; _shortcutTextStyle = new GUIStyle(GUI.skin.label); _shortcutTextStyle.fontSize = 12; _shortcutTextStyle.wordWrap = false; _shortcutTextStyle.clipping = (TextClipping)1; _shortcutTextStyle.alignment = (TextAnchor)3; } } private void DrawShortcutsPopup() { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Invalid comparison between Unknown and I4 //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Invalid comparison between Unknown and I4 //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0187: 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_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_0289: 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_029f: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_031c: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Unknown result type (might be due to invalid IL or missing references) //IL_0404: Unknown result type (might be due to invalid IL or missing references) //IL_0440: Unknown result type (might be due to invalid IL or missing references) //IL_03c7: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) EnsureShortcutStyles(); Event current = Event.current; float width = ((Rect)(ref _windowRect)).width; float height = ((Rect)(ref _windowRect)).height; float num = Mathf.Min(680f, width - 60f); float num2 = Mathf.Min(580f, height - 80f); Rect val = default(Rect); ((Rect)(ref val))..ctor(Mathf.Floor((width - num) * 0.5f), Mathf.Max(44f, Mathf.Floor((height - num2) * 0.5f)), num, num2); if ((int)current.type == 4 && (int)current.keyCode == 27) { current.Use(); CloseShortcuts(); return; } if ((int)current.type == 0 && !((Rect)(ref val)).Contains(current.mousePosition)) { current.Use(); CloseShortcuts(); return; } if ((int)current.type == 7) { Color color = GUI.color; GUI.color = new Color(0f, 0f, 0f, 0.66f); GUI.DrawTexture(new Rect(0f, 0f, width, height), (Texture)(object)Texture2D.whiteTexture); GUI.color = color; } GUI.Box(val, GUIContent.none, _cardStyle); GUI.Label(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 12f, ((Rect)(ref val)).width - 140f, 22f), "SCRIPT EDITOR SHORTCUTS", _shortcutTitleStyle); if (GUI.Button(new Rect(((Rect)(ref val)).xMax - 18f - 84f, ((Rect)(ref val)).y + 10f, 84f, 26f), "Close")) { CloseShortcuts(); return; } GUI.Label(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 38f, ((Rect)(ref val)).width - 36f, 20f), "They work while the text area has the keyboard. Click outside this window or press Esc to close.", _hintStyle); Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 66f, ((Rect)(ref val)).width - 36f, ((Rect)(ref val)).height - 66f - 14f); float num3 = 24f; for (int i = 0; i < ShortcutGroups.Length; i++) { num3 += 30f + (float)ShortcutGroups[i].Rows.Length * 24f + 6f; } float num4 = ((Rect)(ref val2)).width - 18f; float num5 = Mathf.Min(230f, num4 * 0.36f); _shortcutScroll = GUI.BeginScrollView(val2, _shortcutScroll, new Rect(0f, 0f, num4, num3)); float num6 = 0f; GUI.Label(new Rect(8f, num6, num5, 20f), "Shortcut", _hintStyle); GUI.Label(new Rect(8f + num5 + 8f, num6, num4 - num5 - 16f, 20f), "Action", _hintStyle); num6 += 24f; Color color2 = GUI.color; for (int j = 0; j < ShortcutGroups.Length; j++) { ShortcutGroup shortcutGroup = ShortcutGroups[j]; GUI.Label(new Rect(4f, num6 + 6f, num4 - 8f, 20f), shortcutGroup.Name.ToUpperInvariant(), _sectionStyle); GUI.color = Color.white; GUI.DrawTexture(new Rect(0f, num6 + 30f - 3f, num4, 1f), (Texture)(object)_texSep); num6 += 30f; for (int k = 0; k < shortcutGroup.Rows.Length; k++) { if ((k & 1) == 1) { GUI.color = new Color(1f, 1f, 1f, 0.5f); GUI.DrawTexture(new Rect(0f, num6, num4, 24f), (Texture)(object)_texSep); GUI.color = color2; } GUI.Label(new Rect(8f, num6, num5, 24f), shortcutGroup.Rows[k][0], _shortcutKeyStyle); GUI.Label(new Rect(8f + num5 + 8f, num6, num4 - num5 - 16f, 24f), shortcutGroup.Rows[k][1], _shortcutTextStyle); num6 += 24f; } num6 += 6f; } GUI.color = color2; GUI.EndScrollView(); } private void RefreshHitboxOverlay() { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0098: 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_00b2: Unknown result type (might be due to invalid IL or missing references) if (_engine != null && _engine.RenderSuppressed) { return; } bool value = _plugin.ShowHitboxes.Value; bool value2 = _plugin.ShowPlayerHitbox.Value; if (!value && !value2) { _hitboxes.Clear(); } else if (Time.frameCount - _hitboxScanFrame >= 20) { _hitboxScanFrame = Time.frameCount; _hitboxes.Clear(); if (!_bridge.TryGetCameraTransform(out var transform)) { transform = null; } Vector3 origin = (((Object)(object)transform != (Object)null) ? transform.position : Vector3.zero); HashSet seen = new HashSet(); if (value2) { ScanPlayerHitbox(seen, origin); } if (value) { ScanEnemyHitboxes(seen, origin); } } } private void ScanPlayerHitbox(HashSet seen, Vector3 origin) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) Component playerComponent = _bridge.PlayerComponent; if ((Object)(object)playerComponent == (Object)null) { return; } object member = _bridge.GetMember(playerComponent, new string[1] { "playerCollider" }); Collider val = (Collider)((member is Collider) ? member : null); if ((Object)(object)val != (Object)null && val.enabled && ((Component)val).gameObject.activeInHierarchy) { if (seen.Add(((Object)val).GetInstanceID()) && _hitboxes.Count < 512) { _hitboxes.Add(new HitboxMarker { Collider = val, IsPlayer = true }); } return; } Collider[] componentsInChildren; try { componentsInChildren = playerComponent.GetComponentsInChildren(true); } catch { return; } int count = _hitboxes.Count; AddHitboxColliders(componentsInChildren, seen, origin, isPlayer: true, includeTriggers: false); if (_hitboxes.Count == count) { AddHitboxColliders(componentsInChildren, seen, origin, isPlayer: true, includeTriggers: true); } } private void ScanEnemyHitboxes(HashSet seen, Vector3 origin) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) Type type = _bridge.FindType("EnemyIdentifier"); if (type == null) { return; } Object[] array; try { array = Object.FindObjectsOfType(type, false); } catch { return; } foreach (Object obj2 in array) { Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if ((Object)(object)val == (Object)null) { continue; } AddHitboxColliders(val, seen, origin, isPlayer: false, includeTriggers: true); if (!(_bridge.GetMember(val, new string[1] { "limbs" }) is Array array2)) { continue; } for (int j = 0; j < array2.Length; j++) { object? value = array2.GetValue(j); Component val2 = (Component)((value is Component) ? value : null); if ((Object)(object)val2 != (Object)null) { AddHitboxColliders(val2, seen, origin, isPlayer: false, includeTriggers: true); } } } } private void AddHitboxColliders(Component owner, HashSet seen, Vector3 origin, bool isPlayer, bool includeTriggers) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)owner == (Object)null)) { Collider[] componentsInChildren; try { componentsInChildren = owner.GetComponentsInChildren(true); } catch { return; } AddHitboxColliders(componentsInChildren, seen, origin, isPlayer, includeTriggers); } } private void AddHitboxColliders(Collider[] colliders, HashSet seen, Vector3 origin, bool isPlayer, bool includeTriggers) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0056: 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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) foreach (Collider val in colliders) { if ((Object)(object)val == (Object)null || !val.enabled || !((Component)val).gameObject.activeInHierarchy || (!includeTriggers && val.isTrigger) || !seen.Add(((Object)val).GetInstanceID())) { continue; } if (!isPlayer) { Bounds bounds = val.bounds; Vector3 val2 = ((Bounds)(ref bounds)).center - origin; if (((Vector3)(ref val2)).sqrMagnitude > 22500f) { continue; } } if (_hitboxes.Count >= 512) { break; } _hitboxes.Add(new HitboxMarker { Collider = val, IsPlayer = isPlayer }); } } private void ResetHitboxes() { _hitboxes.Clear(); _hitboxScanFrame = -1000; } private void DrawHitboxOverlay() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0196: 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_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) if ((_engine != null && _engine.RenderSuppressed) || (!_plugin.ShowHitboxes.Value && !_plugin.ShowPlayerHitbox.Value) || _hitboxes.Count == 0 || (int)Event.current.type != 7) { return; } Camera val = _overlayCamera; if ((Object)(object)val == (Object)null) { if (_bridge.TryGetCameraTransform(out var transform) && (Object)(object)transform != (Object)null) { val = ((Component)transform).GetComponent(); if ((Object)(object)val == (Object)null) { val = ((Component)transform).GetComponentInChildren(); } } if ((Object)(object)val == (Object)null) { val = Camera.main; } _overlayCamera = val; } if ((Object)(object)val == (Object)null || !((Behaviour)val).isActiveAndEnabled || !EnsureLineMaterial()) { return; } float num = Screen.width; float num2 = Screen.height; Color val2 = default(Color); ((Color)(ref val2))..ctor(1f, 0.22f, 0.22f, 0.9f); Color val3 = default(Color); ((Color)(ref val3))..ctor(0.25f, 1f, 0.45f, 0.95f); GL.PushMatrix(); _lineMaterial.SetPass(0); GL.LoadPixelMatrix(); GL.Begin(1); Vector3 world = default(Vector3); for (int i = 0; i < _hitboxes.Count; i++) { HitboxMarker hitboxMarker = _hitboxes[i]; Collider collider = hitboxMarker.Collider; if ((Object)(object)collider == (Object)null || !collider.enabled || !((Component)collider).gameObject.activeInHierarchy) { continue; } GL.Color(hitboxMarker.IsPlayer ? val3 : val2); Bounds bounds = collider.bounds; Vector3 min = ((Bounds)(ref bounds)).min; Vector3 max = ((Bounds)(ref bounds)).max; for (int j = 0; j < 8; j++) { ((Vector3)(ref world))..ctor(((j & 1) != 0) ? max.x : min.x, ((j & 2) != 0) ? max.y : min.y, ((j & 4) != 0) ? max.z : min.z); _hitboxCorners[j] = ToViewport(val, world); } for (int k = 0; k < BoxEdges.Length; k += 2) { Vector3 val4 = _hitboxCorners[BoxEdges[k]]; Vector3 val5 = _hitboxCorners[BoxEdges[k + 1]]; if (!(val4.z <= 0f) && !(val5.z <= 0f)) { GL.Vertex3(val4.x * num, val4.y * num2, 0f); GL.Vertex3(val5.x * num, val5.y * num2, 0f); } } } GL.End(); GL.PopMatrix(); } private static Color ParseColor(string hex, Color fallback) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(hex)) { return fallback; } Color result = default(Color); if (!ColorUtility.TryParseHtmlString(hex.Trim(), ref result)) { return fallback; } return result; } private static Color CachedColor(ref string source, ref Color cached, string current, Color fallback) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!string.Equals(source, current, StringComparison.Ordinal)) { source = current; cached = ParseColor(current, fallback); } return cached; } public void OnSceneChanged() { _noFontSearchUntil = TimeController.RealTime + 15f; ResetViewmodels(); ResetHitboxes(); } private Font GameFont() { if ((Object)(object)_gameFont != (Object)null) { return _gameFont; } if (TimeController.RealTime >= _nextFontTry) { _fontTries++; _nextFontTry = Math.Max(TimeController.RealTime + ((_fontTries < 3) ? 5f : 60f), _noFontSearchUntil); _gameFont = FindGameFont(); if ((Object)(object)_gameFont != (Object)null) { _plugin.LogInfo("HUD font: using '" + ((Object)_gameFont).name + "'."); } else if (_fontTries == 1) { LogFontCandidates(); } } if ((Object)(object)_gameFont != (Object)null) { return _gameFont; } if ((Object)(object)_fallbackFont == (Object)null) { try { _fallbackFont = Font.CreateDynamicFontFromOSFont(new string[3] { "Consolas", "Lucida Console", "Courier New" }, 16); } catch { } } return _fallbackFont; } private Font FindGameFont() { try { Type type = _bridge.FindType("TMP_FontAsset"); if (type != null) { Object[] array = Resources.FindObjectsOfTypeAll(type); for (int i = 0; i < array.Length; i++) { if (array[i].name.IndexOf("vcr", StringComparison.OrdinalIgnoreCase) >= 0) { object member = _bridge.GetMember(array[i], new string[3] { "sourceFontFile", "m_SourceFontFile_EditorRef", "m_SourceFontFile" }); Font val = (Font)((member is Font) ? member : null); if ((Object)(object)val != (Object)null) { return val; } } } } Font[] array2 = Resources.FindObjectsOfTypeAll(); for (int j = 0; j < array2.Length; j++) { if (((Object)array2[j]).name.IndexOf("vcr", StringComparison.OrdinalIgnoreCase) >= 0) { return array2[j]; } } } catch (Exception ex) { _plugin.LogWarning("HUD font search failed: " + ex.Message); } return null; } private void LogFontCandidates() { try { Font[] array = Resources.FindObjectsOfTypeAll(); string text = string.Empty; for (int i = 0; i < array.Length && i < 20; i++) { text = text + ((i > 0) ? ", " : string.Empty) + ((Object)array[i]).name; } _plugin.LogInfo("HUD font: the game font was not found yet (fonts loaded: " + ((text.Length == 0) ? "none" : text) + "). Retrying; a system font is used meanwhile."); } catch { } } private void EnsureHudStyles() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Expected O, but got Unknown if (!((Object)(object)GUI.skin == (Object)(object)_hudStylesSkin) || _toastStyle == null) { _hudStylesSkin = GUI.skin; _panelStyle = new GUIStyle(_hudStyle); _panelTitleStyle = new GUIStyle(_hudTitleStyle); _panelSmallStyle = new GUIStyle(_smallStyle); _panelSmallStyle.wordWrap = false; _panelStyle.clipping = (TextClipping)0; _panelStyle.alignment = (TextAnchor)3; _panelStyle.wordWrap = false; _panelTitleStyle.clipping = (TextClipping)0; _panelTitleStyle.alignment = (TextAnchor)3; _panelTitleStyle.wordWrap = false; _panelSmallStyle.clipping = (TextClipping)0; _panelSmallStyle.alignment = (TextAnchor)3; _toastStyle = new GUIStyle(GUI.skin.label); _toastStyle.fontSize = 12; _toastStyle.wordWrap = true; _toastStyle.richText = false; _toastStyle.alignment = (TextAnchor)0; _speedoStyle = new GUIStyle(GUI.skin.label); _speedoStyle.alignment = (TextAnchor)4; _speedoStyle.wordWrap = false; _speedoStyle.richText = false; _speedoStyle.clipping = (TextClipping)0; _speedoSubStyle = new GUIStyle(_speedoStyle); } } private string LevelTimerText() { if (!_bridge.TryGetLevelTime(out var seconds)) { return "n/a"; } return seconds.ToString("0.000", CultureInfo.InvariantCulture) + "s"; } private void UpdateFps() { long timestamp = Stopwatch.GetTimestamp(); if (_fpsStamp != 0L) { double num = (double)(timestamp - _fpsStamp) / (double)Stopwatch.Frequency; if (num > 1E-05 && num < 1.0) { float num2 = (float)(1.0 / num); _fpsSmoothed = ((_fpsSmoothed <= 0f) ? num2 : Mathf.Lerp(_fpsSmoothed, num2, 0.05f)); } } _fpsStamp = timestamp; } private void UpdateRate() { long timestamp = Stopwatch.GetTimestamp(); if (_rateStamp == 0L) { _rateStamp = timestamp; _rateTick = _engine.CurrentTick; _rateGameTime = _engine.CurrentTime; return; } double num = (double)(timestamp - _rateStamp) / (double)Stopwatch.Frequency; if (!(num < 1.0)) { double num2 = _engine.CurrentTime - _rateGameTime; double num3 = _engine.CurrentTick - _rateTick; _rateText = (num2 / num).ToString("0.000", CultureInfo.InvariantCulture) + " game s per real s, " + (num3 / num).ToString("0.0", CultureInfo.InvariantCulture) + " ticks/s"; _rateStamp = timestamp; _rateTick = _engine.CurrentTick; _rateGameTime = _engine.CurrentTime; } } private void LogPlayerLookup() { Type newMovementType = _bridge.NewMovementType; Object val = ((newMovementType != null) ? Object.FindObjectOfType(newMovementType) : null); _plugin.LogInfo("Player lookup: " + (_hasPlayer ? "found" : "NOT found") + " type: " + ((newMovementType != null) ? (newMovementType.FullName + " (" + newMovementType.Assembly.GetName().Name + ")") : "null") + " FindObjectOfType: " + ((val != (Object)null) ? val.name : "null") + " scene: " + _bridge.SceneName + " bridge error: " + (_bridge.LastError ?? "none")); } private void UpdateWeaponPreview() { int num = 0; if (_input != null && _engine != null && _engine.Mode == EngineMode.Paused && !OwnsEscape) { num = _input.ReadHeldSlotRaw(); } if (num != _weaponPreviewSlot) { _weaponPreviewSlot = num; if (_cachedHudLines.Count > 0) { BuildHudCache(); } } } public void UpdateSpeed() { //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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) if (_plugin == null || _bridge == null) { return; } UpdateFps(); UpdateRate(); _hasPlayer = _bridge.NewMovement != null; if (!_playerLogged || _hasPlayer != _lastHasPlayer) { _playerLogged = true; _lastHasPlayer = _hasPlayer; LogPlayerLookup(); } UpdateWeaponPreview(); Rigidbody playerRigidbody = _bridge.PlayerRigidbody; if ((Object)(object)playerRigidbody == (Object)null) { _playerNote = (_hasPlayer ? "player found, Rigidbody missing" : "NewMovement not found"); _hasPlayerData = false; _velocity = Vector3.zero; _speedText = string.Empty; _speedKey = int.MinValue; return; } _hasPlayerData = true; _velocity = playerRigidbody.velocity; _playerNote = "rigidbody ok"; float num = Mathf.Sqrt(_velocity.x * _velocity.x + _velocity.z * _velocity.z); if (_engine != null && _engine.CurrentTick < _lastTickSeen) { _peakSpeed = 0f; } _lastTickSeen = ((_engine != null) ? _engine.CurrentTick : 0); if (num > _peakSpeed) { _peakSpeed = num; } string text = (_plugin.SpeedoMode.Value ?? "horizontal").Trim().ToLowerInvariant(); float num2 = (_speedValue = ((text == "total") ? ((Vector3)(ref _velocity)).magnitude : ((!(text == "vertical")) ? num : _velocity.y))); float realTime = TimeController.RealTime; if (realTime >= _speedNextSample) { float num3 = num2 - _speedSampleBase; _speedTrend = ((num3 > 0.3f) ? 1 : ((num3 < -0.3f) ? (-1) : 0)); _speedSampleBase = num2; _speedNextSample = realTime + 0.1f; } int num4 = Mathf.Clamp(_plugin.SpeedoDecimals.Value, 0, 3); float num5 = num4 switch { 2 => 100f, 1 => 10f, 0 => 1f, _ => 1000f, }; int num6 = Mathf.RoundToInt(num2 * num5) * 4 + num4 + (_plugin.SpeedoUnit.Value ? 1048576 : 0); if (num6 != _speedKey) { _speedKey = num6; _speedText = ((float)Mathf.RoundToInt(num2 * num5) / num5).ToString(DecimalFormats[num4], CultureInfo.InvariantCulture) + (_plugin.SpeedoUnit.Value ? " u/s" : string.Empty); } bool flag = _plugin.SpeedoShowVertical.Value && text != "vertical"; bool value = _plugin.SpeedoShowPeak.Value; if (!flag && !value) { _speedSecondary = string.Empty; _secondaryKey = int.MinValue; return; } int num7 = (flag ? Mathf.RoundToInt(_velocity.y * 10f) : 0) * 7919 + (value ? Mathf.RoundToInt(_peakSpeed * 10f) : 0) + (flag ? 1 : 0) + (value ? 2 : 0); if (num7 != _secondaryKey) { _secondaryKey = num7; string text2 = string.Empty; if (flag) { text2 = "vert " + _velocity.y.ToString("+0.0;-0.0;0.0", CultureInfo.InvariantCulture); } if (value) { text2 = text2 + ((text2.Length > 0) ? " " : string.Empty) + "peak " + _peakSpeed.ToString("0.0", CultureInfo.InvariantCulture); } _speedSecondary = text2; } } private void DrawSpeedometer() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Invalid comparison between Unknown and I4 //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: 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) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0209: 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_0215: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) if (!_plugin.SpeedoEnabled.Value || _plugin.CleanRecordingActive || !_hasPlayerData || _speedText.Length == 0 || (int)Event.current.type != 7) { return; } EnsureHudStyles(); float num = Mathf.Clamp(_plugin.SpeedoSize.Value, 12, 160); float num2 = Mathf.Clamp(_plugin.SpeedoOpacity.Value, 0.1f, 1f); Color val = CachedColor(ref _speedoColorSource, ref _speedoColor, _plugin.SpeedoColor.Value, Color.white); if (_plugin.SpeedoColorByChange.Value) { if (_speedTrend > 0) { ((Color)(ref val))..ctor(0.35f, 1f, 0.45f, val.a); } else if (_speedTrend < 0) { ((Color)(ref val))..ctor(1f, 0.38f, 0.32f, val.a); } } val.a *= num2; float num3 = (float)Screen.width * 0.5f + (float)_plugin.SpeedoOffsetX.Value; float num4 = (float)Screen.height * 0.5f + (float)_plugin.SpeedoOffsetY.Value; if (!DrawGameFontText(num3, num4, _speedText, num, val, _plugin.SpeedoShadow.Value)) { _speedoStyle.font = GameFont(); _speedoStyle.fontSize = Mathf.RoundToInt(num); Rect rect = default(Rect); ((Rect)(ref rect))..ctor(num3 - 400f, num4 - num * 0.7f, 800f, num * 1.4f); DrawOutlined(rect, _speedText, _speedoStyle, val, num2, num); } if (_speedSecondary.Length > 0) { float num5 = Mathf.Max(10f, (float)Mathf.RoundToInt(num * 0.42f)); Color color = default(Color); ((Color)(ref color))..ctor(val.r, val.g, val.b, val.a * 0.85f); if (!DrawGameFontText(num3, num4 + num * 0.55f + num5 * 0.75f, _speedSecondary, num5, color, _plugin.SpeedoShadow.Value)) { _speedoSubStyle.font = GameFont(); _speedoSubStyle.fontSize = Mathf.RoundToInt(num5); Rect rect2 = default(Rect); ((Rect)(ref rect2))..ctor(num3 - 400f, num4 + num * 0.55f, 800f, num5 * 1.5f); DrawOutlined(rect2, _speedSecondary, _speedoSubStyle, color, num2, num5); } } } private void DrawOutlined(Rect rect, string text, GUIStyle style, Color color, float alpha, float size) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) Color color2 = GUI.color; if (_plugin.SpeedoShadow.Value) { float num = Mathf.Max(1.5f, size * 0.055f); style.normal.textColor = new Color(0f, 0f, 0f, 0.9f * alpha); GUI.Label(new Rect(((Rect)(ref rect)).x + num, ((Rect)(ref rect)).y + num, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height), text, style); GUI.Label(new Rect(((Rect)(ref rect)).x - num, ((Rect)(ref rect)).y + num, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height), text, style); GUI.Label(new Rect(((Rect)(ref rect)).x + num, ((Rect)(ref rect)).y - num, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height), text, style); GUI.Label(new Rect(((Rect)(ref rect)).x - num, ((Rect)(ref rect)).y - num, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height), text, style); } style.normal.textColor = color; GUI.Label(rect, text, style); GUI.color = color2; } private static string Num(float value) { return value.ToString("0.00", CultureInfo.InvariantCulture); } private static string NumYaw(float value) { float num = value % 360f; if (num < 0f) { num += 360f; } if (num == 0f) { num = 0f; } return num.ToString("0.00", CultureInfo.InvariantCulture); } private void BuildHudCache() { //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_026d: 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_0290: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_075e: Unknown result type (might be due to invalid IL or missing references) //IL_0775: Unknown result type (might be due to invalid IL or missing references) //IL_078c: Unknown result type (might be due to invalid IL or missing references) //IL_083c: Unknown result type (might be due to invalid IL or missing references) //IL_0841: Unknown result type (might be due to invalid IL or missing references) //IL_0d33: Unknown result type (might be due to invalid IL or missing references) //IL_0d4a: Unknown result type (might be due to invalid IL or missing references) //IL_0d61: Unknown result type (might be due to invalid IL or missing references) _cachedHudLines.Clear(); _hudLinesVersion++; _cachedHudError = _engine.LastError ?? string.Empty; if (_engine.NoRefreshActive) { _cachedHudLines.Add("[NOREFRESH FAST-FORWARDING...] tick " + _engine.CurrentTick + " / " + _engine.NoRefreshTargetTick + " " + _engine.NoRefreshTicks.ToString(CultureInfo.InvariantCulture) + " ticks in " + _engine.NoRefreshSeconds.ToString("0.00", CultureInfo.InvariantCulture) + "s (" + _engine.NoRefreshTicksPerSecond.ToString("0", CultureInfo.InvariantCulture) + " ticks/s)"); string text = "start"; if (_engine.Script != null) { IList checkpoints = _engine.Script.Checkpoints; for (int i = 0; i < checkpoints.Count && checkpoints[i].Tick <= _engine.CurrentTick; i++) { text = ((checkpoints[i].Label.Length > 0) ? checkpoints[i].Label : "norefresh") + " @" + checkpoints[i].Tick; } } _cachedHudLines.Add("no 3D rendering (" + _engine.SuspendedCameraCount + " camera(s) off) from tick " + _engine.NoRefreshStartTick + " room " + (_bridge.SceneName ?? "?") + " checkpoint " + text + " F5 / F11 aborts"); Vector3 velocity = _velocity; _cachedHudLines.Add("speed " + Num(Mathf.Sqrt(velocity.x * velocity.x + velocity.z * velocity.z)) + " vel " + Num(velocity.x) + " " + Num(velocity.y) + " " + Num(velocity.z) + " hp " + (_bridge.TryGetHealth(out var health, out var _) ? health.ToString("0", CultureInfo.InvariantCulture) : "n/a")); } if (_plugin.HudShowProgress.Value) { _cachedHudLines.Add("ULTRAKILL TAS " + _cachedModeTag + (_engine.FastForward ? " [FF]" : string.Empty) + ((_engine.PlaybackSpeed < 0.999) ? (" " + _engine.PlaybackSpeed.ToString("0.##", CultureInfo.InvariantCulture) + "x") : string.Empty)); _cachedHudLines.Add("tick " + _engine.CurrentTick + "/" + _engine.TotalTicks + " time " + _engine.CurrentTime.ToString("0.000", CultureInfo.InvariantCulture) + "/" + _engine.TotalTime.ToString("0.000", CultureInfo.InvariantCulture) + "s timer " + LevelTimerText()); double val = ((_engine.LastFrametime > 0.0) ? _engine.LastFrametime : _time.HostFrametime); _cachedHudLines.Add("frametime " + val.ToString("0.######", CultureInfo.InvariantCulture) + " (" + (1.0 / Math.Max(1E-06, val)).ToString("0.#", CultureInfo.InvariantCulture) + " tps) render " + _fpsSmoothed.ToString("0", CultureInfo.InvariantCulture) + " fps enemies " + _cachedEnemyCount); _cachedHudLines.Add("timescale " + Time.timeScale.ToString("0.###", CultureInfo.InvariantCulture)); } if (_rateText.Length > 0) { _cachedHudLines.Add("rate " + _rateText); } bool hasPlayerData = _hasPlayerData; bool hasPlayer = _hasPlayer; if (!hasPlayer) { _cachedHudLines.Add("player n/a (" + (_bridge.IsMainMenu ? "title screen" : "no player in this scene") + ")"); } else if (!hasPlayerData) { _cachedHudLines.Add("player: " + _playerNote); } if (hasPlayerData && _plugin.HudShowSpeed.Value) { float value = Mathf.Sqrt(_velocity.x * _velocity.x + _velocity.z * _velocity.z); _cachedHudLines.Add("speed " + Num(value) + " u/s (vert " + _velocity.y.ToString("+0.00;-0.00;0.00", CultureInfo.InvariantCulture) + " total " + Num(((Vector3)(ref _velocity)).magnitude) + ")"); } if (hasPlayerData && _plugin.HudShowVelocity.Value) { _cachedHudLines.Add("vel " + Num(_velocity.x) + " " + Num(_velocity.y) + " " + Num(_velocity.z)); } if (hasPlayer && _plugin.HudShowPosition.Value) { _cachedHudLines.Add(_bridge.TryGetPlayerPosition(out var position) ? ("pos " + Num(position.x) + " " + Num(position.y) + " " + Num(position.z)) : "pos n/a"); } if (hasPlayer && _plugin.HudShowAngles.Value) { _cachedHudLines.Add(_bridge.TryGetCameraAngles(out var pitch, out var yaw) ? ("pitch " + Num(pitch) + " yaw " + NumYaw(yaw)) : "angles n/a"); Camera main = Camera.main; if ((Object)(object)main != (Object)null && _bridge.TryGetPlayerPosition(out var position2) && _bridge.TryGetCameraAngles(out var pitch2, out var yaw2)) { _cachedHudLines.Add(TasOptimizer.FacingText(((Component)main).transform.forward, position2, yaw2, pitch2)); } } if (hasPlayer && _plugin.HudShowVitals.Value) { float health2 = 0f; float hardDamage2 = 0f; float stamina = 0f; bool flag = _bridge.TryGetHealth(out health2, out hardDamage2); bool flag2 = _bridge.TryGetStamina(out stamina); _cachedHudLines.Add("hp " + (flag ? health2.ToString("0", CultureInfo.InvariantCulture) : "n/a") + " hard " + (flag ? hardDamage2.ToString("0", CultureInfo.InvariantCulture) : "n/a") + " dash " + (flag2 ? ((stamina / 100f).ToString("0.0", CultureInfo.InvariantCulture) + " (" + stamina.ToString("0", CultureInfo.InvariantCulture) + ")") : "n/a")); } if (hasPlayer && _plugin.HudShowState.Value) { _bridge.TryGetSlamming(out var slamming); _cachedHudLines.Add(_bridge.TryGetMovementState(out var onGround, out var sliding, out var dashing, out var jumping) ? ("state " + (onGround ? "GROUND" : "AIR") + (sliding ? " SLIDE" : string.Empty) + (dashing ? " DASH" : string.Empty) + (jumping ? " JUMP" : string.Empty) + (slamming ? " SLAM" : string.Empty)) : "state n/a"); } if (hasPlayer && _plugin.HudShowWeapon.Value) { string name = string.Empty; int slot = -1; int variation = -1; bool flag3 = _weaponPreviewSlot > 0 && _engine.Mode == EngineMode.Paused && _bridge.TryPreviewWeaponSlot(_weaponPreviewSlot, out name, out slot, out variation); _cachedHudLines.Add((flag3 || _bridge.TryGetWeapon(out name, out slot, out variation)) ? ("weapon " + ((name.Length > 0) ? name : "none") + " (slot " + slot + ", variation " + variation + ")") : "weapon n/a"); } if (_plugin.HudShowInputs.Value) { _cachedHudLines.Add("input " + TasInputColumns.FormatCompact((_input != null) ? _input.LiveButtons : TasButtons.None)); } if (_engine.FreeLookActive || _engine.Mode == EngineMode.Paused) { _cachedHudLines.Add("STAGED " + TasInputColumns.FormatCompact(_engine.StagedButtons) + " pitch/yaw " + Num(_engine.StagedPitch) + "/" + NumYaw(_engine.StagedYaw)); _cachedHudLines.Add("BULK ----------|" + TasInputColumns.FormatMovement(_engine.StagedButtons) + "|" + TasInputColumns.FormatActions(_engine.StagedButtons) + "|" + _time.HostFrametime.ToString("0.0##########", CultureInfo.InvariantCulture) + "|" + NumYaw(_engine.StagedYaw) + "|" + Num(_engine.StagedPitch) + "|1"); } if (_plugin.HudShowRng.Value) { _cachedHudLines.Add("seed " + _rng.CurrentSeed + " RNG " + (_rng.SystemRandomPatched ? "deterministic" : "unity-only")); } if (_plugin.HudShowLevelStats.Value) { AppendLevelStats(); } if (hasPlayer && _plugin.HudEntityInspector.Value) { AppendEntityInspector(); } if (hasPlayer && _plugin.HudShowHit.Value) { _cachedHudLines.Add(TryCrosshairHit(out var point) ? ("hit " + Num(point.x) + " " + Num(point.y) + " " + Num(point.z)) : "hit none"); } } private static string RankText(string letter) { string text; switch (letter) { case "D": text = "#0094FF"; break; case "C": text = "#4CFF00"; break; case "B": text = "#FFD800"; break; case "A": text = "#FF6A00"; break; case "S": text = "#FF0000"; break; case "P": text = "#FFFFFF"; break; default: return letter; } return "" + letter + ""; } private static string StatsClock(float seconds) { int num = (int)(seconds / 60f); return num.ToString(CultureInfo.InvariantCulture) + ":" + (seconds - (float)num * 60f).ToString("00.000", CultureInfo.InvariantCulture); } private static string NeedForP(string rank, string needed) { if (rank == "S") { return " P ok"; } if (needed.Length <= 0) { return string.Empty; } return " P: " + needed; } private void AppendLevelStats() { if (!_bridge.TryGetLevelStats(out var info)) { _cachedHudLines.Add("kills -- score -- time --"); _cachedHudLines.Add("rank -- challenge --"); return; } _cachedHudLines.Add("kills " + info.Kills.ToString(CultureInfo.InvariantCulture) + " " + RankText(info.KillsRank) + NeedForP(info.KillsRank, (info.KillsForS >= 0) ? info.KillsForS.ToString(CultureInfo.InvariantCulture) : string.Empty)); _cachedHudLines.Add("score " + info.Score.ToString(CultureInfo.InvariantCulture) + " " + RankText(info.ScoreRank) + NeedForP(info.ScoreRank, (info.ScoreForS >= 0) ? info.ScoreForS.ToString(CultureInfo.InvariantCulture) : string.Empty)); _cachedHudLines.Add("time " + StatsClock(info.Seconds) + " " + RankText(info.TimeRank) + NeedForP(info.TimeRank, (info.TimeForS >= 0) ? ("max " + StatsClock(info.TimeForS)) : string.Empty)); string text = ((info.Challenge < 0) ? "--" : ((info.Challenge == 1) ? "YES" : ((info.Challenge == 2) ? "FAILED" : "NO"))); _cachedHudLines.Add("rank " + RankText(info.TotalRank) + (info.EndScreen ? " (final)" : string.Empty) + " restarts " + info.Restarts.ToString(CultureInfo.InvariantCulture) + ((info.Restarts > 0) ? " (no P)" : string.Empty) + " challenge " + text); } private bool TryCrosshairHit(out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) point = Vector3.zero; if (!_bridge.TryGetCameraTransform(out var transform) || (Object)(object)transform == (Object)null) { return false; } Transform playerTransform = _bridge.PlayerTransform; try { int num = Physics.RaycastNonAlloc(transform.position, transform.forward, _crosshairHits, 1000f, -1, (QueryTriggerInteraction)1); float num2 = float.MaxValue; bool result = false; for (int i = 0; i < num && i < _crosshairHits.Length; i++) { Collider collider = ((RaycastHit)(ref _crosshairHits[i])).collider; if (!((Object)(object)collider == (Object)null) && (!((Object)(object)playerTransform != (Object)null) || !((Component)collider).transform.IsChildOf(playerTransform)) && ((RaycastHit)(ref _crosshairHits[i])).distance < num2) { num2 = ((RaycastHit)(ref _crosshairHits[i])).distance; point = ((RaycastHit)(ref _crosshairHits[i])).point; result = true; } } return result; } catch { return false; } } private void CopyHitCoordinate() { if (!TryCrosshairHit(out var point)) { _statusText = "No surface under the crosshair: nothing copied."; _statusIsError = true; _plugin.Toast("Hit: no surface under the crosshair.", error: true); return; } string text = (GUIUtility.systemCopyBuffer = point.x.ToString("0.000", CultureInfo.InvariantCulture) + " " + point.y.ToString("0.000", CultureInfo.InvariantCulture) + " " + point.z.ToString("0.000", CultureInfo.InvariantCulture)); _statusText = "Copied hit coordinate: " + text; _statusIsError = false; _plugin.Toast("Copied hit coordinate: " + text, error: false); } private void AppendEntityInspector() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) if (!_bridge.TryGetCameraTransform(out var transform)) { _cachedHudLines.Add("entity n/a (no camera)"); return; } EntityRegistry entities = _bridge.Entities; float hitDistance; bool occluded; EntityRegistry.Entity entity = entities.Pick(transform.position, transform.forward, 1000f, out hitDistance, out occluded); if (entity == null || !GameBridge.IsAlive(entity.Component)) { _cachedHudLines.Add("entity none in view (" + entities.LevelCount + " level IDs)"); return; } Component component = entity.Component; Vector3 position = component.transform.position; _cachedHudLines.Add("entity " + entity.Id + " " + entity.Category + " " + entity.TypeName + " '" + ((Object)component.gameObject).name + "'" + (entity.Spawned ? " (spawned)" : string.Empty) + (occluded ? " [behind geometry]" : string.Empty)); _cachedHudLines.Add(" pos " + Num(position.x) + " " + Num(position.y) + " " + Num(position.z) + " dist " + Num(Vector3.Distance(transform.position, position)) + " (ray " + Num(hitDistance) + ")"); string text = entities.DescribeState(entity); _cachedHudLines.Add(" " + ((text.Length > 0) ? text : "state n/a")); _cachedHudLines.Add(entities.TryGetVelocity(entity, out var velocity) ? (" vel " + Num(velocity.x) + " " + Num(velocity.y) + " " + Num(velocity.z) + " (" + Num(((Vector3)(ref velocity)).magnitude) + ")") : " vel n/a (no Rigidbody)"); } private void DrawHud() { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: 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_0281: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_03f2: Unknown result type (might be due to invalid IL or missing references) //IL_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_0402: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_0415: Unknown result type (might be due to invalid IL or missing references) //IL_041a: Unknown result type (might be due to invalid IL or missing references) //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_06a4: Unknown result type (might be due to invalid IL or missing references) //IL_06ab: Unknown result type (might be due to invalid IL or missing references) //IL_0647: Unknown result type (might be due to invalid IL or missing references) //IL_0665: Unknown result type (might be due to invalid IL or missing references) //IL_068e: Unknown result type (might be due to invalid IL or missing references) //IL_055d: Unknown result type (might be due to invalid IL or missing references) //IL_0582: Unknown result type (might be due to invalid IL or missing references) //IL_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_04ae: Unknown result type (might be due to invalid IL or missing references) //IL_05f4: Unknown result type (might be due to invalid IL or missing references) //IL_0622: Unknown result type (might be due to invalid IL or missing references) if (_cachedHudLines.Count == 0) { BuildHudCache(); } EnsureHudStyles(); bool value = _plugin.HudShowInputDisplay.Value; bool flag = value && (_engine.Mode == EngineMode.Paused || _engine.FreeLookActive); int num = 0; if (value) { num = 2 + (_plugin.HudShowPointer.Value ? 1 : 0) + (flag ? 2 : 0); } bool flag2 = !string.IsNullOrEmpty(_cachedHudError) && _plugin.HudShowProgress.Value; if (_cachedHudLines.Count == 0 && num == 0 && !flag2) { return; } if (!_loggedHudDraw) { _loggedHudDraw = true; _plugin.LogInfo("HUD drawing with " + _cachedHudLines.Count + " lines."); } Color textColor = CachedColor(ref _hudColorSource, ref _hudColor, _plugin.HudColor.Value, Color.white); textColor.a *= Mathf.Clamp(_plugin.HudOpacity.Value, 0.1f, 1f); Font val = (_plugin.HudGameFont.Value ? GameFont() : null); _panelStyle.font = val; _panelTitleStyle.font = val; _panelSmallStyle.font = val; _matrixStyle.font = val; _panelStyle.normal.textColor = textColor; _panelTitleStyle.normal.textColor = textColor; _panelSmallStyle.normal.textColor = textColor; if (_measuredVersion != _hudLinesVersion || _measuredFont != val) { _measuredVersion = _hudLinesVersion; _measuredFont = val; float num2 = 300f; for (int i = 0; i < _cachedHudLines.Count; i++) { _measureContent.text = _cachedHudLines[i]; float x = ((i == 0) ? _panelTitleStyle : _panelStyle).CalcSize(_measureContent).x; if (x > num2) { num2 = x; } } _measuredTextWidth = num2 + 24f; _measureContent.text = "Ag"; _panelLineHeight = Mathf.Max(16f, Mathf.Ceil(_panelStyle.CalcSize(_measureContent).y) + 2f); } float measuredTextWidth = _measuredTextWidth; float num3 = (value ? Mathf.Max(560f, measuredTextWidth) : measuredTextWidth); float num4 = ((_cachedHudLines.Count > 0) ? (_panelLineHeight * (float)_cachedHudLines.Count + 12f) : 0f); float num5 = num4 + ((num > 0) ? (4f + (float)num * 20f) : 0f) + (flag2 ? 28f : 0f); float num6 = Mathf.Clamp(_plugin.HudScale.Value, 0.5f, 3f); float num7 = Mathf.Clamp(_plugin.HudOpacity.Value, 0.1f, 1f); float num8 = _plugin.HudOffsetX.Value; float num9 = _plugin.HudOffsetY.Value; string text = (_plugin.HudCorner.Value ?? "topleft").Trim().ToLowerInvariant(); float num10 = (text.EndsWith("right", StringComparison.Ordinal) ? ((float)Screen.width - num3 * num6 - num8) : num8); float num11 = (text.StartsWith("bottom", StringComparison.Ordinal) ? ((float)Screen.height - num5 * num6 - num9) : num9); Matrix4x4 matrix = GUI.matrix; Color color = GUI.color; GUI.matrix = Matrix4x4.TRS(new Vector3(num10, num11, 0f), Quaternion.identity, new Vector3(num6, num6, 1f)); _hudAlpha = num7; float num12 = 0f; if (_cachedHudLines.Count > 0) { if (_plugin.HudBackground.Value) { GUI.color = new Color(1f, 1f, 1f, num7); GUI.Box(new Rect(0f, 0f, measuredTextWidth, num4), GUIContent.none); } float num13 = 6f; for (int j = 0; j < _cachedHudLines.Count; j++) { GUI.Label(new Rect(8f, num13, measuredTextWidth - 12f, _panelLineHeight), _cachedHudLines[j], (j == 0) ? _panelTitleStyle : _panelStyle); num13 += _panelLineHeight; } num12 = num4 + 4f; } if (num > 0) { TasButtons tasButtons = _input.LiveButtons; if (_engine.Mode == EngineMode.Playing) { tasButtons |= _engine.LastButtons; } Color lit = default(Color); ((Color)(ref lit))..ctor(0.35f, 1f, 0.55f); DrawMatrixRow(0f, num12, "now", RowMove, tasButtons, lit); num12 += 20f; DrawMatrixRow(0f, num12, "now", RowWeapons, tasButtons, lit); num12 += 20f; if (_plugin.HudShowPointer.Value) { DrawPointerRow(0f, num12, lit); num12 += 20f; } if (flag) { Color lit2 = default(Color); ((Color)(ref lit2))..ctor(0.45f, 0.85f, 1f); DrawMatrixRow(0f, num12, "F6", RowMove, _engine.StagedButtons, lit2); num12 += 20f; DrawMatrixRow(0f, num12, "F6", RowWeapons, _engine.StagedButtons, lit2); num12 += 20f; } } if (flag2) { GUI.color = new Color(1f, 1f, 1f, num7); GUI.Box(new Rect(0f, num12 + 2f, num3, 22f), GUIContent.none); GUI.Label(new Rect(6f, num12 + 4f, num3 - 12f, 20f), _cachedHudError, _errorStyle); } GUI.matrix = matrix; GUI.color = color; } private void DrawNoRefreshBanner() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Invalid comparison between Unknown and I4 //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) if (_engine.RenderSuppressed && !_plugin.CleanRecordingActive && (int)Event.current.type == 7) { EnsureHudStyles(); if (_noRefreshStyle == null) { _noRefreshStyle = new GUIStyle(GUI.skin.label); _noRefreshStyle.alignment = (TextAnchor)4; } Font font = (_plugin.HudGameFont.Value ? GameFont() : null); _noRefreshStyle.font = font; _noRefreshStyle.fontSize = 16; _noRefreshStyle.normal.textColor = new Color(1f, 0.83f, 0.29f, 1f); string text = "[NOREFRESH FAST-FORWARDING...] tick " + _engine.CurrentTick + " / " + _engine.NoRefreshTargetTick + " " + _engine.NoRefreshTicks.ToString(CultureInfo.InvariantCulture) + " ticks " + _engine.NoRefreshSeconds.ToString("0.00", CultureInfo.InvariantCulture) + "s " + _engine.NoRefreshTicksPerSecond.ToString("0", CultureInfo.InvariantCulture) + " ticks/s (F5 / F11 aborts)"; Color color = GUI.color; GUI.color = new Color(0f, 0f, 0f, 0.75f); GUI.Box(new Rect(0f, 0f, (float)Screen.width, 30f), GUIContent.none); GUI.color = color; GUI.Label(new Rect(0f, 5f, (float)Screen.width, 22f), text, _noRefreshStyle); } } private void DrawToast() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type != 7 || _plugin.CleanRecordingActive) { return; } List messages = _plugin.Messages; if (messages.Count == 0) { return; } EnsureHudStyles(); float realTime = TimeController.RealTime; float num = Mathf.Min(520f, (float)Screen.width * 0.45f); float num2 = (float)Screen.width - num - 16f; float num3 = 16f; int num4 = 0; Color color = GUI.color; int num5 = messages.Count - 1; while (num5 >= 0 && num4 < 5) { TasMessage tasMessage = messages[num5]; float num6 = (tasMessage.IsError ? 8f : 5f); float num7 = realTime - tasMessage.Time; if (!(num7 > num6)) { float num8 = ((num7 > num6 - 1f) ? Mathf.Clamp01(num6 - num7) : 1f); _toastContent.text = tasMessage.Text; float num9 = _toastStyle.CalcHeight(_toastContent, num - 16f) + 10f; Rect val = new Rect(num2, num3, num, num9); GUI.color = (tasMessage.IsError ? new Color(1f, 0.55f, 0.5f, 0.95f * num8) : new Color(1f, 1f, 1f, 0.92f * num8)); GUI.Box(val, GUIContent.none); _toastStyle.normal.textColor = (tasMessage.IsError ? new Color(1f, 0.82f, 0.8f, num8) : new Color(1f, 1f, 1f, num8)); GUI.color = Color.white; GUI.Label(new Rect(num2 + 8f, num3 + 4f, num - 16f, num9 - 6f), tasMessage.Text, _toastStyle); num3 += num9 + 4f; num4++; } num5--; } GUI.color = color; } private static int IndexOf(string[] values, string current) { string text = (current ?? string.Empty).Trim().ToLowerInvariant(); for (int i = 0; i < values.Length; i++) { if (values[i] == text) { return i; } } return 0; } private void SliderRow(string label, ConfigEntry entry, float min, float max, string tip) { GUILayout.BeginHorizontal(Array.Empty()); Lbl(label, tip, GUILayout.Width(150f)); float num = Slide(entry.Value, min, max, tip, GUILayout.Width(220f)); GUILayout.Label(num.ToString("0.00", CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); if (Math.Abs(num - entry.Value) > 0.0001f) { entry.Value = Mathf.Round(num * 100f) / 100f; } } private void IntSliderRow(string label, ConfigEntry entry, int min, int max, string tip) { GUILayout.BeginHorizontal(Array.Empty()); Lbl(label, tip, GUILayout.Width(150f)); int num = Mathf.RoundToInt(Slide(entry.Value, min, max, tip, GUILayout.Width(220f))); GUILayout.Label(num.ToString(CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); if (num != entry.Value) { entry.Value = num; } } private void OffsetRow(string label, ConfigEntry x, ConfigEntry y, string tip) { GUILayout.BeginHorizontal(Array.Empty()); Lbl(label, tip, GUILayout.Width(150f)); GUILayout.Label("X", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(14f) }); x.Value = Mathf.Clamp(IntField(x.Value, 56, tip), -4000, 4000); GUILayout.Label("Y", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(14f) }); y.Value = Mathf.Clamp(IntField(y.Value, 56, tip), -4000, 4000); GUILayout.EndHorizontal(); } private void ColorRow(string label, ConfigEntry entry, string tip) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(Array.Empty()); Lbl(label, tip, GUILayout.Width(150f)); entry.Value = GUILayout.TextField(entry.Value ?? string.Empty, 9, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); Tip(tip); Color color = GUI.color; GUI.color = ParseColor(entry.Value, Color.white); GUILayout.Box(GUIContent.none, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(40f), GUILayout.Height(18f) }); GUI.color = color; Hint("#RRGGBB"); GUILayout.EndHorizontal(); } private void DrawOverlays() { //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_0439: Unknown result type (might be due to invalid IL or missing references) BeginCard("HUD panel"); _plugin.ShowHud.Value = Tog(_plugin.ShowHud.Value, "Show the HUD panel (F12)", "The info panel with tick, speed, position and inputs."); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(400f) }); _plugin.HudShowProgress.Value = Tog(_plugin.HudShowProgress.Value, "Mode, tick, time, frametime, fps", "Playback mode, current tick, elapsed time, tick length and render fps."); _plugin.HudShowSpeed.Value = Tog(_plugin.HudShowSpeed.Value, "Speed (horizontal / vertical / total)", "Player speed in units per second."); _plugin.HudShowVelocity.Value = Tog(_plugin.HudShowVelocity.Value, "Velocity vector (X, Y, Z)", "The three components of the player's velocity."); _plugin.HudShowPosition.Value = Tog(_plugin.HudShowPosition.Value, "Position (X, Y, Z)", "Where the player is in the level."); _plugin.HudShowAngles.Value = Tog(_plugin.HudShowAngles.Value, "Camera pitch / yaw", "Where the camera is looking."); GUILayout.EndVertical(); GUILayout.BeginVertical(Array.Empty()); _plugin.HudShowVitals.Value = Tog(_plugin.HudShowVitals.Value, "Health, hard damage, dash charge", "HP, hard damage and dash charge (stamina bars)."); _plugin.HudShowState.Value = Tog(_plugin.HudShowState.Value, "Ground / slide / dash / jump state", "Whether V1 is grounded, sliding, dashing or jumping."); _plugin.HudShowWeapon.Value = Tog(_plugin.HudShowWeapon.Value, "Equipped weapon", "Current weapon, slot and variation."); _plugin.HudShowInputs.Value = Tog(_plugin.HudShowInputs.Value, "Held buttons as text", "The buttons held this tick, written as text."); _plugin.HudShowRng.Value = Tog(_plugin.HudShowRng.Value, "RNG seed and state", "The random seed and whether randomness is deterministic."); _plugin.HudEntityInspector.Value = Tog(_plugin.HudEntityInspector.Value, "Entity inspector (look_at ID under crosshair)", "Show the ID, type and state of the enemy or object under the crosshair."); _plugin.HudShowHit.Value = Tog(_plugin.HudShowHit.Value, "Surface hit coordinate under crosshair", "Show \"hit x y z\" for the surface the crosshair points at, or \"hit none\"."); _plugin.HudShowLevelStats.Value = Tog(_plugin.HudShowLevelStats.Value, "Level stats (kills, score, time, ranks, challenge)", "Live kills, score and time with their ranks, the total rank and the challenge, plus what each needs for an S (a P rank needs all three S). Shows -- outside a level."); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Copy hit coordinate", "Copy the surface point under the crosshair to the clipboard as \"x y z\" (3 decimals). Shows a message if there is no hit.", GUILayout.Width(170f))) { CopyHitCoordinate(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); EndCard(); BeginCard("Visuals"); _plugin.HideViewmodels.Value = Tog(_plugin.HideViewmodels.Value, "Hide first-person viewmodels (weapons and arms; visual only)", "Do not draw the weapon and arm models in front of the camera. Gameplay is unaffected."); _plugin.ShowHitboxes.Value = Tog(_plugin.ShowHitboxes.Value, "Show enemy hitboxes", "Outline the collision boxes of nearby enemies."); _plugin.ShowPlayerHitbox.Value = Tog(_plugin.ShowPlayerHitbox.Value, "Show local player hitbox (collision bounds)", "Outline V1's own collision shape."); bool freecamActive = _plugin.FreecamActive; bool flag = Tog(freecamActive, "Freecam (" + ((object)_plugin.KeyToggleFreecam.Value/*cast due to .constrained prefix*/).ToString() + "): WASD, Space up, Q down; Shift fast, Ctrl slow", "Fly a free camera around the level without moving V1."); if (flag != freecamActive) { _plugin.SetFreecam(flag); } GUILayout.BeginHorizontal(Array.Empty()); Lbl("Freecam speed", "How fast the freecam flies, in units per second.", GUILayout.Width(150f)); float num = Slide(_plugin.FreecamSpeed.Value, 1f, 100f, "Freecam speed.", GUILayout.Width(180f)); GUILayout.Label(num.ToString("0", CultureInfo.InvariantCulture) + " u/s", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); GUILayout.EndHorizontal(); if (Math.Abs(num - _plugin.FreecamSpeed.Value) > 0.5f) { _plugin.FreecamSpeed.Value = Mathf.Round(num); } _plugin.FreecamShowV1Body.Value = Tog(_plugin.FreecamShowV1Body.Value, "Show V1 playermodel in freecam", "While freecam is on, show V1's full body renderers. Restored when freecam ends."); GUILayout.BeginHorizontal(Array.Empty()); _plugin.ShowTriggers.Value = Tog(_plugin.ShowTriggers.Value, "Show triggers (level trigger / event volumes)", "Outline the level's trigger volumes with their names. Read only.", GUILayout.Width(330f)); Lbl("within", "Only triggers closer than this are drawn.", GUILayout.Width(44f)); float num2 = Slide(_plugin.ShowTriggersDistance.Value, 5f, 500f, "Trigger draw distance.", GUILayout.Width(160f)); GUILayout.Label(num2.ToString("0", CultureInfo.InvariantCulture) + " u", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); if (Math.Abs(num2 - _plugin.ShowTriggersDistance.Value) > 0.5f) { _plugin.ShowTriggersDistance.Value = Mathf.Round(num2); } GUILayout.BeginHorizontal(Array.Empty()); _plugin.ShowTriggersSolid.Value = Tog(_plugin.ShowTriggersSolid.Value, "Solid boxes", "Fill each trigger volume instead of drawing only its outline.", GUILayout.Width(110f)); Lbl("opacity", "How opaque the solid trigger boxes are.", GUILayout.Width(50f)); float num3 = Slide(_plugin.ShowTriggersOpacity.Value, 0.02f, 1f, "Solid trigger box opacity.", GUILayout.Width(160f)); GUILayout.Label(Mathf.RoundToInt(num3 * 100f) + "%", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); GUILayout.EndHorizontal(); if (Math.Abs(num3 - _plugin.ShowTriggersOpacity.Value) > 0.005f) { _plugin.ShowTriggersOpacity.Value = num3; } _plugin.HudShowInputDisplay.Value = Tog(_plugin.HudShowInputDisplay.Value, "Input display (every action lights up while held)", "Rows of key boxes in the HUD that light up when you or the script press something."); _plugin.HudShowPointer.Value = Tog(_plugin.HudShowPointer.Value, "Pointer row (mouse position in pixels and fractions, for menu scripts)", "Shows where the mouse is, ready to copy into mouse / mousef commands."); EndCard(); BeginCard("HUD layout"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Corner", "Which screen corner the info panel is attached to.", GUILayout.Width(150f)); int num4 = IndexOf(CornerValues, _plugin.HudCorner.Value); int num5 = ChoiceRow(num4, CornerLabels, CornerTips, 0f); if (num5 != num4) { _plugin.HudCorner.Value = CornerValues[num5]; } GUILayout.EndHorizontal(); OffsetRow("Offset (px)", _plugin.HudOffsetX, _plugin.HudOffsetY, "Distance from the chosen corner, in pixels."); SliderRow("Scale", _plugin.HudScale, 0.5f, 3f, "Size of the whole info panel."); SliderRow("Opacity", _plugin.HudOpacity, 0.1f, 1f, "How see-through the info panel is."); ColorRow("Text color", _plugin.HudColor, "Colour of the panel text, as #RRGGBB."); _plugin.HudBackground.Value = Tog(_plugin.HudBackground.Value, "Dark background behind the text", "Draw a dark box behind the panel so the text stays readable."); _plugin.HudGameFont.Value = Tog(_plugin.HudGameFont.Value, "Use ULTRAKILL's font (VCR OSD Mono)", "Use the game's own pixel font in the panel when it can be found."); EndCard(); BeginCard("Speedometer"); _plugin.SpeedoEnabled.Value = Tog(_plugin.SpeedoEnabled.Value, "Show the speedometer (centre of the screen, BunnyMod XT style)", "A big speed number under the crosshair."); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Shows", "Which speed the number measures.", GUILayout.Width(150f)); int num6 = IndexOf(SpeedoModeValues, _plugin.SpeedoMode.Value); int num7 = ChoiceRow(num6, SpeedoModeLabels, SpeedoModeTips, 0f); if (num7 != num6) { _plugin.SpeedoMode.Value = SpeedoModeValues[num7]; } GUILayout.EndHorizontal(); IntSliderRow("Decimals", _plugin.SpeedoDecimals, 0, 3, "Digits after the decimal point."); IntSliderRow("Size (px)", _plugin.SpeedoSize, 12, 160, "Height of the number in pixels."); OffsetRow("Offset from centre", _plugin.SpeedoOffsetX, _plugin.SpeedoOffsetY, "Move the number away from the screen centre. Positive Y is down."); SliderRow("Opacity", _plugin.SpeedoOpacity, 0.1f, 1f, "How see-through the number is."); ColorRow("Base color", _plugin.SpeedoColor, "Colour of the number, as #RRGGBB."); _plugin.SpeedoColorByChange.Value = Tog(_plugin.SpeedoColorByChange.Value, "Green while speeding up, red while slowing down", "Tint the number green when you gain speed and red when you lose it."); _plugin.SpeedoShadow.Value = Tog(_plugin.SpeedoShadow.Value, "Outline / shadow", "Dark outline so the number stays readable on bright backgrounds."); _plugin.SpeedoUnit.Value = Tog(_plugin.SpeedoUnit.Value, "Show unit (u/s)", "Append the unit after the number."); _plugin.SpeedoShowVertical.Value = Tog(_plugin.SpeedoShowVertical.Value, "Second line: vertical speed", "A smaller line with the up / down speed."); _plugin.SpeedoShowPeak.Value = Tog(_plugin.SpeedoShowPeak.Value, "Second line: peak speed this run", "A smaller line with the highest speed of this run."); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Center it", "Put the speedometer just under the crosshair.", GUILayout.Width(110f))) { _plugin.SpeedoOffsetX.Value = 0; _plugin.SpeedoOffsetY.Value = 60; } if (Btn("Reset peak", "Forget the highest speed seen so far.", GUILayout.Width(110f))) { _peakSpeed = 0f; } if (Btn("Reset HUD layout", "Put the info panel back in the top left with default size and colour.", GUILayout.Width(140f))) { _plugin.HudCorner.Value = "topleft"; _plugin.HudOffsetX.Value = 10; _plugin.HudOffsetY.Value = 10; _plugin.HudScale.Value = 1f; _plugin.HudOpacity.Value = 1f; _plugin.HudColor.Value = "#FFFFFF"; _plugin.HudBackground.Value = true; } GUILayout.EndHorizontal(); EndCard(); BeginCard("Paused label"); _plugin.PausedLabelEnabled.Value = Tog(_plugin.PausedLabelEnabled.Value, "Show PAUSED above the crosshair while the game is paused", "A small PAUSED text in ULTRAKILL's font above the crosshair whenever the TAS clock is paused."); IntSliderRow("Size (px)", _plugin.PausedLabelSize, 12, 96, "Height of the PAUSED text in pixels."); IntSliderRow("Height above centre", _plugin.PausedLabelOffsetY, 10, 400, "How many pixels above the crosshair the label sits."); EndCard(); BeginCard("Determinism"); _plugin.ForceSystemRandomSeeds.Value = Tog(_plugin.ForceSystemRandomSeeds.Value, "Force deterministic System.Random seeds (requires restart to unpatch)", "Make the game's own random numbers repeatable between runs."); _plugin.CaptureStartState.Value = Tog(_plugin.CaptureStartState.Value, "Capture a start state on Play (enables Rewind)", "Snapshot the game when Play starts so Rewind can come back to it."); _plugin.SavestateCleanupSpawned.Value = Tog(_plugin.SavestateCleanupSpawned.Value, "Savestate: destroy coins, projectiles and enemies spawned after the save", "When a savestate loads, remove things that were created after it was saved."); _plugin.PauseOnSceneChange.Value = Tog(_plugin.PauseOnSceneChange.Value, "Pause playback when a scene loads", "Stop the run when a new level loads instead of carrying on."); EndCard(); BeginCard("Startup"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("autoload", "A script loaded automatically when the game starts.", GUILayout.Width(70f)); _plugin.Autoload.Value = Field(_plugin.Autoload.Value, "Path of the script to load at boot. Empty = none."); GUILayout.EndHorizontal(); _plugin.Autoplay.Value = Tog(_plugin.Autoplay.Value, "Autoplay loaded script on boot", "Start the autoload script as soon as the game boots."); Hint("Path may be absolute or relative to " + _plugin.ScriptDirectory); GUILayout.BeginHorizontal(Array.Empty()); Lbl("record file", "File a recording is saved to when no script file is loaded. Relative names go to the script folder.", GUILayout.Width(80f)); _plugin.RecordingFile.Value = Field(_plugin.RecordingFile.Value, "File name, for example recording.uktas.", GUILayout.Width(260f)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("default seed", "Seed written into new scripts.", GUILayout.Width(85f)); _plugin.DefaultSeed.Value = IntField(_plugin.DefaultSeed.Value, 90, "Seed written into new scripts."); Hint("native step " + _time.NativeFixedStep.ToString("0.####") + "s (fixed)"); GUILayout.EndHorizontal(); _plugin.GuiVisibleOnStart.Value = Tog(_plugin.GuiVisibleOnStart.Value, "Show this window on game start", "Open the TAS window as soon as the game starts."); EndCard(); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Save config", "Write every plugin setting to the BepInEx config file now.", GUILayout.Width(120f))) { _plugin.ConfigFile.Save(); } GUILayout.EndHorizontal(); } private void EnsureOptimizerState() { if (_optimConfig == null) { _optimConfig = new OptimConfig(); _optimBoxes = new OptimBoxSet(); _optimConfig.Mutations.MutateCombat = false; _optimConfig.Mutations.MutateWeapons = false; } } private static List UnconnectedRunner(List candidate, int startTick, int endTick) { return null; } private int ParseTickField(string text, int fallback) { if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return fallback; } return result; } private void DrawOptimizerTab() { EnsureOptimizerState(); DrawOptimizerWindow(); DrawOptimizerObjective(); DrawOptimizerMutations(); DrawOptimizerBoxes(); DrawOptimizerControl(); } private void PushOptimizerOverlay() { if (!((Object)(object)_plugin == (Object)null) && _plugin.Trajectory != null && _optimBoxes != null) { _plugin.Trajectory.SetOptimizerBoxes(_optimBoxes); if (_optimizer == null) { _plugin.Trajectory.SetOptimizerPaths(null, null, null); } else { _plugin.Trajectory.SetOptimizerPaths(PositionsOf(_optimizer.BaselineSamples), PositionsOf(_optimizer.BestSamples), PositionsOf(_optimizer.LastCandidateSamples)); } } } private static List PositionsOf(List samples) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (samples == null) { return null; } List list = new List(samples.Count); for (int i = 0; i < samples.Count; i++) { list.Add(samples[i].Position); } return list; } private void DrawOptimizerBoxes() { //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: 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_0327: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_0360: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) //IL_036d: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_03b4: Unknown result type (might be due to invalid IL or missing references) //IL_03b6: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: 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_03d4: Unknown result type (might be due to invalid IL or missing references) //IL_03d9: Unknown result type (might be due to invalid IL or missing references) //IL_03e0: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_0402: Unknown result type (might be due to invalid IL or missing references) //IL_040e: 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_041d: Unknown result type (might be due to invalid IL or missing references) //IL_0420: Unknown result type (might be due to invalid IL or missing references) //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_0424: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_042b: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_03c2: Unknown result type (might be due to invalid IL or missing references) //IL_03c5: Unknown result type (might be due to invalid IL or missing references) BeginCard("Spatial boxes (freecam)"); _optimBoxKind = ChoiceRow(_optimBoxKind, _optimBoxKindLabels, new string[3] { "Reach this box to win (earliest / fastest entry).", "Any tick inside invalidates the attempt.", "The path must touch this box at least once." }, 0f); GUILayout.BeginHorizontal(Array.Empty()); if (Btn("Place at Crosshair", "Raycast from the camera center and drop a 3-unit box on the hit (or 10 units ahead).", GUILayout.Width(180f))) { PlaceBoxAtCrosshair((OptimBoxKind)_optimBoxKind); } Lbl("Nudge step", "Distance per nudge button.", GUILayout.Width(80f)); _optimBoxStep = Field(_optimBoxStep, "Nudge distance.", GUILayout.Width(60f)); GUILayout.EndHorizontal(); if (!float.TryParse(_optimBoxStep, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || result <= 0f) { result = 0.5f; } for (int i = 0; i < _optimBoxes.Boxes.Count; i++) { OptimBox optimBox = _optimBoxes.Boxes[i]; Vector3 center = optimBox.Center; Vector3 val = optimBox.Size; GUILayout.BeginHorizontal(Array.Empty()); optimBox.Enabled = Tog(optimBox.Enabled, optimBox.Name, "Show and use this box."); GUILayout.Label("c " + center.x.ToString("0.#", CultureInfo.InvariantCulture) + ", " + center.y.ToString("0.#", CultureInfo.InvariantCulture) + ", " + center.z.ToString("0.#", CultureInfo.InvariantCulture), Array.Empty()); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Vector3 zero = Vector3.zero; if (Btn("-X", "Move center -X.", GUILayout.Width(40f))) { zero.x -= result; } if (Btn("+X", "Move center +X.", GUILayout.Width(40f))) { zero.x += result; } if (Btn("-Y", "Move center -Y.", GUILayout.Width(40f))) { zero.y -= result; } if (Btn("+Y", "Move center +Y.", GUILayout.Width(40f))) { zero.y += result; } if (Btn("-Z", "Move center -Z.", GUILayout.Width(40f))) { zero.z -= result; } if (Btn("+Z", "Move center +Z.", GUILayout.Width(40f))) { zero.z += result; } if (Btn("Smaller", "Shrink the box by one step on each axis.", GUILayout.Width(70f))) { val -= Vector3.one * result; } if (Btn("Bigger", "Grow the box by one step on each axis.", GUILayout.Width(70f))) { val += Vector3.one * result; } if (BtnDanger("X", "Remove this box.", GUILayout.Width(26f))) { _optimBoxes.Remove(optimBox); GUILayout.EndHorizontal(); break; } GUILayout.EndHorizontal(); if (zero != Vector3.zero || val != optimBox.Size) { Vector3 val2 = center + zero; Vector3 val3 = new Vector3(Mathf.Max(0.05f, val.x), Mathf.Max(0.05f, val.y), Mathf.Max(0.05f, val.z)) * 0.5f; optimBox.SetCorners(val2 - val3, val2 + val3); } } EndCard(); } private void PlaceBoxAtCrosshair(OptimBoxKind kind) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009c: 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_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00be: 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) Camera main = Camera.main; if ((Object)(object)main == (Object)null) { _plugin.Toast("No camera to raycast from.", error: true); return; } Ray val; using (_plugin.ViewPose()) { val = main.ScreenPointToRay(new Vector3((float)Screen.width * 0.5f, (float)Screen.height * 0.5f, 0f)); } RaycastHit val3 = default(RaycastHit); Vector3 val2 = (Physics.Raycast(val, ref val3, 500f) ? ((RaycastHit)(ref val3)).point : (((Ray)(ref val)).origin + ((Ray)(ref val)).direction * 10f)); Vector3 val4 = Vector3.one * 1.5f; _optimBoxes.Add(kind, val2 - val4, val2 + val4); } private void SyncOptimizerMarkerFields() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 if (_engine == null || Event.current == null || (int)Event.current.type != 8) { return; } TasScript script = _engine.Script; bool flag = script != _optimMarkerScript; float realtimeSinceStartup = Time.realtimeSinceStartup; if (flag || !(realtimeSinceStartup < _optimMarkerNextScan)) { _optimMarkerNextScan = realtimeSinceStartup + 0.25f; if (flag) { _optimMarkerScript = script; _optimMarkerValid = false; } if (script == null || !TasOptimizer.ResolveMarkerTicks(script, out var startTick, out var endTick)) { _optimMarkerValid = false; } else if (!_optimMarkerValid || startTick != _optimMarkerStart || endTick != _optimMarkerEnd) { _optimMarkerValid = true; _optimMarkerStart = startTick; _optimMarkerEnd = endTick; _optimStartText = startTick.ToString(CultureInfo.InvariantCulture); _optimEndText = endTick.ToString(CultureInfo.InvariantCulture); } } } private void DrawOptimizerWindow() { SyncOptimizerMarkerFields(); BeginCard("Optimization window"); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Start Tick", "First tick of the segment to optimize.", GUILayout.Width(90f)); _optimStartText = Field(_optimStartText, "Start tick.", GUILayout.Width(90f)); if (Btn("Current", "Use the current tick as the start.", GUILayout.Width(80f))) { _optimStartText = _engine.CurrentTick.ToString(CultureInfo.InvariantCulture); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("End Tick", "Last tick of the segment (exclusive).", GUILayout.Width(90f)); _optimEndText = Field(_optimEndText, "End tick.", GUILayout.Width(90f)); if (Btn("Current", "Use the current tick as the end.", GUILayout.Width(80f))) { _optimEndText = _engine.CurrentTick.ToString(CultureInfo.InvariantCulture); } GUILayout.EndHorizontal(); GUILayout.Label("Rollback", Array.Empty()); _optimConfig.RollbackFullReplay = ChoiceRow(_optimConfig.RollbackFullReplay ? 1 : 0, new string[2] { "Savestate at Start", "Full FFF Replay" }, new string[2] { "Restore a master savestate taken at the start tick (fast).", "Replay from tick 0 in headless FFF before every attempt (slow, no savestates)." }, 0f) == 1; GUILayout.Label("Execution", Array.Empty()); _optimConfig.UseFastForwardHeadless = ChoiceRow(_optimConfig.UseFastForwardHeadless ? 1 : 0, new string[2] { "Visual FF", "Headless FFF" }, new string[2] { "Render each attempt so you can watch it.", "Disable 3D cameras and batch physics for throughput." }, 0f) == 1; EndCard(); } private void DrawOptimizerObjective() { BeginCard("Objective and constraints"); int num = Array.IndexOf(_optimObjectives, _optimConfig.Objective); if (num < 0) { num = 0; } GUILayout.BeginHorizontal(Array.Empty()); Lbl("Target", "What the optimizer tries to improve.", GUILayout.Width(90f)); if (Btn(_optimObjectiveLabels[num] + " ▾", "Click to cycle the target variable.", GUILayout.Width(220f))) { _optimConfig.Objective = _optimObjectives[(num + 1) % _optimObjectives.Length]; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); Lbl("Direction", "Maximize or minimize the target.", GUILayout.Width(90f)); _optimConfig.Direction = ((ChoiceRow((int)_optimConfig.Direction, new string[2] { "Maximize", "Minimize" }, new string[2] { "Bigger is better.", "Smaller is better." }, 0f) == 1) ? OptimDirection.Minimize : OptimDirection.Maximize); GUILayout.EndHorizontal(); GUILayout.Label("Evaluation scope", Array.Empty()); _optimConfig.Scope = ((ChoiceRow((int)_optimConfig.Scope, new string[2] { "Last Frame Only", "Peak Across All Frames" }, new string[2] { "Judge the final tick of the segment.", "Judge the best value on any tick (e.g. apex height)." }, 0f) == 1) ? OptimScope.AllFrames : OptimScope.LastFrame); GUILayout.Label("Constraints", Array.Empty()); for (int i = 0; i < _optimConfig.Constraints.Count; i++) { OptimConstraint optimConstraint = _optimConfig.Constraints[i]; GUILayout.BeginHorizontal(Array.Empty()); if (Btn(TasOptimizer.VariableName(optimConstraint.Variable), "Cycle variable.", GUILayout.Width(110f))) { optimConstraint.Variable = NextVariable(optimConstraint.Variable); } if (Btn(OpText(optimConstraint.Op), "Cycle operator (<, <=, >, >=).", GUILayout.Width(44f))) { optimConstraint.Op = (OptimOperator)((int)(optimConstraint.Op + 1) % 4); } if (Btn(optimConstraint.Value.ToString("0.###", CultureInfo.InvariantCulture), "Click to edit: select row, type a value below.", GUILayout.Width(70f))) { _optimConstraintIndex = i; } if (Btn((optimConstraint.Scope == OptimScope.LastFrame) ? "Last" : "All", "Toggle last frame / all frames.", GUILayout.Width(44f))) { optimConstraint.Scope = ((optimConstraint.Scope == OptimScope.LastFrame) ? OptimScope.AllFrames : OptimScope.LastFrame); } if (BtnDanger("X", "Remove this constraint.", GUILayout.Width(26f))) { _optimConfig.Constraints.RemoveAt(i); _optimConstraintIndex = -1; GUILayout.EndHorizontal(); break; } GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(Array.Empty()); if (_optimConstraintIndex >= 0 && _optimConstraintIndex < _optimConfig.Constraints.Count) { _optimConstraintValue = Field(_optimConstraintValue, "Value for the selected constraint.", GUILayout.Width(90f)); if (double.TryParse(_optimConstraintValue, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { _optimConfig.Constraints[_optimConstraintIndex].Value = result; } } if (Btn("Add constraint", "Add a row: pos.y < 0 (Last Frame).", GUILayout.Width(120f))) { _optimConfig.Constraints.Add(new OptimConstraint()); _optimConstraintIndex = _optimConfig.Constraints.Count - 1; _optimConstraintValue = "0"; } GUILayout.EndHorizontal(); EndCard(); } private void DrawOptimizerMutations() { OptimMutationSettings mutations = _optimConfig.Mutations; BeginCard("Mutations"); mutations.MutateYaw = Tog(mutations.MutateYaw, "Mutate Yaw", "Change yaw on framebulks."); if (mutations.MutateYaw) { mutations.YawStep = Slide(mutations.YawStep, 0.1f, 25f, "Max yaw change per attempt (deg).", GUILayout.Width(220f)); } mutations.MutatePitch = Tog(mutations.MutatePitch, "Mutate Pitch", "Change pitch on framebulks."); if (mutations.MutatePitch) { mutations.PitchStep = Slide(mutations.PitchStep, 0.1f, 25f, "Max pitch change per attempt (deg).", GUILayout.Width(220f)); } mutations.MutateFramecount = Tog(mutations.MutateFramecount, "Mutate Framecount / Repeats", "Change tick counts on framebulks."); if (mutations.MutateFramecount) { mutations.FramecountStep = Mathf.RoundToInt(Slide(mutations.FramecountStep, 1f, 15f, "Max tick change.", GUILayout.Width(220f))); mutations.KeepTotalTicks = Tog(mutations.KeepTotalTicks, "Keep total segment ticks", "Borrow ticks from another bulk so the segment length stays fixed."); } mutations.MutateMovement = Tog(mutations.MutateMovement, "Mutate Movement Keys (WASD / flrb)", "Toggle movement keys in field 2."); mutations.MutateDashSlide = Tog(mutations.MutateDashSlide, "Mutate Dash & Slide (d, s)", "Toggle dash and slide in field 2."); mutations.MutateJump = Tog(mutations.MutateJump, "Mutate Jump (j)", "Toggle jump in field 3."); mutations.MutateCombat = Tog(mutations.MutateCombat, "Mutate Combat (1, 2, p, v)", "Off by default."); mutations.MutateWeapons = Tog(mutations.MutateWeapons, "Mutate Weapon Switches", "Off by default."); _optimConfig.ProjectileAwareness = Tog(_optimConfig.ProjectileAwareness, "Lock Shots to Airborne Projectiles/Coins", "Aim firing frames at the tracked grenade or coin."); mutations.BulksPerIteration = Mathf.RoundToInt(Slide(mutations.BulksPerIteration, 1f, 4f, "Framebulks mutated per attempt.", GUILayout.Width(220f))); Hint("Single-Frame Mode is not implemented (splitting bulks into 1-tick frames)."); EndCard(); } private void DrawOptimizerControl() { BeginCard("Control and telemetry"); bool flag = _engine.OptimizerRunning || (_optimizer != null && _optimizer.Running); GUILayout.BeginHorizontal(Array.Empty()); if (!flag && BtnPrimary("START OPTIMIZER", "Begin the brute-force search on the window above.", GUILayout.Width(180f))) { StartOptimizer(); } if (flag && BtnDanger("STOP OPTIMIZER", "Stop the search and keep the best found.", GUILayout.Width(180f))) { _engine.StopOptimizerRun(); } GUILayout.EndHorizontal(); if (_engine.OptimizerRunning) { GUILayout.Label(_engine.OptimizerSeeking ? ("Status: fast-forwarding to start tick " + _optimConfig.StartTick + " (tick " + _engine.CurrentTick + ")") : ("Status: attempt " + ((_optimizer != null) ? _optimizer.Iterations : 0) + " on ticks " + _optimConfig.StartTick + ".." + _optimConfig.EndTick + " (tick " + _engine.CurrentTick + ")"), Array.Empty()); } if (_optimizer != null) { float num = Mathf.Max(0.001f, Time.realtimeSinceStartup - _optimStartedAt); double num2 = (float)_optimizer.Iterations / num; double num3 = ((_optimizer.Iterations > 0) ? (100.0 * (double)_optimizer.InvalidCount / (double)_optimizer.Iterations) : 0.0); GUILayout.Label("Speed: " + num2.ToString("0.0", CultureInfo.InvariantCulture) + " it/s (" + num3.ToString("0", CultureInfo.InvariantCulture) + "% invalid) | Attempts: " + _optimizer.Iterations, Array.Empty()); DrawOptimizerBestBlock(); foreach (string item in _optimizer.Log) { Hint(item); } } GUILayout.BeginHorizontal(Array.Empty()); bool flag2 = _optimizer != null && _optimizer.BestSegment != null && _optimizer.BestSegment.Count > 0; if (flag2 && Btn("Apply Best to Current Script", "Splice the best framebulks over the window.", GUILayout.Width(200f))) { ApplyBest(); } if (flag2 && Btn("Save Best to File", "Write optimization-best.uktas in the scripts folder.", GUILayout.Width(150f))) { SaveBest(); } GUILayout.EndHorizontal(); if (flag2 && Btn("Save as New Branch", "Project open: add a branch at Start Tick. No project: save _optimized.uktas.", GUILayout.Width(170f))) { SaveAsNewBranch(); } DrawOptimizerSegmentBox(); EndCard(); } private void EnsureOptimizerBestStyles() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Expected O, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Expected O, but got Unknown //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Expected O, but got Unknown if (_optimBestBoxStyle == null) { EnsureEditorFont(); _texOptimBest = RoundedTexture(24, 6f, Color32.op_Implicit(new Color32((byte)40, (byte)34, (byte)28, byte.MaxValue)), ColAccent, 1f); _texOptimBestFlash = RoundedTexture(24, 6f, Color32.op_Implicit(new Color32((byte)30, (byte)58, (byte)36, byte.MaxValue)), ColGood, 2f); _optimBestBoxStyle = new GUIStyle(GUIStyle.none); _optimBestBoxStyle.normal.background = _texOptimBest; _optimBestBoxStyle.border = new RectOffset(8, 8, 8, 8); _optimBestBoxStyle.padding = new RectOffset(12, 12, 8, 8); _optimBestBoxStyle.margin = new RectOffset(2, 2, 4, 4); _optimBestFlashBoxStyle = new GUIStyle(_optimBestBoxStyle); _optimBestFlashBoxStyle.normal.background = _texOptimBestFlash; _optimBestHeadStyle = new GUIStyle(_sectionStyle); _optimBestHeadStyle.margin = new RectOffset(0, 0, 0, 2); _optimBestFlashHeadStyle = new GUIStyle(_optimBestHeadStyle); _optimBestFlashHeadStyle.normal.textColor = ColGood; _optimBestValueStyle = new GUIStyle(_bodyStyle); _optimBestValueStyle.fontSize = 18; _optimBestValueStyle.fontStyle = (FontStyle)1; _optimBestValueStyle.normal.textColor = ColText; GUIStyle val = (((Object)(object)_skin != (Object)null) ? _skin.textArea : GUI.skin.textArea); _optimSegmentAreaStyle = new GUIStyle(val); _optimSegmentAreaStyle.wordWrap = false; _optimSegmentAreaStyle.fontSize = 12; if ((Object)(object)_editorFont != (Object)null) { _optimSegmentAreaStyle.font = _editorFont; } } } private static string FormatOptimScore(double value) { return value.ToString("0.###", CultureInfo.InvariantCulture); } private static string FormatOptimDelta(double value) { return value.ToString("+0.###;-0.###;0", CultureInfo.InvariantCulture); } private void UpdateOptimizerBestTracking() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 if ((int)Event.current.type != 8) { return; } if (_optimizer == null) { _optimTrackedFor = null; _optimTextFor = null; _optimSegmentText = string.Empty; _optimBestFlashing = false; return; } double bestScore = _optimizer.BestScore; if (_optimTrackedFor != _optimizer) { _optimTrackedFor = _optimizer; _optimTrackReady = false; _optimHasImprovement = false; _optimLastImprovement = 0.0; _optimBestChangedAt = -1000f; } if (!_optimTrackReady) { if (_optimizer.Running) { _optimTrackReady = true; _optimLastSeenBest = bestScore; } } else if (bestScore != _optimLastSeenBest) { double num = bestScore - _optimLastSeenBest; _optimLastSeenBest = bestScore; if ((_optimizer.Config.Direction == OptimDirection.Maximize) ? (num > 0.0) : (num < 0.0)) { _optimHasImprovement = true; _optimLastImprovement = num; _optimBestChangedAt = Time.realtimeSinceStartup; } } _optimBestFlashing = Time.realtimeSinceStartup - _optimBestChangedAt < 4f; IList bestSegment = _optimizer.BestSegment; int num2 = bestSegment?.Count ?? 0; if (_optimTextFor != _optimizer || _optimTextScore != bestScore || _optimTextCount != num2) { _optimTextFor = _optimizer; _optimTextScore = bestScore; _optimTextCount = num2; StringBuilder stringBuilder = new StringBuilder(num2 * 48); for (int i = 0; i < num2; i++) { stringBuilder.AppendLine(bestSegment[i].ToPipeLine()); } _optimSegmentText = stringBuilder.ToString(); } } private void DrawOptimizerBestBlock() { UpdateOptimizerBestTracking(); EnsureOptimizerBestStyles(); bool optimBestFlashing = _optimBestFlashing; double bestScore = _optimizer.BestScore; double num = bestScore - _optimizer.BaselineScore; double value = (_optimHasImprovement ? _optimLastImprovement : num); GUILayout.BeginVertical(optimBestFlashing ? _optimBestFlashBoxStyle : _optimBestBoxStyle, Array.Empty()); GUILayout.Label(optimBestFlashing ? "NEW BEST" : "CURRENT BEST", optimBestFlashing ? _optimBestFlashHeadStyle : _optimBestHeadStyle, Array.Empty()); GUILayout.Label("Best: " + FormatOptimScore(bestScore) + " (" + FormatOptimDelta(value) + ")", _optimBestValueStyle, Array.Empty()); Hint("Baseline: " + FormatOptimScore(_optimizer.BaselineScore) + " | Total vs baseline: " + FormatOptimDelta(num) + (_optimHasImprovement ? " | Last step shown in brackets" : "")); GUILayout.EndVertical(); } private void DrawOptimizerSegmentBox() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Invalid comparison between Unknown and I4 //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Invalid comparison between Unknown and I4 //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Invalid comparison between Unknown and I4 //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Invalid comparison between Unknown and I4 //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Invalid comparison between Unknown and I4 //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Invalid comparison between Unknown and I4 //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Invalid comparison between Unknown and I4 if (_optimizer == null || _optimizer.BestSegment == null || _optimizer.BestSegment.Count == 0) { return; } UpdateOptimizerBestTracking(); EnsureOptimizerBestStyles(); GUILayout.BeginHorizontal(Array.Empty()); Hint("Framebulks for ticks " + _optimizer.Config.StartTick + ".." + _optimizer.Config.EndTick + " (best so far). Click inside, Ctrl+A then Ctrl+C to copy."); if (Btn("Copy", "Copy these framebulk lines to the clipboard.", GUILayout.Width(60f))) { GUIUtility.systemCopyBuffer = _optimSegmentText; _plugin.Toast("Copied " + _optimizer.BestSegment.Count + " framebulk line(s).", error: false); } GUILayout.EndHorizontal(); Event current = Event.current; if ((int)current.type == 4 && GUI.GetNameOfFocusedControl() == "UktasOptimBestSegment") { bool flag = current.control || current.command; bool num = !flag && current.character >= ' ' && current.character != '\u007f'; bool flag2 = (int)current.keyCode == 8 || (int)current.keyCode == 127 || (int)current.keyCode == 13 || (int)current.keyCode == 271 || (flag && ((int)current.keyCode == 118 || (int)current.keyCode == 120)); if (num || flag2) { current.Use(); } } _optimSegmentScroll = GUILayout.BeginScrollView(_optimSegmentScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(150f) }); GUI.SetNextControlName("UktasOptimBestSegment"); GUILayout.TextArea(_optimSegmentText, _optimSegmentAreaStyle, Array.Empty()); GUILayout.EndScrollView(); } private void StartOptimizer() { if (_engine.Script == null) { _plugin.Toast("Optimizer: no script loaded.", error: true); return; } int num = ParseTickField(_optimStartText, -1); int num2 = ParseTickField(_optimEndText, -1); if (TasOptimizer.ResolveMarkerTicks(_engine.Script, out var startTick, out var endTick)) { num = startTick; num2 = endTick; _optimStartText = num.ToString(CultureInfo.InvariantCulture); _optimEndText = num2.ToString(CultureInfo.InvariantCulture); } if (num < 0 || num2 <= num) { _plugin.Toast("Optimizer: set Start Tick below End Tick.", error: true); return; } _optimConfig.StartTick = num; _optimConfig.EndTick = num2; if (!ExtractSegment(num, num2, out var segment, out var error)) { _plugin.Toast("Optimizer: " + error, error: true); return; } _optimizer = new TasOptimizer(_optimConfig, _optimBoxes, segment, UnconnectedRunner, (int)DateTime.Now.Ticks); _optimStartedAt = Time.realtimeSinceStartup; EngineOptimizerHost engineOptimizerHost = new EngineOptimizerHost(_engine, _states, _bridge, _engine.Script, _engine.ScriptPath, num, num2, delegate(string msg) { _plugin.Toast(msg, error: false); }); engineOptimizerHost.Headless = _optimConfig.UseFastForwardHeadless; engineOptimizerHost.FullReplay = _optimConfig.RollbackFullReplay; engineOptimizerHost.AimLockEnabled = _optimConfig.ProjectileAwareness; TasOptimizerRunner runner = new TasOptimizerRunner(_optimizer, engineOptimizerHost); if (!_engine.StartOptimizerRun(runner, out var error2)) { _plugin.Toast("Optimizer: " + error2, error: true); } else { _plugin.Toast("Optimizer started. Fast-forwarding (FFF) to tick " + num + " first.", error: false); } } private void SaveAsNewBranch() { if (_optimizer == null || _optimizer.BestSegment == null || _optimizer.BestSegment.Count == 0) { _plugin.Toast("Optimizer: no best segment yet.", error: true); return; } try { int startTick = _optimConfig.StartTick; int endTick = _optimConfig.EndTick; TasScript tasScript = TasScript.Parse(_engine.Script.Serialize(), "optimized"); if (!TasOptimizer.SpliceSegment(tasScript, startTick, endTick, _optimizer.BestSegment, out var error)) { _plugin.Toast("Save as branch failed: " + error, error: true); } else if (_plugin.Project != null) { BranchProject project = _plugin.Project; UktasBranch uktasBranch = project.AddDivergentBranch("Optimized @" + startTick, _engine.Script, tasScript, startTick); _plugin.Toast("Added branch '" + uktasBranch.Name + "' to " + Path.GetFileName(project.ProjectPath) + "; bridged script updated. Switch in the Branches tab.", error: false); } else { string path = (string.IsNullOrEmpty(_engine.ScriptPath) ? _plugin.ScriptDirectory : Path.GetDirectoryName(_engine.ScriptPath)); string text = (string.IsNullOrEmpty(_engine.ScriptPath) ? "script" : Path.GetFileNameWithoutExtension(_engine.ScriptPath)); string text2 = Path.Combine(path, text + "_optimized.uktas"); tasScript.Save(text2); _plugin.Toast("Saved " + text2, error: false); } } catch (Exception ex) { _plugin.Toast("Save as branch failed: " + ex.Message, error: true); } } private bool ExtractSegment(int start, int end, out List segment, out string error) { segment = new List(); error = null; TickLocation tickLocation = _engine.Script.Locate(start); TickLocation tickLocation2 = _engine.Script.Locate(end); if (!tickLocation.Valid || !tickLocation2.Valid || tickLocation.TickWithinLine != 0 || tickLocation2.TickWithinLine != 0) { error = "start and end must fall on framebulk boundaries."; return false; } for (int i = tickLocation.LineIndex; i < tickLocation2.LineIndex; i++) { segment.Add(_engine.Script.Lines[i].Clone()); } return true; } private void ApplyBest() { int startTick = ParseTickField(_optimStartText, -1); int endTick = ParseTickField(_optimEndText, -1); if (!TasOptimizer.SpliceSegment(_engine.Script, startTick, endTick, _optimizer.BestSegment, out var error)) { _plugin.Toast("Apply failed: " + error, error: true); return; } if (string.IsNullOrEmpty(_engine.ScriptPath)) { _plugin.Toast("Spliced in memory. Script has no file path; save from the editor.", error: false); return; } try { _engine.Script.Save(_engine.ScriptPath); _plugin.Toast("Applied best segment and saved " + Path.GetFileName(_engine.ScriptPath), error: false); } catch (Exception ex) { _plugin.Toast("Save failed: " + ex.Message, error: true); } } private void SaveBest() { try { string text = Path.Combine(_plugin.ScriptDirectory, "optimization-best.uktas"); TasOptimizer.SaveSegment(_engine.Script, _optimizer.BestSegment, text); _plugin.Toast("Saved " + text, error: false); } catch (Exception ex) { _plugin.Toast("Save failed: " + ex.Message, error: true); } } private static string OpText(OptimOperator op) { return op switch { OptimOperator.Less => "<", OptimOperator.LessEq => "<=", OptimOperator.Greater => ">", _ => ">=", }; } private static OptimObjective NextVariable(OptimObjective v) { OptimObjective[] array = new OptimObjective[8] { OptimObjective.PosX, OptimObjective.PosY, OptimObjective.PosZ, OptimObjective.VelX, OptimObjective.VelY, OptimObjective.VelZ, OptimObjective.SpeedXZ, OptimObjective.Speed3D }; int num = Array.IndexOf(array, v); return array[(num + 1) % array.Length]; } private bool IsClockPaused() { switch (_engine.Mode) { case EngineMode.Paused: return true; case EngineMode.Recording: case EngineMode.Standalone: return _time.Paused; default: return false; } } private void DrawPausedLabel() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Invalid comparison between Unknown and I4 //IL_00cb: 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_015a: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown if (!_plugin.PausedLabelEnabled.Value || _plugin.CleanRecordingActive || (int)Event.current.type != 7 || !IsClockPaused()) { return; } EnsureHudStyles(); float num = Mathf.Clamp(_plugin.PausedLabelSize.Value, 12, 96); float num2 = (float)Screen.width * 0.5f; float num3 = (float)Screen.height * 0.5f - (float)Mathf.Clamp(_plugin.PausedLabelOffsetY.Value, 0, 600); float num4 = 0.82f + 0.18f * Mathf.Sin(TimeController.RealTime * 3.2f); Color color = default(Color); ((Color)(ref color))..ctor(1f, 0.88f, 0.62f, num4); if (!DrawGameFontText(num2, num3, "PAUSED", num, color, outline: true)) { if (_pausedStyle == null) { _pausedStyle = new GUIStyle(_speedoStyle); _pausedStyle.alignment = (TextAnchor)4; _pausedStyle.fontStyle = (FontStyle)1; } _pausedStyle.font = GameFont(); _pausedStyle.fontSize = Mathf.RoundToInt(num); Rect rect = default(Rect); ((Rect)(ref rect))..ctor(num2 - 200f, num3 - num * 0.7f, 400f, num * 1.4f); DrawOutlined(rect, "PAUSED", _pausedStyle, color, num4, num); } } private Texture2D NewTexture(int width, int height, Func pixel) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_003a: 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) Texture2D val = new Texture2D(width, height, (TextureFormat)4, false); ((Object)val).hideFlags = (HideFlags)61; ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; Color[] array = (Color[])(object)new Color[width * height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { array[i * width + j] = pixel(j, i); } } val.SetPixels(array); val.Apply(false, false); return val; } private static float RoundedDistance(float x, float y, float width, float height, float radius) { float num = Mathf.Abs(x + 0.5f - width * 0.5f) - (width * 0.5f - radius); float num2 = Mathf.Abs(y + 0.5f - height * 0.5f) - (height * 0.5f - radius); float num3 = Mathf.Max(num, 0f); float num4 = Mathf.Max(num2, 0f); return Mathf.Sqrt(num3 * num3 + num4 * num4) + Mathf.Min(Mathf.Max(num, num2), 0f) - radius; } private Texture2D RoundedTexture(int size, float radius, Color fill, Color border, float borderWidth) { //IL_001d: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return NewTexture(size, size, delegate(int x, int y) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) float num = RoundedDistance(x, y, size, size, radius); float num2 = Mathf.Clamp01(0.5f - num); float num3 = Mathf.Clamp01(0.5f + num + borderWidth); Color result = Color.Lerp(fill, border, num3); result.a *= num2; return result; }); } private Texture2D SolidTexture(Color color) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) return NewTexture(4, 4, (int x, int y) => color); } private Texture2D CircleTexture(int size, Color fill, Color rim) { //IL_000e: 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) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) return NewTexture(size, size, delegate(int x, int y) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) float num = RoundedDistance(x, y, size, size, (float)size * 0.5f); float num2 = Mathf.Clamp01(0.5f - num); Color result = Color.Lerp(fill, rim, Mathf.Clamp01(0.5f + num + 1.5f)); result.a *= num2; return result; }); } private Texture2D TrackTexture(int size, int barHeight, Color fill) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) return NewTexture(size, size, delegate(int x, int y) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) float num = (float)(size + barHeight) * 0.5f; float num2 = (float)(size - barHeight) * 0.5f; float num3 = RoundedDistance(x, (float)y - num2, size, barHeight, (float)barHeight * 0.5f); float num4 = (((float)y + 0.5f >= num2 && (float)y + 0.5f <= num) ? Mathf.Clamp01(0.5f - num3) : 0f); Color result = fill; result.a *= num4; return result; }); } private Texture2D CheckTexture(bool on, bool hover) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Expected O, but got Unknown //IL_00c3: 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_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0099: 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) Color[] array = (Color[])(object)new Color[1024]; Color val = (on ? ColAccent : ColField); Color val2 = (on ? ColAccentPressed : (hover ? ColAccent : ColFieldBorder)); for (int i = 0; i < 32; i++) { for (int j = 0; j < 32; j++) { float num = RoundedDistance(j, i, 32f, 32f, 7f); float num2 = Mathf.Clamp01(0.5f - num); Color val3 = Color.Lerp(val, val2, Mathf.Clamp01(0.5f + num + 2.2f)); val3.a *= num2; array[i * 32 + j] = val3; } } if (on) { Color color = Color32.op_Implicit(new Color32((byte)26, (byte)20, (byte)14, byte.MaxValue)); StampLine(array, 32, 8.5f, 16.5f, 13.5f, 10.5f, 2.2f, color); StampLine(array, 32, 13.5f, 10.5f, 23.5f, 22.5f, 2.2f, color); } Texture2D val4 = new Texture2D(32, 32, (TextureFormat)4, false) { hideFlags = (HideFlags)61, filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1 }; val4.SetPixels(array); val4.Apply(false, false); return val4; } private static void StampLine(Color[] pixels, int size, float x0, float y0, float x1, float y1, float radius, Color color) { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: 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_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) int num = 40; for (int i = 0; i <= num; i++) { float num2 = (float)i / (float)num; float num3 = Mathf.Lerp(x0, x1, num2); float num4 = Mathf.Lerp(y0, y1, num2); int num5 = Mathf.Max(0, (int)(num3 - radius - 1f)); int num6 = Mathf.Min(size - 1, (int)(num3 + radius + 1f)); int num7 = Mathf.Max(0, (int)(num4 - radius - 1f)); int num8 = Mathf.Min(size - 1, (int)(num4 + radius + 1f)); for (int j = num7; j <= num8; j++) { for (int k = num5; k <= num6; k++) { float num9 = (float)k + 0.5f - num3; float num10 = (float)j + 0.5f - num4; float num11 = Mathf.Clamp01(radius + 0.5f - Mathf.Sqrt(num9 * num9 + num10 * num10)); if (!(num11 <= 0f)) { Color val = pixels[j * size + k]; pixels[j * size + k] = Color.Lerp(val, new Color(color.r, color.g, color.b, val.a), num11); } } } } } private static void SetState(GUIStyleState state, Texture2D background, Color text) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) state.background = background; state.textColor = text; } private static void SetAllStates(GUIStyle style, Texture2D normal, Texture2D hover, Texture2D active, Color text) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_004d: 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_0069: Unknown result type (might be due to invalid IL or missing references) SetState(style.normal, normal, text); SetState(style.hover, hover, text); SetState(style.active, active, text); SetState(style.focused, normal, text); SetState(style.onNormal, normal, text); SetState(style.onHover, hover, text); SetState(style.onActive, active, text); SetState(style.onFocused, normal, text); } private void EnsureTheme() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: 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) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_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_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0379: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Unknown result type (might be due to invalid IL or missing references) //IL_0396: Unknown result type (might be due to invalid IL or missing references) //IL_03e8: Unknown result type (might be due to invalid IL or missing references) //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_03f2: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Unknown result type (might be due to invalid IL or missing references) //IL_041c: Unknown result type (might be due to invalid IL or missing references) //IL_0432: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_04b6: Unknown result type (might be due to invalid IL or missing references) //IL_0515: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Unknown result type (might be due to invalid IL or missing references) //IL_0532: Expected O, but got Unknown //IL_053b: Unknown result type (might be due to invalid IL or missing references) //IL_0545: Expected O, but got Unknown //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_0588: Unknown result type (might be due to invalid IL or missing references) //IL_059f: Unknown result type (might be due to invalid IL or missing references) //IL_05a9: Expected O, but got Unknown //IL_05c8: Unknown result type (might be due to invalid IL or missing references) //IL_05d7: Unknown result type (might be due to invalid IL or missing references) //IL_05e1: Expected O, but got Unknown //IL_05e8: Unknown result type (might be due to invalid IL or missing references) //IL_05f2: Expected O, but got Unknown //IL_05f7: Unknown result type (might be due to invalid IL or missing references) //IL_0601: Expected O, but got Unknown //IL_062e: Unknown result type (might be due to invalid IL or missing references) //IL_0644: Unknown result type (might be due to invalid IL or missing references) //IL_065a: Unknown result type (might be due to invalid IL or missing references) //IL_0670: Unknown result type (might be due to invalid IL or missing references) //IL_0686: Unknown result type (might be due to invalid IL or missing references) //IL_069c: Unknown result type (might be due to invalid IL or missing references) //IL_06b2: Unknown result type (might be due to invalid IL or missing references) //IL_06c8: Unknown result type (might be due to invalid IL or missing references) //IL_06d7: Unknown result type (might be due to invalid IL or missing references) //IL_06e1: Expected O, but got Unknown //IL_06e6: Unknown result type (might be due to invalid IL or missing references) //IL_06f0: Expected O, but got Unknown //IL_06f5: Unknown result type (might be due to invalid IL or missing references) //IL_06ff: Expected O, but got Unknown //IL_071d: Unknown result type (might be due to invalid IL or missing references) //IL_0733: Unknown result type (might be due to invalid IL or missing references) //IL_0749: Unknown result type (might be due to invalid IL or missing references) //IL_075f: Unknown result type (might be due to invalid IL or missing references) //IL_076e: Unknown result type (might be due to invalid IL or missing references) //IL_0778: Expected O, but got Unknown //IL_077d: Unknown result type (might be due to invalid IL or missing references) //IL_0787: Expected O, but got Unknown //IL_07a5: Unknown result type (might be due to invalid IL or missing references) //IL_07b4: Unknown result type (might be due to invalid IL or missing references) //IL_07be: Expected O, but got Unknown //IL_07c2: Unknown result type (might be due to invalid IL or missing references) //IL_07cc: Expected O, but got Unknown //IL_07e3: Unknown result type (might be due to invalid IL or missing references) //IL_07f2: Unknown result type (might be due to invalid IL or missing references) //IL_07fc: Expected O, but got Unknown //IL_080b: Unknown result type (might be due to invalid IL or missing references) //IL_0815: Expected O, but got Unknown //IL_082c: Unknown result type (might be due to invalid IL or missing references) //IL_0842: Unknown result type (might be due to invalid IL or missing references) //IL_0858: Unknown result type (might be due to invalid IL or missing references) //IL_0867: Unknown result type (might be due to invalid IL or missing references) //IL_0871: Expected O, but got Unknown //IL_088b: Unknown result type (might be due to invalid IL or missing references) //IL_0895: Expected O, but got Unknown //IL_0915: Unknown result type (might be due to invalid IL or missing references) //IL_091f: Expected O, but got Unknown //IL_0930: Unknown result type (might be due to invalid IL or missing references) //IL_0944: Unknown result type (might be due to invalid IL or missing references) //IL_094e: Expected O, but got Unknown //IL_095c: Unknown result type (might be due to invalid IL or missing references) //IL_0966: Expected O, but got Unknown //IL_0970: Unknown result type (might be due to invalid IL or missing references) //IL_097a: Expected O, but got Unknown //IL_097c: Unknown result type (might be due to invalid IL or missing references) //IL_0986: Expected O, but got Unknown //IL_09aa: Unknown result type (might be due to invalid IL or missing references) //IL_09be: Unknown result type (might be due to invalid IL or missing references) //IL_09c8: Expected O, but got Unknown //IL_09ca: Unknown result type (might be due to invalid IL or missing references) //IL_09d4: Expected O, but got Unknown //IL_09f8: Unknown result type (might be due to invalid IL or missing references) //IL_0a04: Unknown result type (might be due to invalid IL or missing references) //IL_0a0e: Expected O, but got Unknown //IL_0a2d: Unknown result type (might be due to invalid IL or missing references) //IL_0a37: Expected O, but got Unknown //IL_0a48: Unknown result type (might be due to invalid IL or missing references) //IL_0a5c: Unknown result type (might be due to invalid IL or missing references) //IL_0a66: Expected O, but got Unknown //IL_0a68: Unknown result type (might be due to invalid IL or missing references) //IL_0a72: Expected O, but got Unknown //IL_0a95: Unknown result type (might be due to invalid IL or missing references) //IL_0a9a: Unknown result type (might be due to invalid IL or missing references) //IL_0ab2: Unknown result type (might be due to invalid IL or missing references) //IL_0abc: Expected O, but got Unknown //IL_0ad4: Unknown result type (might be due to invalid IL or missing references) //IL_0aec: Unknown result type (might be due to invalid IL or missing references) //IL_0af6: Expected O, but got Unknown //IL_0b19: Unknown result type (might be due to invalid IL or missing references) //IL_0b1e: Unknown result type (might be due to invalid IL or missing references) //IL_0b2a: Unknown result type (might be due to invalid IL or missing references) //IL_0b34: Expected O, but got Unknown //IL_0b47: Unknown result type (might be due to invalid IL or missing references) //IL_0b5c: Unknown result type (might be due to invalid IL or missing references) //IL_0b71: Unknown result type (might be due to invalid IL or missing references) //IL_0b87: Unknown result type (might be due to invalid IL or missing references) //IL_0b91: Expected O, but got Unknown //IL_0b9b: Unknown result type (might be due to invalid IL or missing references) //IL_0ba5: Expected O, but got Unknown //IL_0bb9: Unknown result type (might be due to invalid IL or missing references) //IL_0bc3: Expected O, but got Unknown //IL_0bdb: Unknown result type (might be due to invalid IL or missing references) //IL_0bef: Unknown result type (might be due to invalid IL or missing references) //IL_0bf9: Expected O, but got Unknown //IL_0c07: Unknown result type (might be due to invalid IL or missing references) //IL_0c11: Expected O, but got Unknown //IL_0c1c: Unknown result type (might be due to invalid IL or missing references) //IL_0c26: Expected O, but got Unknown //IL_0c30: Unknown result type (might be due to invalid IL or missing references) //IL_0c3a: Expected O, but got Unknown //IL_0c45: Unknown result type (might be due to invalid IL or missing references) //IL_0c5a: Unknown result type (might be due to invalid IL or missing references) //IL_0c6f: Unknown result type (might be due to invalid IL or missing references) //IL_0c84: Unknown result type (might be due to invalid IL or missing references) //IL_0c99: Unknown result type (might be due to invalid IL or missing references) //IL_0cae: Unknown result type (might be due to invalid IL or missing references) //IL_0cc6: Unknown result type (might be due to invalid IL or missing references) //IL_0cd0: Expected O, but got Unknown //IL_0ce8: Unknown result type (might be due to invalid IL or missing references) //IL_0cfc: Unknown result type (might be due to invalid IL or missing references) //IL_0d06: Expected O, but got Unknown //IL_0d0c: Unknown result type (might be due to invalid IL or missing references) //IL_0d16: Expected O, but got Unknown //IL_0d27: Unknown result type (might be due to invalid IL or missing references) //IL_0d3b: Unknown result type (might be due to invalid IL or missing references) //IL_0d45: Expected O, but got Unknown //IL_0d4b: Unknown result type (might be due to invalid IL or missing references) //IL_0d55: Expected O, but got Unknown //IL_0d66: Unknown result type (might be due to invalid IL or missing references) //IL_0d7a: Unknown result type (might be due to invalid IL or missing references) //IL_0d84: Expected O, but got Unknown //IL_0d90: Unknown result type (might be due to invalid IL or missing references) //IL_0d9a: Expected O, but got Unknown if (!((Object)(object)_skin != (Object)null)) { _texWindow = NewTexture(48, 96, delegate(int x, int y) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) float num = RoundedDistance(x, y, 48f, 96f, 10f); float num2 = Mathf.Clamp01(0.5f - num); Color result = Color.Lerp((y >= 62) ? ColHeader : ColWindow, ColWindowBorder, Mathf.Clamp01(0.5f + num + 1.2f)); result.a *= num2; return result; }); _texCard = RoundedTexture(24, 6f, ColCard, ColCardBorder, 1f); _texButton = RoundedTexture(24, 6f, ColButton, ColButton, 0f); _texButtonHover = RoundedTexture(24, 6f, ColButtonHover, ColButtonHover, 0f); _texButtonPressed = RoundedTexture(24, 6f, ColButtonPressed, ColButtonPressed, 0f); _texPrimary = RoundedTexture(24, 6f, ColAccent, ColAccent, 0f); _texPrimaryHover = RoundedTexture(24, 6f, ColAccentHover, ColAccentHover, 0f); _texPrimaryPressed = RoundedTexture(24, 6f, ColAccentPressed, ColAccentPressed, 0f); _texDanger = RoundedTexture(24, 6f, ColDanger, ColDanger, 0f); _texDangerHover = RoundedTexture(24, 6f, ColDangerHover, ColDangerHover, 0f); _texDangerPressed = RoundedTexture(24, 6f, ColDangerPressed, ColDangerPressed, 0f); _texField = RoundedTexture(24, 5f, ColField, ColFieldBorder, 1f); _texFieldHover = RoundedTexture(24, 5f, ColField, Color32.op_Implicit(new Color32((byte)86, (byte)98, (byte)122, byte.MaxValue)), 1f); _texFieldFocus = RoundedTexture(24, 5f, ColField, ColAccent, 1.4f); _texTabHover = RoundedTexture(24, 6f, Color32.op_Implicit(new Color32((byte)40, (byte)46, (byte)58, byte.MaxValue)), Color32.op_Implicit(new Color32((byte)40, (byte)46, (byte)58, byte.MaxValue)), 0f); _texTabActive = NewTexture(16, 32, (int x, int y) => (y < 3) ? ColAccent : ColCard); _texSep = SolidTexture(ColCardBorder); _texTrack = TrackTexture(16, 6, Color32.op_Implicit(new Color32((byte)14, (byte)17, (byte)22, byte.MaxValue))); _texThumb = CircleTexture(16, ColAccent, ColAccentPressed); _texThumbHover = CircleTexture(16, ColAccentHover, ColAccent); _texScrollTrack = RoundedTexture(16, 5f, Color32.op_Implicit(new Color32((byte)20, (byte)23, (byte)29, byte.MaxValue)), Color32.op_Implicit(new Color32((byte)20, (byte)23, (byte)29, byte.MaxValue)), 0f); _texScrollThumb = RoundedTexture(16, 5f, Color32.op_Implicit(new Color32((byte)66, (byte)75, (byte)96, byte.MaxValue)), Color32.op_Implicit(new Color32((byte)66, (byte)75, (byte)96, byte.MaxValue)), 0f); _texScrollThumbHover = RoundedTexture(16, 5f, Color32.op_Implicit(new Color32((byte)96, (byte)108, (byte)134, byte.MaxValue)), Color32.op_Implicit(new Color32((byte)96, (byte)108, (byte)134, byte.MaxValue)), 0f); _texCheckOff = CheckTexture(on: false, hover: false); _texCheckOn = CheckTexture(on: true, hover: false); _texCheckHover = CheckTexture(on: false, hover: true); _texTip = RoundedTexture(24, 5f, Color32.op_Implicit(new Color32((byte)12, (byte)14, (byte)19, (byte)245)), ColAccent, 1f); _texBanner = RoundedTexture(24, 6f, Color32.op_Implicit(new Color32((byte)0, (byte)0, (byte)0, (byte)150)), Color32.op_Implicit(new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)40)), 1f); _skinBase = GUI.skin; _skin = Object.Instantiate(GUI.skin); ((Object)_skin).hideFlags = (HideFlags)61; _skin.settings.cursorColor = ColAccentHover; _skin.settings.selectionColor = new Color(ColAccent.r, ColAccent.g, ColAccent.b, 0.45f); _skin.settings.cursorFlashSpeed = 1.6f; _skin.settings.doubleClickSelectsWord = true; _skin.settings.tripleClickSelectsLine = true; GUIStyle window = _skin.window; SetAllStates(window, _texWindow, _texWindow, _texWindow, ColText); window.border = new RectOffset(14, 14, 34, 14); window.padding = new RectOffset(14, 14, 40, 12); window.alignment = (TextAnchor)0; window.contentOffset = new Vector2(6f, -31f); window.fontStyle = (FontStyle)1; window.fontSize = 13; window.clipping = (TextClipping)1; GUIStyle label = _skin.label; label.normal.textColor = ColText; label.fontSize = 12; label.margin = new RectOffset(2, 2, 2, 2); GUIStyle button = _skin.button; SetAllStates(button, _texButton, _texButtonHover, _texButtonPressed, ColText); button.border = new RectOffset(8, 8, 8, 8); button.padding = new RectOffset(11, 11, 5, 6); button.margin = new RectOffset(3, 3, 3, 3); button.alignment = (TextAnchor)4; button.fontSize = 12; button.clipping = (TextClipping)1; GUIStyle textField = _skin.textField; SetState(textField.normal, _texField, ColText); SetState(textField.hover, _texFieldHover, ColText); SetState(textField.active, _texFieldFocus, ColText); SetState(textField.focused, _texFieldFocus, ColText); SetState(textField.onNormal, _texField, ColText); SetState(textField.onHover, _texFieldHover, ColText); SetState(textField.onActive, _texFieldFocus, ColText); SetState(textField.onFocused, _texFieldFocus, ColText); textField.border = new RectOffset(8, 8, 8, 8); textField.padding = new RectOffset(8, 8, 5, 6); textField.margin = new RectOffset(3, 3, 3, 3); textField.fontSize = 12; GUIStyle textArea = _skin.textArea; SetState(textArea.normal, _texField, ColText); SetState(textArea.hover, _texFieldHover, ColText); SetState(textArea.active, _texFieldFocus, ColText); SetState(textArea.focused, _texFieldFocus, ColText); textArea.border = new RectOffset(8, 8, 8, 8); textArea.padding = new RectOffset(8, 8, 6, 6); textArea.fontSize = 12; GUIStyle box = _skin.box; SetState(box.normal, _texCard, ColText); box.border = new RectOffset(8, 8, 8, 8); box.padding = new RectOffset(8, 8, 6, 6); GUIStyle horizontalSlider = _skin.horizontalSlider; SetState(horizontalSlider.normal, _texTrack, ColText); horizontalSlider.border = new RectOffset(7, 7, 0, 0); horizontalSlider.fixedHeight = 16f; horizontalSlider.margin = new RectOffset(4, 4, 6, 4); GUIStyle horizontalSliderThumb = _skin.horizontalSliderThumb; SetState(horizontalSliderThumb.normal, _texThumb, ColText); SetState(horizontalSliderThumb.hover, _texThumbHover, ColText); SetState(horizontalSliderThumb.active, _texThumbHover, ColText); horizontalSliderThumb.border = new RectOffset(0, 0, 0, 0); horizontalSliderThumb.fixedWidth = 16f; horizontalSliderThumb.fixedHeight = 16f; horizontalSliderThumb.overflow = new RectOffset(0, 0, 0, 0); StyleScrollbar(_skin.verticalScrollbar, _skin.verticalScrollbarThumb, vertical: true); StyleScrollbar(_skin.horizontalScrollbar, _skin.horizontalScrollbarThumb, vertical: false); HideScrollButton(_skin.verticalScrollbarUpButton); HideScrollButton(_skin.verticalScrollbarDownButton); HideScrollButton(_skin.horizontalScrollbarLeftButton); HideScrollButton(_skin.horizontalScrollbarRightButton); _cardStyle = new GUIStyle(GUIStyle.none); SetState(_cardStyle.normal, _texCard, ColText); _cardStyle.border = new RectOffset(8, 8, 8, 8); _cardStyle.padding = new RectOffset(14, 14, 10, 12); _cardStyle.margin = new RectOffset(2, 2, 4, 6); _sectionStyle = new GUIStyle(label); _sectionStyle.fontSize = 11; _sectionStyle.fontStyle = (FontStyle)1; _sectionStyle.normal.textColor = ColAccent; _sectionStyle.margin = new RectOffset(2, 2, 0, 4); _hintStyle = new GUIStyle(label); _hintStyle.fontSize = 11; _hintStyle.wordWrap = true; _hintStyle.normal.textColor = ColMuted; _bodyStyle = new GUIStyle(label); _bodyStyle.wordWrap = true; _bodyStyle.fontSize = 13; _sepStyle = new GUIStyle(GUIStyle.none); SetState(_sepStyle.normal, _texSep, ColText); _sepStyle.margin = new RectOffset(0, 0, 6, 6); _primaryStyle = new GUIStyle(button); SetAllStates(_primaryStyle, _texPrimary, _texPrimaryHover, _texPrimaryPressed, Color32.op_Implicit(new Color32((byte)26, (byte)18, (byte)10, byte.MaxValue))); _primaryStyle.fontStyle = (FontStyle)1; _dangerStyle = new GUIStyle(button); SetAllStates(_dangerStyle, _texDanger, _texDangerHover, _texDangerPressed, Color.white); _dangerStyle.fontStyle = (FontStyle)1; _selectedStyle = new GUIStyle(button); SetAllStates(_selectedStyle, _texPrimary, _texPrimaryHover, _texPrimaryPressed, Color32.op_Implicit(new Color32((byte)26, (byte)18, (byte)10, byte.MaxValue))); _tabStyle = new GUIStyle(button); SetAllStates(_tabStyle, null, _texTabHover, _texTabHover, ColMuted); _tabStyle.hover.textColor = ColText; _tabStyle.active.textColor = ColText; _tabStyle.padding = new RectOffset(12, 12, 6, 7); _tabStyle.margin = new RectOffset(1, 1, 0, 0); _tabStyle.fontSize = 12; _tabActiveStyle = new GUIStyle(_tabStyle); SetAllStates(_tabActiveStyle, _texTabActive, _texTabActive, _texTabActive, Color.white); _tabActiveStyle.border = new RectOffset(4, 4, 0, 3); _tabActiveStyle.fontStyle = (FontStyle)1; _toggleStyle = new GUIStyle(label); _toggleStyle.padding = new RectOffset(26, 4, 3, 3); _toggleStyle.margin = new RectOffset(3, 3, 3, 3); _toggleStyle.normal.textColor = ColText; _toggleStyle.hover.textColor = Color.white; _toggleStyle.onNormal.textColor = ColText; _toggleStyle.onHover.textColor = Color.white; _toggleStyle.active.textColor = Color.white; _toggleStyle.onActive.textColor = Color.white; _toggleStyle.clipping = (TextClipping)0; _statusBarStyle = new GUIStyle(label); _statusBarStyle.fontSize = 11; _statusBarStyle.normal.textColor = ColMuted; _statusBarStyle.margin = new RectOffset(4, 4, 4, 0); _bannerStyle = new GUIStyle(GUIStyle.none); SetState(_bannerStyle.normal, _texBanner, Color.white); _bannerStyle.border = new RectOffset(8, 8, 8, 8); _tipStyle = new GUIStyle(GUIStyle.none); SetState(_tipStyle.normal, _texTip, ColText); _tipStyle.border = new RectOffset(8, 8, 8, 8); _tipStyle.padding = new RectOffset(10, 10, 7, 8); _tipStyle.wordWrap = true; _tipStyle.fontSize = 12; _tipStyle.alignment = (TextAnchor)0; _tipStyle.richText = false; _tipStyle.clipping = (TextClipping)0; } } private void StyleScrollbar(GUIStyle track, GUIStyle thumb, bool vertical) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown SetState(track.normal, _texScrollTrack, ColText); track.border = new RectOffset(6, 6, 6, 6); track.margin = new RectOffset(0, 0, 0, 0); track.padding = new RectOffset(2, 2, 2, 2); if (vertical) { track.fixedWidth = 14f; } else { track.fixedHeight = 14f; } SetState(thumb.normal, _texScrollThumb, ColText); SetState(thumb.hover, _texScrollThumbHover, ColText); SetState(thumb.active, _texScrollThumbHover, ColText); thumb.border = new RectOffset(6, 6, 6, 6); thumb.overflow = new RectOffset(0, 0, 0, 0); thumb.padding = new RectOffset(0, 0, 0, 0); thumb.margin = new RectOffset(0, 0, 0, 0); if (vertical) { thumb.fixedWidth = 14f; thumb.fixedHeight = 0f; } else { thumb.fixedHeight = 14f; thumb.fixedWidth = 0f; } } private static void HideScrollButton(GUIStyle button) { //IL_0007: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown SetState(button.normal, null, Color.clear); SetState(button.hover, null, Color.clear); SetState(button.active, null, Color.clear); button.fixedWidth = 0f; button.fixedHeight = 0f; button.padding = new RectOffset(0, 0, 0, 0); button.margin = new RectOffset(0, 0, 0, 0); button.border = new RectOffset(0, 0, 0, 0); } private void BeginCard(string title) { GUILayout.BeginVertical(_cardStyle, Array.Empty()); if (!string.IsNullOrEmpty(title)) { GUILayout.Label(title.ToUpperInvariant(), _sectionStyle, Array.Empty()); } } private void EndCard() { GUILayout.EndVertical(); } private void Separator() { GUILayout.Box(GUIContent.none, _sepStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Height(1f), GUILayout.ExpandWidth(true) }); } private void Hint(string text) { GUILayout.Label(text, _hintStyle, Array.Empty()); } private void Lbl(string text, string tip, params GUILayoutOption[] options) { GUILayout.Label(text, options); Tip(tip); } private bool Btn(string label, string tip, params GUILayoutOption[] options) { bool result = GUILayout.Button(label, options); Tip(tip); return result; } private bool BtnPrimary(string label, string tip, params GUILayoutOption[] options) { bool result = GUILayout.Button(label, _primaryStyle, options); Tip(tip); return result; } private bool BtnDanger(string label, string tip, params GUILayoutOption[] options) { bool result = GUILayout.Button(label, _dangerStyle, options); Tip(tip); return result; } private bool BtnChoice(bool selected, string label, string tip, params GUILayoutOption[] options) { bool result = GUILayout.Button(label, selected ? _selectedStyle : GUI.skin.button, options); Tip(tip); return result; } private string Field(string value, string tip, params GUILayoutOption[] options) { string result = GUILayout.TextField(value ?? string.Empty, options); Tip(tip); return result; } private bool Tog(bool value, string label, string tip, params GUILayoutOption[] options) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) bool flag = GUILayout.Toggle(value, label, _toggleStyle, options); if ((int)Event.current.type == 7) { Rect lastRect = GUILayoutUtility.GetLastRect(); bool flag2 = ((Rect)(ref lastRect)).Contains(Event.current.mousePosition); Texture2D val = (flag ? _texCheckOn : (flag2 ? _texCheckHover : _texCheckOff)); Color color = GUI.color; GUI.color = Color.white; GUI.DrawTexture(new Rect(((Rect)(ref lastRect)).x + 4f, ((Rect)(ref lastRect)).y + (((Rect)(ref lastRect)).height - 16f) * 0.5f, 16f, 16f), (Texture)(object)val); GUI.color = color; } Tip(tip); return flag; } private float Slide(float value, float min, float max, string tip, params GUILayoutOption[] options) { float result = GUILayout.HorizontalSlider(value, min, max, options); Tip(tip); return result; } private void StatusLine() { if (!string.IsNullOrEmpty(_statusText)) { GUILayout.Label(_statusText, _statusIsError ? _errorStyle : _hintStyle, Array.Empty()); } } private void Tip(string text) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_003a: 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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(text) && (int)Event.current.type == 7 && !_shortcutsOpen && (!_tipClipActive || ((Rect)(ref _tipClip)).Contains(_tipWindowMouse))) { Rect lastRect = GUILayoutUtility.GetLastRect(); if (((Rect)(ref lastRect)).Contains(Event.current.mousePosition)) { _tipText = text; } } } private void DrawTooltip() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_007f: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type != 7) { return; } if (string.IsNullOrEmpty(_tipText)) { _tipShown = null; return; } float realTime = TimeController.RealTime; if (!string.Equals(_tipShown, _tipText, StringComparison.Ordinal)) { _tipShown = _tipText; _tipSince = realTime; } if (!(realTime - _tipSince < 0.35f)) { GUIContent measureContent = _measureContent; measureContent.text = _tipText; float num = Mathf.Min(340f, _tipStyle.CalcSize(measureContent).x + 4f); float num2 = _tipStyle.CalcHeight(measureContent, num); Vector2 mousePosition = Event.current.mousePosition; float width = ((Rect)(ref _windowRect)).width; float height = ((Rect)(ref _windowRect)).height; float num3 = mousePosition.x + 16f; float num4 = mousePosition.y + 20f; if (num3 + num > width - 6f) { num3 = Mathf.Max(6f, mousePosition.x - num - 10f); } if (num4 + num2 > height - 6f) { num4 = Mathf.Max(6f, mousePosition.y - num2 - 12f); } Color color = GUI.color; GUI.color = Color.white; GUI.Label(new Rect(num3, num4, num, num2), measureContent, _tipStyle); GUI.color = color; } } private void AskConfirm(string title, string body, string yesLabel, bool offerSkip, Action action) { _confirmTitle = title; _confirmBody = body; _confirmYes = yesLabel; _confirmOffersSkip = offerSkip; _confirmSkipChecked = false; _confirmAction = action; } private void RequestOverwriteSave(string path, Action save) { if (string.IsNullOrEmpty(path)) { _statusText = "Type a file path first."; _statusIsError = true; _plugin.Toast("Type a file path first.", error: true); } else if (_skipOverwriteConfirm || !File.Exists(path)) { save(); } else { AskConfirm("Overwrite this file?", "Are you sure? This will overwrite your file:\n" + path, "Overwrite", offerSkip: true, save); } } private bool AskRecordingOverwrite(string path) { if (_skipOverwriteConfirm) { return false; } _visible = true; AskConfirm("Overwrite this file?", "Are you sure? Stopping the recording will overwrite your file:\n" + path + "\nThe file is replaced by the script in memory (the recording), and its comments are dropped. Cancel keeps recording, paused.", "Overwrite", offerSkip: true, delegate { _engine.StopRecording(save: true); }); _plugin.Toast("Stopping the recording would overwrite " + Path.GetFileName(path) + ": confirm in the TAS window.", error: false); return true; } private void DrawConfirm() { GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.FlexibleSpace(); GUILayout.BeginVertical(_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(560f) }); GUILayout.Label(_confirmTitle.ToUpperInvariant(), _sectionStyle, Array.Empty()); GUILayout.Label(_confirmBody, _bodyStyle, Array.Empty()); if (_confirmOffersSkip) { GUILayout.Space(4f); _confirmSkipChecked = Tog(_confirmSkipChecked, "Don't ask again until the game closes", "Skips this confirmation for every save until you restart ULTRAKILL."); } GUILayout.Space(8f); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.FlexibleSpace(); if (Btn("Cancel", "Keep the existing file and go back.", GUILayout.Width(110f))) { _confirmAction = null; _statusText = "Cancelled. Nothing was changed."; _statusIsError = false; } else if (BtnDanger(_confirmYes, "Yes, replace the file on disk.", GUILayout.Width(130f))) { Action confirmAction = _confirmAction; if (_confirmOffersSkip && _confirmSkipChecked) { _skipOverwriteConfirm = true; } _confirmAction = null; confirmAction?.Invoke(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); } private bool EnsureFontAtlas() { if (_fontAtlas != (Object)null) { return true; } if (TimeController.RealTime < _nextFontAtlasTry) { return false; } _fontAtlasTries++; _nextFontAtlasTry = Math.Max(TimeController.RealTime + ((_fontAtlasTries < 3) ? 5f : 60f), _noFontSearchUntil); _fontAtlas = FindFontAtlas(); if (_fontAtlas != (Object)null) { ReadFontAtlas(); } return _fontAtlas != (Object)null; } private Object FindFontAtlas() { try { Type type = _bridge.FindType("TMP_FontAsset"); if (type == null) { return null; } Object[] array = Resources.FindObjectsOfTypeAll(type); if (array == null || array.Length == 0) { return null; } Dictionary dictionary = new Dictionary(); Type type2 = _bridge.FindType("TMP_Text"); if (type2 != null) { Object[] array2 = Resources.FindObjectsOfTypeAll(type2); for (int i = 0; i < array2.Length; i++) { if (!(array2[i] == (Object)null)) { object member = _bridge.GetMember(array2[i], new string[2] { "font", "m_fontAsset" }); Object val = (Object)((member is Object) ? member : null); if (!(val == (Object)null)) { dictionary.TryGetValue(val, out var value); dictionary[val] = value + 1; } } } } Object result = null; string text = string.Empty; int num = 0; foreach (Object val2 in array) { if (!(val2 == (Object)null)) { string text2 = (val2.name ?? string.Empty).ToLowerInvariant(); int num2 = 0; if (text2.Contains("vcr")) { num2 += 6; } else if (text2.Contains("osd") || text2.Contains("mono")) { num2 += 4; } if (dictionary.TryGetValue(val2, out var value2)) { num2 += Math.Min(value2, 3); } if (num2 != 0 && (num2 > num || (num2 == num && text2.Length < text.Length))) { result = val2; text = text2; num = num2; } } } return result; } catch (Exception ex) { _plugin.LogWarning("Speedometer font: font asset search failed: " + ex.Message); } return null; } private void ReadFontAtlas() { //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) _atlasGlyphs.Clear(); _fontAtlasName = _fontAtlas.name; Texture2D[] array = _bridge.GetMember(_fontAtlas, new string[2] { "atlasTextures", "m_AtlasTextures" }) as Texture2D[]; _fontAtlasLookup = _bridge.GetMember(_fontAtlas, new string[2] { "characterLookupTable", "m_CharacterLookupTable" }) as IDictionary; _fontAtlasCharacterTable = ((_fontAtlasLookup == null) ? (_bridge.GetMember(_fontAtlas, new string[2] { "characterTable", "m_CharacterTable" }) as IEnumerable) : null); object member = _bridge.GetMember(_fontAtlas, new string[2] { "faceInfo", "m_FaceInfo" }); float num = ReadAtlasNumber(member, "pointSize", 90f); float num2 = ReadAtlasNumber(member, "scale", 1f); _fontAtlasPointSize = ((num > 0f) ? num : 90f); _fontAtlasScale = ((num2 > 0f) ? num2 : 1f); if (array == null || array.Length == 0 || (_fontAtlasLookup == null && _fontAtlasCharacterTable == null)) { _plugin.LogWarning("Speedometer font: '" + _fontAtlasName + "' has no readable glyph atlas; keeping the system font."); _fontAtlas = null; _fontAtlasTextures = null; return; } Texture[] fontAtlasTextures = (Texture[])(object)array; _fontAtlasTextures = fontAtlasTextures; _fontAtlasMasks = (Texture[])(object)new Texture[array.Length]; if ((Object)(object)MaskTexture(0) == (Object)null) { _plugin.LogWarning("Speedometer font: the glyph atlas of '" + _fontAtlasName + "' cannot be drawn; keeping the system font."); _fontAtlas = null; _fontAtlasTextures = null; _fontAtlasMasks = null; return; } _plugin.LogInfo("Speedometer font: drawing ULTRAKILL's '" + _fontAtlasName + "' glyph atlas (" + ((Texture)array[0]).width + "x" + ((Texture)array[0]).height + ", " + ((object)array[0].format/*cast due to .constrained prefix*/).ToString() + ")."); } private Texture MaskTexture(int index) { if (_fontAtlasMasks == null || index < 0 || index >= _fontAtlasMasks.Length) { return null; } Texture val = _fontAtlasMasks[index]; if ((Object)(object)val != (Object)null) { return val; } Texture2D val2 = (Texture2D)((index < _fontAtlasTextures.Length) ? /*isinst with value type is only supported in some contexts*/: null); if ((Object)(object)val2 == (Object)null) { return null; } Color32[] array = ReadAtlasPixels(val2); if (array == null) { _plugin.LogWarning("Speedometer font: could not read the glyph atlas '" + ((Object)val2).name + "'; keeping the system font."); return null; } val = (Texture)(object)BuildMask(array, ((Texture)val2).width, ((Texture)val2).height); _fontAtlasMasks[index] = val; return val; } private Color32[] ReadAtlasPixels(Texture2D source) { //IL_0046: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown try { return source.GetPixels32(); } catch { } RenderTexture active = RenderTexture.active; RenderTexture val = null; try { val = RenderTexture.GetTemporary(((Texture)source).width, ((Texture)source).height, 0, (RenderTextureFormat)0); Graphics.Blit((Texture)(object)source, val); RenderTexture.active = val; Texture2D val2 = new Texture2D(((Texture)source).width, ((Texture)source).height, (TextureFormat)4, false); val2.ReadPixels(new Rect(0f, 0f, (float)((Texture)source).width, (float)((Texture)source).height), 0, 0); val2.Apply(false, false); Color32[] pixels = val2.GetPixels32(); Object.Destroy((Object)val2); return pixels; } catch (Exception ex) { _plugin.LogWarning("Speedometer font: glyph atlas copy failed: " + ex.Message); return null; } finally { RenderTexture.active = active; if ((Object)(object)val != (Object)null) { RenderTexture.ReleaseTemporary(val); } } } private static Texture2D BuildMask(Color32[] pixels, int width, int height) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) bool flag = false; for (int i = 0; i < pixels.Length; i++) { if (pixels[i].a < 250) { flag = true; break; } } Color32[] array = (Color32[])(object)new Color32[pixels.Length]; for (int j = 0; j < pixels.Length; j++) { Color32 val = pixels[j]; int num = (int)(((float)(int)(flag ? val.a : Math.Max(val.r, Math.Max(val.g, val.b))) / 255f - 0.42f) / 0.16f * 255f); if (num < 0) { num = 0; } else if (num > 255) { num = 255; } array[j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)num); } Texture2D val2 = new Texture2D(width, height, (TextureFormat)4, false) { name = "ULTRAKILL font mask", filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1 }; val2.SetPixels32(array); val2.Apply(false, true); return val2; } private float ReadAtlasNumber(object target, string name, float fallback) { if (target == null) { return fallback; } object member = _bridge.GetMember(target, new string[1] { name }); if (member is float) { return (float)member; } if (member is int) { return (int)member; } if (member is uint) { return (uint)member; } if (member is double) { return (float)(double)member; } if (member is IConvertible) { try { return Convert.ToSingle(member, CultureInfo.InvariantCulture); } catch { } } return fallback; } private object LookupAtlasCharacter(char c) { if (_fontAtlasLookup != null) { try { return _fontAtlasLookup[(uint)c]; } catch { return null; } } if (_fontAtlasCharacterTable == null) { return null; } foreach (object item in _fontAtlasCharacterTable) { if (item == null) { continue; } object member = _bridge.GetMember(item, new string[2] { "unicode", "m_Unicode" }); if (member == null) { continue; } try { if (Convert.ToUInt32(member, CultureInfo.InvariantCulture) == c) { return item; } } catch { } } return null; } private AtlasGlyph ReadAtlasGlyph(char c) { //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) AtlasGlyph result = new AtlasGlyph { scale = 1f }; object obj = LookupAtlasCharacter(c); if (obj == null) { return result; } object member = _bridge.GetMember(obj, new string[2] { "glyph", "m_Glyph" }); if (member == null) { return result; } float num = ReadAtlasNumber(member, "scale", 1f); result.scale = ((num > 0f) ? num : 1f); object member2 = _bridge.GetMember(member, new string[2] { "metrics", "m_Metrics" }); result.width = ReadAtlasNumber(member2, "width", 0f); result.height = ReadAtlasNumber(member2, "height", 0f); result.bearingX = ReadAtlasNumber(member2, "horizontalBearingX", 0f); result.bearingY = ReadAtlasNumber(member2, "horizontalBearingY", 0f); result.advance = ReadAtlasNumber(member2, "horizontalAdvance", 0f); object member3 = _bridge.GetMember(member, new string[2] { "glyphRect", "m_GlyphRect" }); float num2 = ReadAtlasNumber(member3, "x", 0f); float num3 = ReadAtlasNumber(member3, "y", 0f); float num4 = ReadAtlasNumber(member3, "width", 0f); float num5 = ReadAtlasNumber(member3, "height", 0f); int num6 = Mathf.RoundToInt(ReadAtlasNumber(member, "atlasIndex", 0f)); if (_fontAtlasTextures == null || num6 < 0 || num6 >= _fontAtlasTextures.Length) { return result; } Texture val = MaskTexture(num6); if ((Object)(object)val == (Object)null || num4 <= 0f || num5 <= 0f || result.width <= 0f || result.height <= 0f) { return result; } result.texture = val; result.texCoords = new Rect(num2 / (float)val.width, num3 / (float)val.height, num4 / (float)val.width, num5 / (float)val.height); result.usable = true; return result; } private AtlasGlyph AtlasGlyphFor(char c) { if (_atlasGlyphs.TryGetValue(c, out var value)) { return value; } value = ReadAtlasGlyph(c); _atlasGlyphs[c] = value; return value; } private bool DrawGameFontText(float centreX, float centreY, string text, float size, Color color, bool outline) { //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(text) || !EnsureFontAtlas()) { return false; } float num = size / _fontAtlasPointSize * _fontAtlasScale; if (num <= 0f) { return false; } float num2 = 0f; float num3 = float.MinValue; float num4 = float.MaxValue; bool flag = false; for (int i = 0; i < text.Length; i++) { AtlasGlyph atlasGlyph = AtlasGlyphFor(text[i]); num2 += atlasGlyph.advance * atlasGlyph.scale * num; if (atlasGlyph.usable) { flag = true; num3 = Mathf.Max(num3, atlasGlyph.bearingY * atlasGlyph.scale * num); num4 = Mathf.Min(num4, (atlasGlyph.bearingY - atlasGlyph.height) * atlasGlyph.scale * num); } } if (!flag) { return false; } float num5 = centreY + (num3 + num4) * 0.5f; float num6 = centreX - num2 * 0.5f; Color color2 = GUI.color; if (outline) { float num7 = Mathf.Max(1.5f, size * 0.055f); GUI.color = new Color(0f, 0f, 0f, 0.9f * color.a); DrawAtlasRun(num6 + num7, num5 + num7, text, num); DrawAtlasRun(num6 - num7, num5 + num7, text, num); DrawAtlasRun(num6 + num7, num5 - num7, text, num); DrawAtlasRun(num6 - num7, num5 - num7, text, num); } GUI.color = color; DrawAtlasRun(num6, num5, text, num); GUI.color = color2; return true; } private void DrawAtlasRun(float penX, float baseline, string text, float pixelsPerPoint) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < text.Length; i++) { AtlasGlyph atlasGlyph = AtlasGlyphFor(text[i]); if (atlasGlyph.usable) { GUI.DrawTextureWithTexCoords(new Rect(penX + atlasGlyph.bearingX * atlasGlyph.scale * pixelsPerPoint, baseline - atlasGlyph.bearingY * atlasGlyph.scale * pixelsPerPoint, atlasGlyph.width * atlasGlyph.scale * pixelsPerPoint, atlasGlyph.height * atlasGlyph.scale * pixelsPerPoint), atlasGlyph.texture, atlasGlyph.texCoords, true); } penX += atlasGlyph.advance * atlasGlyph.scale * pixelsPerPoint; } } private void ResolveTriggerTypes() { if (_triggerTypesResolved) { return; } Type type = _bridge.FindType("ObjectActivator") ?? _bridge.FindType("EnemyIdentifier"); if (type == null) { return; } _triggerTypesResolved = true; Type[] array; try { array = type.Assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { array = ex.Types; } catch (Exception ex2) { _plugin.LogWarning("Show triggers: could not list game types: " + ex2.Message); array = new Type[0]; } foreach (Type type2 in array) { if (!(type2 == null) && !type2.IsAbstract && !type2.ContainsGenericParameters && typeof(Component).IsAssignableFrom(type2) && (type2.Name.IndexOf("Trigger", StringComparison.Ordinal) >= 0 || type2.Name.IndexOf("Event", StringComparison.Ordinal) >= 0)) { _triggerTypes.Add(type2); } } for (int j = 0; j < TriggerExtraTypeNames.Length; j++) { Type type3 = _bridge.FindType(TriggerExtraTypeNames[j]); if (type3 == null) { _plugin.LogWarning("Show triggers: game type '" + TriggerExtraTypeNames[j] + "' not found; it is skipped."); } else if (!_triggerTypes.Contains(type3)) { _triggerTypes.Add(type3); } } _plugin.LogInfo("Show triggers: " + _triggerTypes.Count + " trigger/event component types."); } private void RefreshTriggerOverlay() { try { RefreshTriggerOverlayCore(); } catch (Exception ex) { _triggerVisible.Clear(); if (!_triggerWarned) { _triggerWarned = true; _plugin.LogWarning("Show triggers: refresh failed: " + ex.Message); } } } private void RefreshTriggerOverlayCore() { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (_engine != null && _engine.RenderSuppressed) { return; } if (!_plugin.ShowTriggers.Value) { if (_triggerAll.Count > 0) { _triggerAll.Clear(); _triggerVisible.Clear(); _triggerSceneHandle = int.MinValue; } return; } object member = _bridge.GetMember(_bridge.CameraController, OverlayCameraNames); _overlayCamera = (Camera)((member is Camera) ? member : null); if ((Object)(object)_overlayCamera == (Object)null) { _overlayCamera = Camera.main; } Scene activeScene = SceneManager.GetActiveScene(); int handle = ((Scene)(ref activeScene)).handle; if (handle != _triggerSceneHandle || Time.frameCount - _triggerScanFrame >= 300) { _triggerSceneHandle = handle; _triggerScanFrame = Time.frameCount; ScanTriggers(); } FilterTriggers(); } private void ScanTriggers() { _triggerAll.Clear(); ResolveTriggerTypes(); _triggerSeen.Clear(); for (int i = 0; i < _triggerTypes.Count && _triggerAll.Count < 4000; i++) { Object[] array; try { array = Object.FindObjectsOfType(_triggerTypes[i]); } catch { continue; } for (int j = 0; j < array.Length; j++) { if (_triggerAll.Count >= 4000) { break; } Object obj2 = array[j]; Component val = (Component)(object)((obj2 is Component) ? obj2 : null); if ((Object)(object)val == (Object)null) { continue; } string label = ((object)val).GetType().Name + " " + ((Object)val.gameObject).name; val.GetComponents(_triggerColliders); bool flag = false; for (int k = 0; k < _triggerColliders.Count; k++) { Collider val2 = _triggerColliders[k]; if (!((Object)(object)val2 == (Object)null) && val2.isTrigger) { flag = true; if (_triggerSeen.Add(((Object)val2).GetInstanceID())) { _triggerAll.Add(new TriggerMarker { Owner = val, Collider = val2, Label = label }); } } } if (!flag && _triggerSeen.Add(((Object)val.gameObject).GetInstanceID())) { _triggerAll.Add(new TriggerMarker { Owner = val, Label = label }); } } } } private void FilterTriggers() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) _triggerVisible.Clear(); Camera overlayCamera = _overlayCamera; if ((Object)(object)overlayCamera == (Object)null) { return; } Vector3 position = ((Component)overlayCamera).transform.position; float num = Mathf.Clamp(_plugin.ShowTriggersDistance.Value, 5f, 500f); float num2 = num * num; for (int i = 0; i < _triggerAll.Count && _triggerVisible.Count < 128; i++) { TriggerMarker triggerMarker = _triggerAll[i]; if (!GameBridge.IsAlive(triggerMarker.Owner) || !triggerMarker.Owner.gameObject.activeInHierarchy) { continue; } float num3; if ((Object)(object)triggerMarker.Collider != (Object)null) { if (!triggerMarker.Collider.enabled) { continue; } Bounds bounds = triggerMarker.Collider.bounds; num3 = ((Bounds)(ref bounds)).SqrDistance(position); } else { Vector3 val = triggerMarker.Owner.transform.position - position; num3 = ((Vector3)(ref val)).sqrMagnitude; } if (num3 <= num2) { _triggerVisible.Add(triggerMarker); } } } private bool EnsureLineMaterial() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown if ((Object)(object)_lineMaterial != (Object)null) { return true; } if (_lineMaterialTried) { return false; } _lineMaterialTried = true; Shader val = Shader.Find("Hidden/Internal-Colored"); if ((Object)(object)val == (Object)null) { _plugin.LogWarning("Show triggers: shader Hidden/Internal-Colored not found; drawing screen rectangles instead."); return false; } _lineMaterial = new Material(val); ((Object)_lineMaterial).hideFlags = (HideFlags)61; _lineMaterial.SetInt("_SrcBlend", 5); _lineMaterial.SetInt("_DstBlend", 10); _lineMaterial.SetInt("_Cull", 0); _lineMaterial.SetInt("_ZWrite", 0); _lineMaterial.SetInt("_ZTest", 8); return true; } private static Vector3 ToViewport(Camera camera, Vector3 world) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) return camera.WorldToViewportPoint(world); } private void DrawTriggerOverlay() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010c: 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_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0335: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: 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_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_0502: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0469: Unknown result type (might be due to invalid IL or missing references) //IL_046e: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_0440: Unknown result type (might be due to invalid IL or missing references) //IL_044c: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_0471: Unknown result type (might be due to invalid IL or missing references) //IL_0473: Unknown result type (might be due to invalid IL or missing references) //IL_0478: Unknown result type (might be due to invalid IL or missing references) //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_0496: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_04b5: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_04d3: Unknown result type (might be due to invalid IL or missing references) if ((_engine != null && _engine.RenderSuppressed) || !_plugin.ShowTriggers.Value || _triggerVisible.Count == 0 || (int)Event.current.type != 7) { return; } Camera overlayCamera = _overlayCamera; if ((Object)(object)overlayCamera == (Object)null || !((Behaviour)overlayCamera).isActiveAndEnabled) { return; } if (_triggerLabelStyle == null) { _triggerLabelStyle = new GUIStyle(GUI.skin.label); _triggerLabelStyle.fontSize = 11; _triggerLabelStyle.alignment = (TextAnchor)7; _triggerLabelStyle.wordWrap = false; _triggerLabelStyle.richText = false; _triggerLabelStyle.clipping = (TextClipping)0; } float num = Screen.width; float num2 = Screen.height; Color val = default(Color); ((Color)(ref val))..ctor(1f, 0.78f, 0.2f, 0.9f); Color val2 = default(Color); ((Color)(ref val2))..ctor(0.4f, 0.9f, 1f, 0.9f); bool flag = EnsureLineMaterial(); Color color = GUI.color; Color color2 = default(Color); ((Color)(ref color2))..ctor(val.r, val.g, val.b, Mathf.Clamp(_plugin.ShowTriggersOpacity.Value, 0.02f, 1f)); if (flag) { GL.PushMatrix(); _lineMaterial.SetPass(0); GL.LoadPixelMatrix(); if (_plugin.ShowTriggersSolid.Value) { DrawSolidTriggerBoxes(overlayCamera, num, num2, color2); } GL.Begin(1); } Vector3 world = default(Vector3); for (int i = 0; i < _triggerVisible.Count; i++) { TriggerMarker triggerMarker = _triggerVisible[i]; if (!GameBridge.IsAlive(triggerMarker.Owner)) { continue; } if ((Object)(object)triggerMarker.Collider != (Object)null && GameBridge.IsAlive(triggerMarker.Collider)) { Bounds bounds = triggerMarker.Collider.bounds; Vector3 min = ((Bounds)(ref bounds)).min; Vector3 max = ((Bounds)(ref bounds)).max; for (int j = 0; j < 8; j++) { ((Vector3)(ref world))..ctor(((j & 1) != 0) ? max.x : min.x, ((j & 2) != 0) ? max.y : min.y, ((j & 4) != 0) ? max.z : min.z); _triggerCorners[j] = ToViewport(overlayCamera, world); } if (flag) { GL.Color(val); for (int k = 0; k < BoxEdges.Length; k += 2) { Vector3 val3 = _triggerCorners[BoxEdges[k]]; Vector3 val4 = _triggerCorners[BoxEdges[k + 1]]; if (!(val3.z <= 0f) && !(val4.z <= 0f)) { GL.Vertex3(val3.x * num, val3.y * num2, 0f); GL.Vertex3(val4.x * num, val4.y * num2, 0f); } } } else { DrawScreenRect(val, num, num2); } } else if (flag) { Vector3 val5 = ToViewport(overlayCamera, triggerMarker.Owner.transform.position); if (val5.z > 0f) { float num3 = val5.x * num; float num4 = val5.y * num2; GL.Color(val2); GL.Vertex3(num3 - 6f, num4, 0f); GL.Vertex3(num3 + 6f, num4, 0f); GL.Vertex3(num3, num4 - 6f, 0f); GL.Vertex3(num3, num4 + 6f, 0f); } } } if (flag) { GL.End(); GL.PopMatrix(); } Vector3 position = default(Vector3); for (int l = 0; l < _triggerVisible.Count; l++) { TriggerMarker triggerMarker2 = _triggerVisible[l]; if (GameBridge.IsAlive(triggerMarker2.Owner)) { bool flag2 = (Object)(object)triggerMarker2.Collider != (Object)null && GameBridge.IsAlive(triggerMarker2.Collider); if (flag2) { Bounds bounds2 = triggerMarker2.Collider.bounds; ((Vector3)(ref position))..ctor(((Bounds)(ref bounds2)).center.x, ((Bounds)(ref bounds2)).max.y, ((Bounds)(ref bounds2)).center.z); } else { position = triggerMarker2.Owner.transform.position; } Vector3 val6 = ToViewport(overlayCamera, position); if (!(val6.z <= 0f)) { float num5 = val6.x * num; float num6 = (1f - val6.y) * num2; _triggerLabelStyle.normal.textColor = (flag2 ? val : val2); GUI.Label(new Rect(num5 - 200f, num6 - 18f, 400f, 16f), triggerMarker2.Label, _triggerLabelStyle); } } } GUI.color = color; } private void DrawSolidTriggerBoxes(Camera camera, float width, float height, Color color) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: 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) GL.Begin(7); GL.Color(color); Vector3 world = default(Vector3); for (int i = 0; i < _triggerVisible.Count; i++) { TriggerMarker triggerMarker = _triggerVisible[i]; if ((Object)(object)triggerMarker.Collider == (Object)null || !GameBridge.IsAlive(triggerMarker.Collider) || !triggerMarker.Collider.enabled) { continue; } Bounds bounds = triggerMarker.Collider.bounds; Vector3 min = ((Bounds)(ref bounds)).min; Vector3 max = ((Bounds)(ref bounds)).max; bool flag = false; for (int j = 0; j < 8; j++) { ((Vector3)(ref world))..ctor(((j & 1) != 0) ? max.x : min.x, ((j & 2) != 0) ? max.y : min.y, ((j & 4) != 0) ? max.z : min.z); _triggerCorners[j] = ToViewport(camera, world); if (_triggerCorners[j].z <= 0f) { flag = true; } } if (flag) { continue; } for (int k = 0; k < BoxFaces.Length; k += 4) { for (int l = 0; l < 4; l++) { Vector3 val = _triggerCorners[BoxFaces[k + l]]; GL.Vertex3(val.x * width, val.y * height, 0f); } } } GL.End(); } private void DrawScreenRect(Color color, float width, float height) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_009d: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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) float num = float.MaxValue; float num2 = float.MaxValue; float num3 = float.MinValue; float num4 = float.MinValue; for (int i = 0; i < 8; i++) { Vector3 val = _triggerCorners[i]; if (val.z <= 0f) { return; } float num5 = val.x * width; float num6 = (1f - val.y) * height; num = Mathf.Min(num, num5); num3 = Mathf.Max(num3, num5); num2 = Mathf.Min(num2, num6); num4 = Mathf.Max(num4, num6); } GUI.color = color; Texture2D whiteTexture = Texture2D.whiteTexture; GUI.DrawTexture(new Rect(num, num2, num3 - num, 1f), (Texture)(object)whiteTexture); GUI.DrawTexture(new Rect(num, num4, num3 - num, 1f), (Texture)(object)whiteTexture); GUI.DrawTexture(new Rect(num, num2, 1f, num4 - num2), (Texture)(object)whiteTexture); GUI.DrawTexture(new Rect(num3, num2, 1f, num4 - num2), (Texture)(object)whiteTexture); } private void ApplyViewmodelVisibility() { if (!_plugin.HideViewmodels.Value) { RestoreViewmodels(); return; } Transform weapon = CurrentWeaponRoot(); Transform arm = CurrentArmRoot(); if (Time.frameCount != _viewmodelScanFrame) { _viewmodelScanFrame = Time.frameCount; CollectViewmodels(weapon, arm); } foreach (KeyValuePair item in _viewmodelWasForcedOff) { Renderer key = item.Key; if ((Object)(object)key != (Object)null) { key.forceRenderingOff = true; } } } private void CollectViewmodels(Transform weapon, Transform arm) { _viewmodelSeen.Clear(); AddViewmodelRenderers(weapon); AddViewmodelRenderers(arm); } private void AddViewmodelRenderers(Transform root) { if ((Object)(object)root == (Object)null) { return; } Renderer[] componentsInChildren; try { componentsInChildren = ((Component)root).GetComponentsInChildren(true); } catch { return; } foreach (Renderer val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && _viewmodelSeen.Add(((Object)val).GetInstanceID()) && !_viewmodelWasForcedOff.ContainsKey(val)) { _viewmodelWasForcedOff.Add(val, val.forceRenderingOff); } } } private Transform CurrentWeaponRoot() { object gunControl = _bridge.GunControl; if (gunControl == null) { return null; } return TransformOf(_bridge.GetMember(gunControl, new string[2] { "currentWeapon", "weapon" })); } private Transform CurrentArmRoot() { object fistControl = _bridge.FistControl; if (fistControl == null) { return null; } return TransformOf(_bridge.GetMember(fistControl, new string[2] { "currentArmObject", "currentArm" })); } private static Transform TransformOf(object value) { Component val = (Component)((value is Component) ? value : null); if ((Object)(object)val != (Object)null) { return val.transform; } GameObject val2 = (GameObject)((value is GameObject) ? value : null); if (!((Object)(object)val2 != (Object)null)) { return null; } return val2.transform; } private void RestoreViewmodels() { foreach (KeyValuePair item in _viewmodelWasForcedOff) { Renderer key = item.Key; if ((Object)(object)key != (Object)null) { key.forceRenderingOff = item.Value; } } _viewmodelWasForcedOff.Clear(); _viewmodelSeen.Clear(); _viewmodelScanFrame = -1000; } private void ResetViewmodels() { RestoreViewmodels(); } } public sealed class TasMouse { public bool Active; public Vector2 Position; public bool Left; public bool Right; public bool Middle; public float Scroll; public int GlideTicksLeft; public Vector2 GlideTarget; public void Reset() { Active = false; Left = (Right = (Middle = false)); Scroll = 0f; GlideTicksLeft = 0; } public void StepGlide() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) if (GlideTicksLeft > 0) { Position = Vector2.Lerp(Position, GlideTarget, 1f / (float)GlideTicksLeft); GlideTicksLeft--; if (GlideTicksLeft == 0) { Position = GlideTarget; } } } } internal sealed class BoundControl { public Key Key; public int MouseButton = -1; public int Scroll; } public sealed class InputPatcher { private struct ActionBinding { public TasButtons Flag; public string Action; public string Part; public ActionBinding(TasButtons flag, string action, string part) { Flag = flag; Action = action; Part = part; } } private sealed class ActionAccessor { public string Name; public MemberInfo SourceMember; public MemberInfo PressedMember; public MemberInfo PerformedMember; public bool Resolved; } public readonly TasMouse Pointer = new TasMouse(); private static readonly ActionBinding[] ActionBindings = new ActionBinding[29] { new ActionBinding(TasButtons.Forward, "Movement/Move", "up"), new ActionBinding(TasButtons.Back, "Movement/Move", "down"), new ActionBinding(TasButtons.Left, "Movement/Move", "left"), new ActionBinding(TasButtons.Right, "Movement/Move", "right"), new ActionBinding(TasButtons.Jump, "Movement/Jump", null), new ActionBinding(TasButtons.Slide, "Movement/Slide", null), new ActionBinding(TasButtons.Dash, "Movement/Dodge", null), new ActionBinding(TasButtons.Fire1, "Weapon/PrimaryFire", null), new ActionBinding(TasButtons.Fire2, "Weapon/SecondaryFire", null), new ActionBinding(TasButtons.Punch, "Fist/Punch", null), new ActionBinding(TasButtons.Whiplash, "Fist/Hook", null), new ActionBinding(TasButtons.Slot1, "Weapon/Revolver", null), new ActionBinding(TasButtons.Slot2, "Weapon/Shotgun", null), new ActionBinding(TasButtons.Slot3, "Weapon/Nailgun", null), new ActionBinding(TasButtons.Slot4, "Weapon/Railcannon", null), new ActionBinding(TasButtons.Slot5, "Weapon/Rocket Launcher", null), new ActionBinding(TasButtons.Slot6, "Weapon/Spawner Arm", null), new ActionBinding(TasButtons.FistChange, "Fist/ChangeFist", null), new ActionBinding(TasButtons.FistFeedbacker, "Fist/PunchFeedbacker", null), new ActionBinding(TasButtons.FistKnuckleblaster, "Fist/PunchKnuckleblaster", null), new ActionBinding(TasButtons.WeaponNext, "Weapon/NextWeapon", null), new ActionBinding(TasButtons.WeaponPrev, "Weapon/PreviousWeapon", null), new ActionBinding(TasButtons.WeaponLast, "Weapon/LastUsedWeapon", null), new ActionBinding(TasButtons.VariationNext, "Weapon/NextVariation", null), new ActionBinding(TasButtons.VariationPrev, "Weapon/PreviousVariation", null), new ActionBinding(TasButtons.Variant1, "Weapon/VariationSlot1", null), new ActionBinding(TasButtons.Variant2, "Weapon/VariationSlot2", null), new ActionBinding(TasButtons.Variant3, "Weapon/VariationSlot3", null), new ActionBinding(TasButtons.Stats, "HUD/Stats", null) }; private readonly Dictionary> _bound = new Dictionary>(); private bool _boundFromAsset; private int _boundBuildFrame = -100000; public static InputPatcher Instance; private readonly Plugin _plugin; private readonly GameBridge _bridge; private Harmony _harmony; private bool _active; private bool _hasAngles; private bool _freeLook; private bool _freecam; private bool _staging; private int _lastFreeLookFrame = -1; private int _lastFreecamFrame = -1; private float _freecamRealStamp = -1f; private Vector3 _freecamPosition; private float _freecamPitch; private float _freecamYaw; private Transform _freecamCamera; private bool _holdAngles; private float _holdPitch; private float _holdYaw; private TasButtons _stagedButtons; private float _stagedPitch; private float _stagedYaw; private float _pitch; private float _yaw; private TasButtons _buttons; private bool _menuConfirmWasDown; private bool _menuCancelWasDown; private bool _menuPauseWasDown; private bool _menuUpWasDown; private bool _menuDownWasDown; private bool _menuLeftWasDown; private bool _menuRightWasDown; private bool _confirmDown; private bool _cancelDown; private bool _pauseDown; private bool _upDown; private bool _downDown; private bool _leftDown; private bool _rightDown; private object _cachedSource; private readonly Dictionary _accessors = new Dictionary(StringComparer.Ordinal); private Dictionary _bindings; private int _lastBindingRefreshFrame = -1000; private bool _legacyUiPatched; private bool _cameraPatched; private bool _legacyUiAttempted; private bool _cameraAttempted; private int _lastPatchAttemptFrame = -1000; private readonly bool[] _mouseButtonScratch = new bool[5]; private bool _warpFailed; private readonly List _keyBuffer = new List(16); private bool _inputSystemUpdateFailed; private static readonly Dictionary ActionNames = new Dictionary { { TasButtons.Forward, new string[4] { "W", "Forward", "MoveForward", "Up" } }, { TasButtons.Back, new string[4] { "S", "Back", "MoveBack", "Down" } }, { TasButtons.Left, new string[3] { "A", "Left", "MoveLeft" } }, { TasButtons.Right, new string[3] { "D", "Right", "MoveRight" } }, { TasButtons.Jump, new string[1] { "Jump" } }, { TasButtons.Slide, new string[1] { "Slide" } }, { TasButtons.Dash, new string[2] { "Dodge", "Dash" } }, { TasButtons.Fire1, new string[3] { "Fire1", "Fire", "Shoot" } }, { TasButtons.Fire2, new string[3] { "Fire2", "AltFire", "SecondaryFire" } }, { TasButtons.Punch, new string[2] { "Punch", "Fist" } }, { TasButtons.Whiplash, new string[2] { "Hook", "Whiplash" } }, { TasButtons.Slot1, new string[1] { "Slot1" } }, { TasButtons.Slot2, new string[1] { "Slot2" } }, { TasButtons.Slot3, new string[1] { "Slot3" } }, { TasButtons.Slot4, new string[1] { "Slot4" } }, { TasButtons.Slot5, new string[1] { "Slot5" } }, { TasButtons.Slot6, new string[1] { "Slot6" } }, { TasButtons.FistChange, new string[1] { "ChangeFist" } }, { TasButtons.FistFeedbacker, new string[1] { "PunchFeedbacker" } }, { TasButtons.FistKnuckleblaster, new string[1] { "PunchKnuckleblaster" } }, { TasButtons.WeaponNext, new string[1] { "NextWeapon" } }, { TasButtons.WeaponPrev, new string[1] { "PrevWeapon" } }, { TasButtons.WeaponLast, new string[1] { "LastWeapon" } }, { TasButtons.VariationNext, new string[1] { "NextVariation" } }, { TasButtons.VariationPrev, new string[1] { "PreviousVariation" } }, { TasButtons.Variant1, new string[1] { "SelectVariant1" } }, { TasButtons.Variant2, new string[1] { "SelectVariant2" } }, { TasButtons.Variant3, new string[1] { "SelectVariant3" } }, { TasButtons.Stats, new string[1] { "Stats" } } }; private static readonly TasButtons[] AllActionButtons = new TasButtons[29] { TasButtons.Forward, TasButtons.Back, TasButtons.Left, TasButtons.Right, TasButtons.Jump, TasButtons.Slide, TasButtons.Dash, TasButtons.Fire1, TasButtons.Fire2, TasButtons.Punch, TasButtons.Whiplash, TasButtons.Slot1, TasButtons.Slot2, TasButtons.Slot3, TasButtons.Slot4, TasButtons.Slot5, TasButtons.Slot6, TasButtons.FistChange, TasButtons.FistFeedbacker, TasButtons.FistKnuckleblaster, TasButtons.WeaponNext, TasButtons.WeaponPrev, TasButtons.WeaponLast, TasButtons.VariationNext, TasButtons.VariationPrev, TasButtons.Variant1, TasButtons.Variant2, TasButtons.Variant3, TasButtons.Stats }; private const TasButtons AlwaysRepeatPress = TasButtons.Slot1 | TasButtons.Slot2 | TasButtons.Slot3 | TasButtons.Slot4 | TasButtons.Slot5 | TasButtons.Slot6 | TasButtons.FistChange | TasButtons.Variant1 | TasButtons.Variant2 | TasButtons.Variant3; private static readonly TasButtons[] SlotButtons = new TasButtons[6] { TasButtons.Slot1, TasButtons.Slot2, TasButtons.Slot3, TasButtons.Slot4, TasButtons.Slot5, TasButtons.Slot6 }; public TasButtons LiveButtons { get; private set; } public Vector2 LiveMousePosition { get; private set; } public bool LiveMouseLeft { get; private set; } public bool LiveMouseRight { get; private set; } public bool LiveMouseMiddle { get; private set; } public bool HardwareBlocked => KeyUtil.GuiCapturesInput; public bool HasAngles => _hasAngles; public float CurrentPitch => _pitch; public float CurrentYaw => _yaw; public TasButtons CurrentButtons => _buttons; public bool IsActive => _active; public bool FreeLookActive => _freeLook; public bool FreecamActive => _freecam; public bool FreecamAttached { get { if (_freecam) { return (Object)(object)_freecamCamera != (Object)null; } return false; } } public TasButtons StagedButtons => _stagedButtons; public float StagedPitch => _stagedPitch; public float StagedYaw => _stagedYaw; public bool LegacyUiPatched => _legacyUiPatched; public bool CameraPatched => _cameraPatched; public TasButtons HeldButtons => _buttons; private void EnsureBound() { if (Time.frameCount - _boundBuildFrame < (_boundFromAsset ? 600 : 60) && _bound.Count > 0) { return; } _boundBuildFrame = Time.frameCount; InputActionAsset val = FindActionAsset(); _bound.Clear(); _boundFromAsset = (Object)(object)val != (Object)null; for (int i = 0; i < ActionBindings.Length; i++) { ActionBinding entry = ActionBindings[i]; if (!_bound.TryGetValue(entry.Flag, out var value)) { value = new List(2); _bound[entry.Flag] = value; } if ((Object)(object)val != (Object)null) { CollectBindings(val, entry, value); } if (value.Count == 0) { AddFallback(entry.Flag, value); } } } private InputActionAsset FindActionAsset() { try { object inputSource = _bridge.InputSource; if (inputSource != null) { object member = _bridge.GetMember(inputSource, new string[1] { "Actions" }); object member2 = _bridge.GetMember(member, new string[2] { "asset", "k__BackingField" }); InputActionAsset val = (InputActionAsset)((member2 is InputActionAsset) ? member2 : null); if ((Object)(object)val != (Object)null) { return val; } } object inputManager = _bridge.InputManager; if (inputManager != null) { object member3 = _bridge.GetMember(inputManager, new string[1] { "defaultActions" }); return (InputActionAsset)((member3 is InputActionAsset) ? member3 : null); } } catch (Exception ex) { _plugin.LogWarning("Could not read the input action asset: " + ex.Message); } return null; } private static void CollectBindings(InputActionAsset asset, ActionBinding entry, List into) { //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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) InputAction val = asset.FindAction(entry.Action, false); if (val == null) { return; } ReadOnlyArray bindings = val.bindings; for (int i = 0; i < bindings.Count; i++) { InputBinding val2 = bindings[i]; if (((InputBinding)(ref val2)).isComposite) { continue; } if (entry.Part != null) { if (!((InputBinding)(ref val2)).isPartOfComposite || !string.Equals(((InputBinding)(ref val2)).name, entry.Part, StringComparison.OrdinalIgnoreCase)) { continue; } } else if (((InputBinding)(ref val2)).isPartOfComposite) { continue; } BoundControl boundControl = ParseControlPath(((InputBinding)(ref val2)).effectivePath); if (boundControl != null) { into.Add(boundControl); } } } private static BoundControl ParseControlPath(string path) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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) if (string.IsNullOrEmpty(path)) { return null; } if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { Key val = ResolveKey(path.Substring("/".Length)); if ((int)val != 0) { return new BoundControl { Key = val }; } return null; } if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { switch (path.Substring("/".Length).ToLowerInvariant()) { case "leftbutton": return new BoundControl { MouseButton = 0 }; case "rightbutton": return new BoundControl { MouseButton = 1 }; case "middlebutton": return new BoundControl { MouseButton = 2 }; case "forwardbutton": return new BoundControl { MouseButton = 3 }; case "backbutton": return new BoundControl { MouseButton = 4 }; case "scroll/up": return new BoundControl { Scroll = 1 }; case "scroll/down": return new BoundControl { Scroll = -1 }; } } return null; } private static Key ResolveKey(string name) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) switch (name.ToLowerInvariant()) { case "shift": return (Key)51; case "ctrl": return (Key)55; case "alt": return (Key)53; default: { Keyboard current = Keyboard.current; if (current == null) { return (Key)0; } try { KeyControl val = ((InputControl)current).TryGetChildControl(name); return (Key)((val != null) ? ((int)val.keyCode) : 0); } catch { return (Key)0; } } } } private void AddFallback(TasButtons flag, List into) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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) //IL_0015: Invalid comparison between Unknown and I4 //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected I4, but got Unknown KeyCode val = FallbackKey(flag); if ((int)val >= 323 && (int)val <= 329) { into.Add(new BoundControl { MouseButton = val - 323 }); return; } Key val2 = ToInputSystemKey(val); if ((int)val2 != 0) { into.Add(new BoundControl { Key = val2 }); } } private List BoundFor(TasButtons flag) { if (!_bound.TryGetValue(flag, out var value)) { return null; } return value; } private static bool IsMouseButtonDown(Mouse mouse, int button) { return button switch { 0 => mouse.leftButton.isPressed, 1 => mouse.rightButton.isPressed, 2 => mouse.middleButton.isPressed, 3 => mouse.forwardButton.isPressed, 4 => mouse.backButton.isPressed, _ => false, }; } private TasButtons ReadBoundButtons() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) EnsureBound(); TasButtons tasButtons = TasButtons.None; Keyboard current = Keyboard.current; Mouse val = Mouse_Current(); float num = ((val != null) ? ((InputControl)(object)val.scroll).ReadValue().y : 0f); for (int i = 0; i < ActionBindings.Length; i++) { TasButtons flag = ActionBindings[i].Flag; if ((tasButtons & flag) != TasButtons.None) { continue; } List list = BoundFor(flag); if (list == null) { continue; } for (int j = 0; j < list.Count; j++) { BoundControl boundControl = list[j]; bool flag2 = false; if ((int)boundControl.Key != 0 && current != null) { flag2 = ((ButtonControl)current[boundControl.Key]).isPressed; } else if (boundControl.MouseButton >= 0 && val != null) { flag2 = IsMouseButtonDown(val, boundControl.MouseButton); } else if (boundControl.Scroll > 0) { flag2 = num > 0.01f; } else if (boundControl.Scroll < 0) { flag2 = num < -0.01f; } if (flag2) { tasButtons |= flag; break; } } } return tasButtons; } private static Mouse Mouse_Current() { return Mouse.current; } public void UpdateLive() { //IL_0012: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) TasButtons tasButtons = ReadBoundButtons(); if (KeyUtil.Held(_plugin.MenuUpKey.Value)) { tasButtons |= TasButtons.MenuUp; } if (KeyUtil.Held(_plugin.MenuDownKey.Value)) { tasButtons |= TasButtons.MenuDown; } if (KeyUtil.Held(_plugin.MenuLeftKey.Value)) { tasButtons |= TasButtons.MenuLeft; } if (KeyUtil.Held(_plugin.MenuRightKey.Value)) { tasButtons |= TasButtons.MenuRight; } if (KeyUtil.Held(_plugin.MenuConfirmKey.Value)) { tasButtons |= TasButtons.MenuConfirm; } if (KeyUtil.Held(_plugin.MenuCancelKey.Value)) { tasButtons |= TasButtons.MenuCancel; } if (KeyUtil.Held((KeyCode)27)) { tasButtons |= TasButtons.MenuPause; } LiveButtons = tasButtons; Mouse val = Mouse_Current(); if (val != null) { LiveMousePosition = ((InputControl)(object)((Pointer)val).position).ReadValue(); LiveMouseLeft = val.leftButton.isPressed; LiveMouseRight = val.rightButton.isPressed; LiveMouseMiddle = val.middleButton.isPressed; } } public string DescribeBindings() { //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) EnsureBound(); StringBuilder stringBuilder = new StringBuilder(512); stringBuilder.Append("Input bindings (").Append(_boundFromAsset ? "from the game's action asset" : "defaults, asset not found").Append("):"); for (int i = 0; i < ActionBindings.Length; i++) { List list = BoundFor(ActionBindings[i].Flag); stringBuilder.Append("\n ").Append(ActionBindings[i].Flag).Append(" <- "); if (list == null || list.Count == 0) { stringBuilder.Append("(none)"); continue; } for (int j = 0; j < list.Count; j++) { if (j > 0) { stringBuilder.Append(", "); } BoundControl boundControl = list[j]; if ((int)boundControl.Key != 0) { stringBuilder.Append(boundControl.Key); } else if (boundControl.MouseButton >= 0) { stringBuilder.Append("Mouse").Append(boundControl.MouseButton); } else { stringBuilder.Append((boundControl.Scroll > 0) ? "WheelUp" : "WheelDown"); } } } return stringBuilder.ToString(); } public InputPatcher(Plugin plugin, GameBridge bridge) { _plugin = plugin; _bridge = bridge; Instance = this; } public void Initialize() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _harmony = new Harmony("com.tas.ultrakill.input"); TryPatchLegacyUi(); TryPatchGameHooks(); } public void Shutdown() { EndFreecam(); EndFreeLook(); ReleaseAll(); if (_harmony != null) { _harmony.UnpatchSelf(); } } public void SetActive(bool active) { if (!active) { ReleaseControl(); return; } EndFreeLook(); _active = true; _hasAngles = false; RefreshBindings(force: true); } public void ReleaseControl() { _freeLook = false; _staging = false; _active = false; _hasAngles = false; ReleaseAll(); } public void BeginFreeLook(float pitch, float yaw) { if (_freeLook) { _stagedPitch = _pitch; _stagedYaw = _yaw; return; } ReleaseControl(); _freeLook = true; _staging = true; _pitch = Mathf.Clamp(pitch, -89.9f, 89.9f); _yaw = yaw; _stagedPitch = _pitch; _stagedYaw = _yaw; _stagedButtons = TasButtons.None; _lastFreeLookFrame = -1; _buttons = TasButtons.None; ApplyActionStates(TasButtons.None); ApplyDeviceState(TasButtons.None); TryPatchGameHooks(); } public void EndFreeLook() { _freeLook = false; _staging = false; _stagedButtons = TasButtons.None; } public bool BeginFreecam() { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) if (_freecam) { return true; } if (!_bridge.TryGetCameraTransform(out var transform) || (Object)(object)transform == (Object)null) { return false; } TryPatchGameHooks(); _freecam = true; _lastFreecamFrame = -1; _freecamRealStamp = -1f; _freecamCamera = transform; _freecamPosition = transform.position; Vector3 eulerAngles = transform.eulerAngles; _freecamPitch = ((eulerAngles.x > 180f) ? (eulerAngles.x - 360f) : eulerAngles.x); _freecamYaw = eulerAngles.y; return true; } public void EndFreecam() { if (_freecam) { _freecam = false; _freecamCamera = null; } } public bool TryGetFreecamPose(out Vector3 position, out Quaternion rotation) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) position = _freecamPosition; rotation = Quaternion.Euler(_freecamPitch, _freecamYaw, 0f); if (_freecam) { return (Object)(object)_freecamCamera != (Object)null; } return false; } private void ReadUserMouseDelta(out float mouseX, out float mouseY) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) mouseX = 0f; mouseY = 0f; try { mouseX = Input.GetAxisRaw("Mouse X"); mouseY = Input.GetAxisRaw("Mouse Y"); } catch (Exception) { } if (!_active && Mathf.Abs(mouseX) < 1E-05f && Mathf.Abs(mouseY) < 1E-05f && Mouse.current != null) { Vector2 val = ((InputControl)(object)((Pointer)Mouse.current).delta).ReadValue(); mouseX = val.x; mouseY = val.y; } } private bool FreecamKeyHeld(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return KeyUtil.UserHeld(key, !_active); } public void ToggleFreecam() { if (_freecam) { EndFreecam(); } else { BeginFreecam(); } } private void ApplyFreecam() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Invalid comparison between Unknown and I4 //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: 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_0152: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_015e: 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_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0179: 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_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_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018a: 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_0196: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: 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_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) if (_lastFreecamFrame == SimulationFreeze.FrameCount) { return; } _lastFreecamFrame = SimulationFreeze.FrameCount; if (_bridge.TryGetCameraTransform(out var transform) && !((Object)(object)transform == (Object)null)) { if ((Object)(object)transform != (Object)(object)_freecamCamera) { _freecamCamera = transform; _freecamRealStamp = -1f; } if ((int)Cursor.lockState == 1 && !HardwareBlocked) { ReadUserMouseDelta(out var mouseX, out var mouseY); float num = Mathf.Max(0.01f, _plugin.FreeLookSensitivity.Value); _freecamYaw += mouseX * num; _freecamPitch = Mathf.Clamp(_freecamPitch - mouseY * num, -89.9f, 89.9f); } float num2 = Mathf.Max(0.1f, _plugin.FreecamSpeed.Value); if (FreecamKeyHeld((KeyCode)304) || FreecamKeyHeld((KeyCode)303)) { num2 *= 4f; } if (FreecamKeyHeld((KeyCode)306) || FreecamKeyHeld((KeyCode)305)) { num2 *= 0.25f; } Quaternion val = Quaternion.Euler(_freecamPitch, _freecamYaw, 0f); Vector3 val2 = Vector3.zero; if (FreecamKeyHeld((KeyCode)119)) { val2 += val * Vector3.forward; } if (FreecamKeyHeld((KeyCode)115)) { val2 -= val * Vector3.forward; } if (FreecamKeyHeld((KeyCode)100)) { val2 += val * Vector3.right; } if (FreecamKeyHeld((KeyCode)97)) { val2 -= val * Vector3.right; } if (FreecamKeyHeld((KeyCode)32)) { val2 += Vector3.up; } if (FreecamKeyHeld((KeyCode)113)) { val2 -= Vector3.up; } if (((Vector3)(ref val2)).sqrMagnitude > 1f) { ((Vector3)(ref val2)).Normalize(); } float realTime = TimeController.RealTime; float num3 = ((_freecamRealStamp < 0f) ? 0f : Mathf.Clamp(realTime - _freecamRealStamp, 0f, 0.1f)); _freecamRealStamp = realTime; _freecamPosition += val2 * num2 * num3; } } public void UpdateStaging() { if (_freeLook) { TryPatchGameHooks(); _stagedButtons = ReadPhysicalButtonsLegacy(); _stagedPitch = _pitch; _stagedYaw = _yaw; } } public void CaptureStaged(out TasButtons buttons, out float pitch, out float yaw) { UpdateStaging(); buttons = (_freeLook ? _stagedButtons : _buttons); pitch = (_freeLook ? _stagedPitch : _pitch); yaw = (_freeLook ? _stagedYaw : _yaw); } public void ApplyFrame(TasButtons buttons, float pitch, float yaw) { ApplyFrame(buttons, TasButtons.None, pitch, yaw); } public void ApplyFrame(TasButtons buttons, TasButtons repeatPress, float pitch, float yaw) { repeatPress |= TasButtons.Slot1 | TasButtons.Slot2 | TasButtons.Slot3 | TasButtons.Slot4 | TasButtons.Slot5 | TasButtons.Slot6 | TasButtons.FistChange | TasButtons.Variant1 | TasButtons.Variant2 | TasButtons.Variant3; TasButtons buttons2 = _buttons; _buttons = buttons; _pitch = Mathf.Clamp(pitch, -89.9f, 89.9f); _yaw = yaw; _hasAngles = true; ComputeMenuEdges(buttons); if (_active || HardwareBlocked) { TryPatchGameHooks(); ApplyDeviceState(buttons); ApplyActionStates(buttons, buttons & buttons2 & ~repeatPress); } } public void RestoreHeldState(TasButtons buttons) { _buttons = buttons; if (_active || HardwareBlocked) { ApplyDeviceState(buttons); ApplyActionStates(buttons, buttons); } } public void InjectNeutral() { if (_active || HardwareBlocked) { _buttons = TasButtons.None; ComputeMenuEdges(TasButtons.None); ApplyActionStates(TasButtons.None); ApplyDeviceState(TasButtons.None); } } public void OnGuiCaptureEnded() { _holdAngles = false; if (!_active) { ReleaseAll(); } } public void OnGuiCaptureBegan() { _holdAngles = _bridge.TryGetCameraAngles(out var pitch, out var yaw); _holdPitch = pitch; _holdYaw = yaw; } public void OnSceneChanged() { _holdAngles = false; } public void ReleaseAll() { _buttons = TasButtons.None; ComputeMenuEdges(TasButtons.None); ApplyActionStates(TasButtons.None); ApplyDeviceState(TasButtons.None); } private void ComputeMenuEdges(TasButtons buttons) { bool flag = Has(buttons, TasButtons.MenuConfirm); bool flag2 = Has(buttons, TasButtons.MenuCancel); bool flag3 = Has(buttons, TasButtons.MenuPause); bool flag4 = Has(buttons, TasButtons.MenuUp); bool flag5 = Has(buttons, TasButtons.MenuDown); bool flag6 = Has(buttons, TasButtons.MenuLeft); bool flag7 = Has(buttons, TasButtons.MenuRight); _confirmDown = flag && !_menuConfirmWasDown; _cancelDown = flag2 && !_menuCancelWasDown; _pauseDown = flag3 && !_menuPauseWasDown; _upDown = flag4 && !_menuUpWasDown; _downDown = flag5 && !_menuDownWasDown; _leftDown = flag6 && !_menuLeftWasDown; _rightDown = flag7 && !_menuRightWasDown; _menuConfirmWasDown = flag; _menuCancelWasDown = flag2; _menuPauseWasDown = flag3; _menuUpWasDown = flag4; _menuDownWasDown = flag5; _menuLeftWasDown = flag6; _menuRightWasDown = flag7; } private static bool Has(TasButtons value, TasButtons flag) { return (value & flag) != 0; } private void ApplyActionStates(TasButtons buttons) { ApplyActionStates(buttons, TasButtons.None); } private void ApplyActionStates(TasButtons buttons, TasButtons suppressEdges) { object inputSource = _bridge.InputSource; if (inputSource == null) { return; } if (inputSource != _cachedSource) { _cachedSource = inputSource; _accessors.Clear(); } for (int i = 0; i < AllActionButtons.Length; i++) { TasButtons tasButtons = AllActionButtons[i]; string[] array = ActionNames[tasButtons]; if (!_accessors.TryGetValue(array[0], out var value)) { value = new ActionAccessor { Name = array[0] }; _accessors[array[0]] = value; } bool pressed = Has(buttons, tasButtons); WriteActionState(value, inputSource, array, pressed, Has(suppressEdges, tasButtons)); } } private void WriteActionState(ActionAccessor accessor, object source, string[] candidateNames, bool pressed, bool suppressEdge) { try { if (!accessor.Resolved) { for (int i = 0; i < candidateNames.Length; i++) { MemberInfo memberInfo = _bridge.FindMember(source.GetType(), candidateNames[i]); if (memberInfo == null) { continue; } object memberValue = _bridge.GetMemberValue(source, memberInfo); if (memberValue != null) { Type type = memberValue.GetType(); MemberInfo memberInfo2 = _bridge.FindMember(type, "IsPressed") ?? _bridge.FindMember(type, "Pressed"); if (!(memberInfo2 == null)) { accessor.SourceMember = memberInfo; accessor.PressedMember = memberInfo2; accessor.PerformedMember = _bridge.FindMember(type, "PerformedFrame") ?? _bridge.FindMember(type, "PerformedThisFrame") ?? _bridge.FindMember(type, "PressFrame"); accessor.Name = candidateNames[i]; accessor.Resolved = true; break; } } } } if (!accessor.Resolved) { return; } object memberValue2 = _bridge.GetMemberValue(source, accessor.SourceMember); if (memberValue2 != null) { _bridge.SetMemberValue(memberValue2, accessor.PressedMember, pressed); if (pressed && !suppressEdge && accessor.PerformedMember != null) { int num = Time.frameCount + _plugin.PerformedFrameOffset.Value; _bridge.SetMemberValue(memberValue2, accessor.PerformedMember, num); } FieldInfo fieldInfo = accessor.SourceMember as FieldInfo; if (fieldInfo != null && memberValue2.GetType().IsValueType) { fieldInfo.SetValue(source, memberValue2); } } } catch (Exception ex) { _plugin.LogWarning("InputSource write failed for " + accessor.Name + ": " + ex.Message); } } private bool ReadActionState(string[] candidateNames) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) object inputSource = _bridge.InputSource; if (inputSource != null) { for (int i = 0; i < candidateNames.Length; i++) { object member = _bridge.GetMember(inputSource, new string[1] { candidateNames[i] }); if (member != null) { object member2 = _bridge.GetMember(member, new string[2] { "IsPressed", "Pressed" }); if (member2 != null) { return GameBridge.ToBool(member2, fallback: false); } } } } RefreshBindings(force: false); if (_bindings != null) { for (int j = 0; j < candidateNames.Length; j++) { if (_bindings.TryGetValue(candidateNames[j], out var value)) { return KeyUtil.GameHeld(value); } } } return false; } public TasButtons ReadPhysicalButtons() { TasButtons tasButtons = TasButtons.None; if (!HardwareBlocked) { for (int i = 0; i < AllActionButtons.Length; i++) { TasButtons tasButtons2 = AllActionButtons[i]; if (ReadActionState(ActionNames[tasButtons2])) { tasButtons |= tasButtons2; } } tasButtons |= ReadBoundButtons(); } return tasButtons | ReadMenuKeys(); } private TasButtons ReadMenuKeys() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) TasButtons tasButtons = TasButtons.None; if (KeyUtil.GameHeld(_plugin.MenuUpKey.Value)) { tasButtons |= TasButtons.MenuUp; } if (KeyUtil.GameHeld(_plugin.MenuDownKey.Value)) { tasButtons |= TasButtons.MenuDown; } if (KeyUtil.GameHeld(_plugin.MenuLeftKey.Value)) { tasButtons |= TasButtons.MenuLeft; } if (KeyUtil.GameHeld(_plugin.MenuRightKey.Value)) { tasButtons |= TasButtons.MenuRight; } if (KeyUtil.GameHeld(_plugin.MenuConfirmKey.Value)) { tasButtons |= TasButtons.MenuConfirm; } if (KeyUtil.GameHeld(_plugin.MenuCancelKey.Value)) { tasButtons |= TasButtons.MenuCancel; } if (KeyUtil.GameHeld((KeyCode)27)) { tasButtons |= TasButtons.MenuPause; } return tasButtons; } public TasButtons ReadPhysicalButtonsLegacy() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) TasButtons tasButtons = TasButtons.None; if (!HardwareBlocked) { RefreshBindings(force: false); for (int i = 0; i < AllActionButtons.Length; i++) { TasButtons tasButtons2 = AllActionButtons[i]; if (IsBoundHeld(ActionNames[tasButtons2], FallbackKey(tasButtons2))) { tasButtons |= tasButtons2; } } tasButtons |= ReadBoundButtons(); } return tasButtons | ReadMenuKeys(); } public int ReadHeldSlotRaw() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) RefreshBindings(force: false); for (int i = 0; i < SlotButtons.Length; i++) { if (IsBoundHeld(ActionNames[SlotButtons[i]], FallbackKey(SlotButtons[i]), raw: true)) { return i + 1; } } return 0; } private bool IsBoundHeld(string[] names, KeyCode fallback) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return IsBoundHeld(names, fallback, raw: false); } private bool IsBoundHeld(string[] names, KeyCode fallback, bool raw) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (_bindings != null) { for (int i = 0; i < names.Length; i++) { if (_bindings.TryGetValue(names[i], out var value) && (int)value != 0 && (raw ? KeyUtil.Held(value) : KeyUtil.GameHeld(value))) { return true; } } } if ((int)fallback != 0) { if (!raw) { return KeyUtil.GameHeld(fallback); } return KeyUtil.Held(fallback); } return false; } private static KeyCode FallbackKey(TasButtons button) { switch (button) { case TasButtons.None: case TasButtons.Forward: case TasButtons.Back: case TasButtons.Forward | TasButtons.Back: case TasButtons.Left: case TasButtons.Forward | TasButtons.Left: case TasButtons.Back | TasButtons.Left: case TasButtons.Forward | TasButtons.Back | TasButtons.Left: case TasButtons.Right: { TasButtons num = button - 1; if (num <= (TasButtons.Forward | TasButtons.Back)) { switch (num) { case TasButtons.None: return (KeyCode)119; case TasButtons.Forward: return (KeyCode)115; case TasButtons.Forward | TasButtons.Back: return (KeyCode)97; case TasButtons.Back: goto end_IL_0007; } } if (button != TasButtons.Right) { break; } return (KeyCode)100; } case TasButtons.Jump: return (KeyCode)32; case TasButtons.Slide: return (KeyCode)306; case TasButtons.Dash: return (KeyCode)304; case TasButtons.Fire1: return (KeyCode)323; case TasButtons.Fire2: return (KeyCode)324; case TasButtons.Punch: return (KeyCode)102; case TasButtons.Whiplash: return (KeyCode)101; case TasButtons.Slot1: return (KeyCode)49; case TasButtons.Slot2: return (KeyCode)50; case TasButtons.Slot3: return (KeyCode)51; case TasButtons.Slot4: return (KeyCode)52; case TasButtons.Slot5: return (KeyCode)53; case TasButtons.Slot6: return (KeyCode)54; case TasButtons.Stats: { return (KeyCode)9; } end_IL_0007: break; } return (KeyCode)0; } private void RefreshBindings(bool force) { if (force || _bindings == null || Time.frameCount - _lastBindingRefreshFrame >= 120) { _lastBindingRefreshFrame = Time.frameCount; Dictionary inputBindings = _bridge.InputBindings; if (inputBindings != null) { _bindings = inputBindings; } } } private void ApplyDeviceState(TasButtons buttons) { //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0140: 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_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: 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_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0379: Unknown result type (might be due to invalid IL or missing references) if (!_plugin.InjectDeviceState.Value || (Keyboard.current == null && Mouse.current == null)) { return; } RefreshBindings(force: false); EnsureBound(); _keyBuffer.Clear(); bool[] mouseButtonScratch = _mouseButtonScratch; Array.Clear(mouseButtonScratch, 0, mouseButtonScratch.Length); float num = 0f; for (int i = 0; i < AllActionButtons.Length; i++) { TasButtons flag = AllActionButtons[i]; if (!Has(buttons, flag)) { continue; } List list = BoundFor(flag); if (list == null) { continue; } for (int j = 0; j < list.Count; j++) { BoundControl boundControl = list[j]; if ((int)boundControl.Key != 0) { AddKey(boundControl.Key); } else if (boundControl.MouseButton >= 0 && boundControl.MouseButton < mouseButtonScratch.Length) { mouseButtonScratch[boundControl.MouseButton] = true; } else if (boundControl.Scroll != 0) { num += (float)boundControl.Scroll * 120f; } } } if (Has(buttons, TasButtons.MenuUp)) { AddKey(_plugin.MenuUpKey.Value); } if (Has(buttons, TasButtons.MenuDown)) { AddKey(_plugin.MenuDownKey.Value); } if (Has(buttons, TasButtons.MenuLeft)) { AddKey(_plugin.MenuLeftKey.Value); } if (Has(buttons, TasButtons.MenuRight)) { AddKey(_plugin.MenuRightKey.Value); } if (Has(buttons, TasButtons.MenuConfirm)) { AddKey(_plugin.MenuConfirmKey.Value); } if (Has(buttons, TasButtons.MenuCancel)) { AddKey(_plugin.MenuCancelKey.Value); } if (Has(buttons, TasButtons.MenuPause)) { AddKey((KeyCode)27); } if (HardwareBlocked && !_active && KeyUtil.GameHeld((KeyCode)27)) { AddKey((KeyCode)27); } TasMouse pointer = Pointer; if (pointer.Active) { mouseButtonScratch[0] |= pointer.Left; mouseButtonScratch[1] |= pointer.Right; mouseButtonScratch[2] |= pointer.Middle; num += pointer.Scroll * 120f; } try { Keyboard current = Keyboard.current; if (current != null) { KeyboardState val = ((_keyBuffer.Count == 0) ? default(KeyboardState) : new KeyboardState(_keyBuffer.ToArray())); InputSystem.QueueStateEvent((InputDevice)(object)current, val, -1.0); } Mouse current2 = Mouse.current; if (current2 != null) { Vector2 val2 = (pointer.Active ? pointer.Position : ((InputControl)(object)((Pointer)current2).position).ReadValue()); MouseState val3 = new MouseState { position = val2, delta = Vector2.zero, scroll = new Vector2(0f, num) }; if (mouseButtonScratch[0]) { ((MouseState)(ref val3)).WithButton((MouseButton)0, true); } if (mouseButtonScratch[1]) { ((MouseState)(ref val3)).WithButton((MouseButton)1, true); } if (mouseButtonScratch[2]) { ((MouseState)(ref val3)).WithButton((MouseButton)2, true); } if (mouseButtonScratch[3]) { ((MouseState)(ref val3)).WithButton((MouseButton)3, true); } if (mouseButtonScratch[4]) { ((MouseState)(ref val3)).WithButton((MouseButton)4, true); } InputSystem.QueueStateEvent((InputDevice)(object)current2, val3, -1.0); if (pointer.Active && !_warpFailed) { try { current2.WarpCursorPosition(val2); } catch { _warpFailed = true; } } } if (!_inputSystemUpdateFailed) { InputSystem.Update(); } } catch (Exception ex) { if (!_inputSystemUpdateFailed) { _inputSystemUpdateFailed = true; _plugin.LogWarning("InputSystem injection disabled: " + ex.GetType().Name + ": " + ex.Message); } } } private void AddBoundKey(KeyCode key, ref bool mouseLeft, ref bool mouseRight) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 if ((int)key >= 323 && (int)key <= 329) { if ((int)key == 323) { mouseLeft = true; } else if ((int)key == 324) { mouseRight = true; } } else { AddKey(key); } } private void AddKey(KeyCode keyCode) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) Key val = ToInputSystemKey(keyCode); if ((int)val != 0 && !_keyBuffer.Contains(val)) { _keyBuffer.Add(val); } } internal static Key ToInputSystemKey(KeyCode code) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 //IL_000c: 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) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Invalid comparison between Unknown and I4 //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Invalid comparison between Unknown and I4 //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Invalid comparison between Unknown and I4 //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 //IL_003e: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Invalid comparison between Unknown and I4 //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Invalid comparison between Unknown and I4 //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Invalid comparison between Unknown and I4 //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Invalid comparison between Unknown and I4 //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Invalid comparison between Unknown and I4 //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Invalid comparison between Unknown and I4 //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Expected I4, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Invalid comparison between Unknown and I4 //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Invalid comparison between Unknown and I4 //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Invalid comparison between Unknown and I4 //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Expected I4, but got Unknown //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Invalid comparison between Unknown and I4 //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Invalid comparison between Unknown and I4 //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Invalid comparison between Unknown and I4 //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Expected I4, but got Unknown //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected I4, but got Unknown //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Invalid comparison between Unknown and I4 //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Invalid comparison between Unknown and I4 //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Invalid comparison between Unknown and I4 //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Invalid comparison between Unknown and I4 //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Invalid comparison between Unknown and I4 //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if ((int)code >= 97 && (int)code <= 122) { return (Key)(15 + (code - 97)); } if ((int)code == 48) { return (Key)50; } if ((int)code >= 49 && (int)code <= 57) { return (Key)(41 + (code - 49)); } if ((int)code >= 256 && (int)code <= 265) { return (Key)(84 + (code - 256)); } if ((int)code >= 282 && (int)code <= 293) { return (Key)(94 + (code - 282)); } if ((int)code <= 59) { if ((int)code <= 19) { if ((int)code <= 9) { if ((int)code == 8) { return (Key)65; } if ((int)code == 9) { return (Key)3; } } else { if ((int)code == 13) { return (Key)2; } if ((int)code == 19) { return (Key)76; } } } else if ((int)code <= 32) { if ((int)code == 27) { return (Key)60; } if ((int)code == 32) { return (Key)1; } } else { switch (code - 39) { default: if ((int)code != 59) { break; } return (Key)6; case 5: return (Key)7; case 7: return (Key)8; case 8: return (Key)9; case 0: return (Key)5; case 6: return (Key)13; case 1: case 2: case 3: case 4: break; } } } else if ((int)code <= 96) { if ((int)code <= 91) { if ((int)code == 61) { return (Key)14; } if ((int)code == 91) { return (Key)11; } } else { if ((int)code == 93) { return (Key)12; } if ((int)code == 96) { return (Key)4; } } } else if ((int)code <= 281) { if ((int)code == 127) { return (Key)71; } switch (code - 271) { case 6: return (Key)70; case 7: return (Key)68; case 8: return (Key)69; case 9: return (Key)67; case 10: return (Key)66; case 0: return (Key)77; case 2: return (Key)63; case 3: return (Key)64; case 5: return (Key)61; case 4: return (Key)62; } } else { switch (code - 300) { default: switch (code - 323) { case 0: return (Key)0; case 1: return (Key)0; case 2: return (Key)0; } break; case 0: return (Key)73; case 1: return (Key)72; case 2: return (Key)75; case 16: return (Key)74; case 4: return (Key)51; case 3: return (Key)52; case 6: return (Key)55; case 5: return (Key)56; case 8: return (Key)53; case 7: return (Key)54; case 9: case 10: case 11: case 12: case 13: case 14: case 15: break; } } return (Key)0; } private void AddKey(Key key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if ((int)key != 0 && !_keyBuffer.Contains(key)) { _keyBuffer.Add(key); } } private void TryPatchGameHooks() { if (Time.frameCount - _lastPatchAttemptFrame >= 60) { _lastPatchAttemptFrame = Time.frameCount; if (!_cameraPatched) { TryPatchCamera(); } if (!_legacyUiPatched) { TryPatchLegacyUi(); } } } private void TryPatchCamera() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown if (_cameraPatched || _cameraAttempted) { return; } Type cameraControllerType = _bridge.CameraControllerType; if (cameraControllerType == null) { return; } _cameraAttempted = true; try { MethodInfo method = typeof(InputPatcher).GetMethod("CameraControllerPrefix", BindingFlags.Static | BindingFlags.NonPublic); MethodInfo methodInfo = FindInstanceMethod(cameraControllerType, "LateUpdate"); MethodInfo methodInfo2 = FindInstanceMethod(cameraControllerType, "Update"); bool flag = false; if (methodInfo != null) { _harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); flag = true; } if (methodInfo2 != null && methodInfo2 != methodInfo) { _harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); flag = true; } if (flag) { _cameraPatched = true; _plugin.LogInfo("CameraController angle enforcement patched."); } } catch (Exception ex) { _plugin.LogWarning("CameraController patch failed: " + ex.Message); } } private static MethodInfo FindInstanceMethod(Type type, string name) { try { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); } catch (AmbiguousMatchException) { return null; } } private void TryPatchLegacyUi() { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Expected O, but got Unknown //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown if (_legacyUiPatched || _legacyUiAttempted) { return; } _legacyUiAttempted = true; try { MethodInfo methodInfo = FindBaseInputMethod("GetAxisRaw"); MethodInfo methodInfo2 = FindBaseInputMethod("GetAxis"); MethodInfo methodInfo3 = FindBaseInputMethod("GetButtonDown"); MethodInfo methodInfo4 = FindBaseInputMethod("GetButton"); MethodInfo methodInfo5 = FindBaseInputMethod("GetButtonUp"); if (!(methodInfo == null) && !(methodInfo3 == null)) { _harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(InputPatcher).GetMethod("BaseInputAxisRawPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (methodInfo2 != null && methodInfo2 != methodInfo) { _harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(InputPatcher).GetMethod("BaseInputAxisPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } _harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(InputPatcher).GetMethod("BaseInputButtonDownPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (methodInfo4 != null) { _harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(InputPatcher).GetMethod("BaseInputButtonPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } if (methodInfo5 != null) { _harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(InputPatcher).GetMethod("BaseInputButtonUpPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } _legacyUiPatched = true; _plugin.LogInfo("Legacy uGUI BaseInput patched for menu injection."); } } catch (Exception ex) { _plugin.LogWarning("BaseInput patch failed: " + ex.Message); } } private void ApplyFreeLook() { //IL_0052: 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) float num = 0f; float num2 = 0f; try { num = Input.GetAxisRaw("Mouse X"); num2 = Input.GetAxisRaw("Mouse Y"); } catch (Exception) { } if (Mathf.Abs(num) < 1E-05f && Mathf.Abs(num2) < 1E-05f && Mouse.current != null) { Vector2 val = ((InputControl)(object)((Pointer)Mouse.current).delta).ReadValue(); num = val.x; num2 = val.y; } if (HardwareBlocked) { num = 0f; num2 = 0f; } float num3 = Mathf.Max(0.01f, _plugin.FreeLookSensitivity.Value); _pitch = Mathf.Clamp(_pitch - num2 * num3, -89.9f, 89.9f); _yaw += num * num3; _stagedPitch = _pitch; _stagedYaw = _yaw; _bridge.SetCameraAngles(_pitch, _yaw); _bridge.ApplyCameraTransform(_pitch, _yaw); } private void EnforceCameraAngles() { if (_active && _hasAngles) { _holdAngles = false; if (_plugin.EnforceCameraAngles.Value) { _bridge.SetCameraAngles(_pitch, _yaw); } } else if (HardwareBlocked) { if (!_holdAngles) { OnGuiCaptureBegan(); } if (_holdAngles) { _bridge.SetCameraAngles(_holdPitch, _holdYaw); } } } public void UpdateFrozenCamera() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 if (_freecam) { ApplyFreecam(); } else if (_freeLook && (int)Cursor.lockState == 1 && _lastFreeLookFrame != SimulationFreeze.FrameCount) { _lastFreeLookFrame = SimulationFreeze.FrameCount; ApplyFreeLook(); } } private static bool CameraControllerPrefix() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 InputPatcher instance = Instance; if (instance != null) { if (instance._freecam) { instance.ApplyFreecam(); if (!instance._active) { return false; } instance.EnforceCameraAngles(); return true; } if (instance._freeLook && (int)Cursor.lockState == 1) { if (instance._lastFreeLookFrame != SimulationFreeze.FrameCount) { instance._lastFreeLookFrame = SimulationFreeze.FrameCount; instance.ApplyFreeLook(); } return false; } instance.EnforceCameraAngles(); } return true; } private bool BlockLegacyInput() { if (!_active && !HardwareBlocked) { return _staging; } return true; } private static bool BaseInputAxisRawPrefix(string axisName, ref float __result) { InputPatcher instance = Instance; if (instance == null || !instance.BlockLegacyInput()) { return true; } string text = axisName ?? string.Empty; if (text == "Horizontal") { __result = (Has(instance._buttons, TasButtons.MenuRight) ? 1f : 0f) - (Has(instance._buttons, TasButtons.MenuLeft) ? 1f : 0f); return false; } if (text == "Vertical") { __result = (Has(instance._buttons, TasButtons.MenuUp) ? 1f : 0f) - (Has(instance._buttons, TasButtons.MenuDown) ? 1f : 0f); return false; } return true; } private static bool BaseInputAxisPrefix(string axisName, ref float __result) { return BaseInputAxisRawPrefix(axisName, ref __result); } private static bool BaseInputButtonDownPrefix(string buttonName, ref bool __result) { InputPatcher instance = Instance; if (instance == null || !instance.BlockLegacyInput()) { return true; } string name = buttonName ?? string.Empty; if (IsSubmit(name)) { __result = instance._confirmDown; return false; } if (IsCancel(name)) { __result = instance._cancelDown || instance._pauseDown; return false; } __result = false; return false; } private static bool BaseInputButtonPrefix(string buttonName, ref bool __result) { InputPatcher instance = Instance; if (instance == null || !instance.BlockLegacyInput()) { return true; } string name = buttonName ?? string.Empty; if (IsSubmit(name)) { __result = Has(instance._buttons, TasButtons.MenuConfirm); return false; } if (IsCancel(name)) { __result = Has(instance._buttons, TasButtons.MenuCancel) || Has(instance._buttons, TasButtons.MenuPause); return false; } __result = false; return false; } private static bool BaseInputButtonUpPrefix(string buttonName, ref bool __result) { InputPatcher instance = Instance; if (instance == null || !instance.BlockLegacyInput()) { return true; } string name = buttonName ?? string.Empty; if (IsSubmit(name)) { __result = !Has(instance._buttons, TasButtons.MenuConfirm) && instance._menuConfirmWasDown; return false; } if (IsCancel(name)) { __result = !Has(instance._buttons, TasButtons.MenuCancel) && instance._menuCancelWasDown; return false; } __result = false; return false; } private static MethodInfo FindBaseInputMethod(string name) { try { return typeof(BaseInput).GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(string) }, null); } catch (AmbiguousMatchException) { return null; } } private static bool IsSubmit(string name) { if (!(name == "Submit") && !(name == "Confirm")) { return name == "MenuSubmit"; } return true; } private static bool IsCancel(string name) { if (!(name == "Cancel") && !(name == "Back")) { return name == "MenuCancel"; } return true; } public string Describe() { int num = 0; foreach (KeyValuePair accessor in _accessors) { if (accessor.Value.Resolved) { num++; } } return "TAS input: " + (_active ? "active" : "idle") + ", actions resolved " + num + "/" + AllActionButtons.Length + ", InputSystem " + ((Keyboard.current != null) ? "keyboard ok" : "no keyboard") + ", camera patch " + (_cameraPatched ? "yes" : "no") + ", legacy UI patch " + (_legacyUiPatched ? "yes" : "no"); } } internal static class KeyUtil { private static bool _legacyUnavailable; private static bool _guiOwnsEscape; private static bool _escapeLatch; public static bool LegacyInputWorks => !_legacyUnavailable; public static bool NewKeyboardAvailable => Keyboard.current != null; public static bool GuiCapturesInput { get; private set; } public static void SetGuiCapture(bool captures, bool guiOwnsEscape) { bool flag = captures && Held((KeyCode)27); if (!captures) { _escapeLatch = false; } else if (guiOwnsEscape && flag) { _escapeLatch = true; } else if (!flag) { _escapeLatch = false; } GuiCapturesInput = captures; _guiOwnsEscape = captures && guiOwnsEscape; } public static bool IsBlocked(KeyCode key) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 if (!GuiCapturesInput) { return false; } if ((int)key == 27) { if (!_guiOwnsEscape) { return _escapeLatch; } return true; } return true; } public static bool GameHeld(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (!IsBlocked(key)) { return Held(key); } return false; } public static bool UserHeld(KeyCode key, bool allowInputSystem) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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) if ((int)key == 0 || IsBlocked(key)) { return false; } if (!_legacyUnavailable) { try { return Input.GetKey(key); } catch (Exception) { _legacyUnavailable = true; } } if (allowInputSystem) { return HeldFromInputSystem(key); } return false; } public static bool Held(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if ((int)key == 0) { return false; } if (!_legacyUnavailable) { try { if (Input.GetKey(key)) { return true; } } catch (Exception) { _legacyUnavailable = true; } } return HeldFromInputSystem(key); } public static bool Down(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if ((int)key == 0) { return false; } if (!_legacyUnavailable) { try { if (Input.GetKeyDown(key)) { return true; } } catch (Exception) { _legacyUnavailable = true; } } return DownFromInputSystem(key); } private static bool HeldFromInputSystem(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (IsMouseButton(key)) { Mouse current = Mouse.current; if (current != null) { return MouseButtonControl(current, key).isPressed; } return false; } Keyboard current2 = Keyboard.current; if (current2 == null) { return false; } Key val = InputPatcher.ToInputSystemKey(key); if ((int)val != 0) { return ((ButtonControl)current2[val]).isPressed; } return false; } private static bool IsMouseButton(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 if ((int)key >= 323) { return (int)key <= 329; } return false; } private static ButtonControl MouseButtonControl(Mouse mouse, KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected I4, but got Unknown return (ButtonControl)((key - 323) switch { 0 => mouse.leftButton, 1 => mouse.rightButton, 2 => mouse.middleButton, 3 => mouse.backButton, 4 => mouse.forwardButton, _ => null, }); } private static bool DownFromInputSystem(KeyCode key) { //IL_0000: 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_0033: 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_0039: 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) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (IsMouseButton(key)) { Mouse current = Mouse.current; if (current == null) { return false; } ButtonControl val = MouseButtonControl(current, key); if (val != null) { return val.wasPressedThisFrame; } return false; } Keyboard current2 = Keyboard.current; if (current2 == null) { return false; } Key val2 = InputPatcher.ToInputSystemKey(key); if ((int)val2 != 0) { return ((ButtonControl)current2[val2]).wasPressedThisFrame; } return false; } } public enum OptimBoxKind { Goal, KeepOut, Waypoint } public sealed class OptimBox { public OptimBoxKind Kind; public string Name = string.Empty; public bool Enabled = true; public Vector3 Min; public Vector3 Max; public Vector3 Center => (Min + Max) * 0.5f; public Vector3 Size => Max - Min; public OptimBox(OptimBoxKind kind, Vector3 a, Vector3 b) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) Kind = kind; SetCorners(a, b); } public void SetCorners(Vector3 a, Vector3 b) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) Min = Vector3.Min(a, b); Max = Vector3.Max(a, b); } public bool Contains(Vector3 p) { //IL_0000: 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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (p.x >= Min.x && p.x <= Max.x && p.y >= Min.y && p.y <= Max.y && p.z >= Min.z) { return p.z <= Max.z; } return false; } public float DistanceTo(Vector3 p) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(Mathf.Clamp(p.x, Min.x, Max.x), Mathf.Clamp(p.y, Min.y, Max.y), Mathf.Clamp(p.z, Min.z, Max.z)); return Vector3.Distance(p, val); } public bool SegmentIntersects(Vector3 a, Vector3 b, out float fraction) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) float num = 0f; float num2 = 1f; Vector3 v = b - a; for (int i = 0; i < 3; i++) { float num3 = Component(a, i); float num4 = Component(v, i); float num5 = Component(Min, i); float num6 = Component(Max, i); if (Mathf.Abs(num4) < 1E-09f) { if (num3 < num5 || num3 > num6) { fraction = 0f; return false; } continue; } float num7 = (num5 - num3) / num4; float num8 = (num6 - num3) / num4; if (num7 > num8) { float num9 = num7; num7 = num8; num8 = num9; } num = Mathf.Max(num, num7); num2 = Mathf.Min(num2, num8); if (num > num2) { fraction = 0f; return false; } } fraction = num; return true; } private static float Component(Vector3 v, int axis) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return axis switch { 1 => v.y, 0 => v.x, _ => v.z, }; } public override string ToString() { return Kind.ToString() + " " + (string.IsNullOrEmpty(Name) ? "box" : Name) + " [" + Min.x.ToString("0.##") + "," + Min.y.ToString("0.##") + "," + Min.z.ToString("0.##") + " .. " + Max.x.ToString("0.##") + "," + Max.y.ToString("0.##") + "," + Max.z.ToString("0.##") + "]"; } } public sealed class OptimBoxSet { public readonly List Boxes = new List(); public OptimBox Add(OptimBoxKind kind, Vector3 a, Vector3 b) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) OptimBox optimBox = new OptimBox(kind, a, b); optimBox.Name = kind.ToString() + " " + (CountOf(kind) + 1); Boxes.Add(optimBox); return optimBox; } public void Remove(OptimBox box) { Boxes.Remove(box); } public int CountOf(OptimBoxKind kind) { int num = 0; for (int i = 0; i < Boxes.Count; i++) { if (Boxes[i].Kind == kind) { num++; } } return num; } public IEnumerable Enabled(OptimBoxKind kind) { for (int i = 0; i < Boxes.Count; i++) { if (Boxes[i].Kind == kind && Boxes[i].Enabled) { yield return Boxes[i]; } } } public static bool Touches(OptimBox box, Vector3 prev, Vector3 cur, bool first, out float fraction) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (first && box.Contains(prev)) { fraction = 0f; return true; } if (box.Contains(cur)) { fraction = 1f; return true; } return box.SegmentIntersects(prev, cur, out fraction); } } public sealed class TasMessage { public string Text = string.Empty; public bool IsError; public float Time; } [BepInPlugin("com.tas.ultrakill", "ULTRAKILL TAS Tool", "1.1.0")] [BepInProcess("ULTRAKILL.exe")] [DefaultExecutionOrder(-30000)] public sealed class Plugin : BaseUnityPlugin { public const string Guid = "com.tas.ultrakill"; public const string PluginName = "ULTRAKILL TAS Tool"; public const string PluginVersion = "1.1.0"; private static bool _quitting; private int _tickFrame = -1; private GameBridge _bridge; private RngController _rng; private TimeController _time; private InputPatcher _input; private SaveStateManager _states; private TasEngine _engine; private GuiManager _gui; private FrameEndHook _frameEnd; private GameObject _frameEndObject; private bool _fastForwardKeyHeld; private bool _loggedUpdate; private bool _loggedOnGui; private bool _loggedInsert; private bool _guiWasVisible; private bool _freecamCursorWasFree; private bool _sceneHooked; public readonly List Messages = new List(64); public ConfigEntry Autoload; public ConfigEntry Autoplay; public ConfigEntry DefaultHostFrametime; public ConfigEntry FrameLockedPlayback; public ConfigEntry DefaultSeed; public ConfigEntry PhysicsSubsteps; public ConfigEntry RecordingFile; public ConfigEntry LastScriptFile; public ConfigEntry CaptureStartState; public ConfigEntry PauseOnSceneChange; public ConfigEntry ForceSystemRandomSeeds; public ConfigEntry DeterministicPhysics; public ConfigEntry AlignFixedStepPhase; public ConfigEntry TraceDeterminism; public ConfigEntry SavestateCleanupSpawned; public ConfigEntry RespawnDynamicObjects; public ConfigEntry BlockGameInputWhileGuiOpen; public ConfigEntry InjectDeviceState; public ConfigEntry EnforceCameraAngles; public ConfigEntry PerformedFrameOffset; public ConfigEntry ActiveStateSlot; public ConfigEntry PlayStartMode; public ConfigEntry RestartLevelOnPlay; public ConfigEntry PlayStartLevel; public ConfigEntry PlayStartStateSlot; public ConfigEntry GuiVisibleOnStart; public ConfigEntry UnlockAllWeapons; public ConfigEntry WaitForPlayerControl; public ConfigEntry SceneSettleFrames; public ConfigEntry FreeLookSensitivity; public ConfigEntry FreecamSpeed; public ConfigEntry FreecamShowV1Body; public ConfigEntry TrajectoryEnabled; public ConfigEntry TrajectoryVisibilityMode; public ConfigEntry TrajectoryGradient; public ConfigEntry TrajectoryColor; public ConfigEntry TrajectoryThickness; public ConfigEntry TrajectoryOpacity; public ConfigEntry TrajectoryMarkerEvery; public ConfigEntry TrajectoryMaxNodes; public ConfigEntry TrajectoryHoverHitbox; public ConfigEntry CoinPathEnabled; public ConfigEntry CoinPathOpacity; public ConfigEntry CoinPathThickness; public ConfigEntry ThirdPersonDistance; public ConfigEntry ThirdPersonHeight; public ConfigEntry FfmpegPath; public ConfigEntry RecordingDirectory; public ConfigEntry RecordCleanRender; public ConfigEntry RecordAudio; public ConfigEntry KillPlaneY; public ConfigEntry StepRecord; public ConfigEntry RollingHistoryTicks; public ConfigEntry HistoryDuringPlayback; public ConfigEntry AutoSaveToDisk; public ConfigEntry AutoReloadOnPlay; public ConfigEntry UseNorefresh; public ConfigEntry NoRefreshFastForward; public ConfigEntry PauseAtNoRefreshBreak; public ConfigEntry ShowHud; public ConfigEntry HudShowSpeed; public ConfigEntry HudShowVelocity; public ConfigEntry HudShowAngles; public ConfigEntry HudShowVitals; public ConfigEntry HudShowRng; public ConfigEntry HudShowInputs; public ConfigEntry HudShowProgress; public ConfigEntry HudShowPosition; public ConfigEntry HudShowState; public ConfigEntry HudShowWeapon; public ConfigEntry HudShowInputDisplay; public ConfigEntry HudShowPointer; public ConfigEntry HudEntityInspector; public ConfigEntry HudShowHit; public ConfigEntry HudShowLevelStats; public ConfigEntry ShowTriggers; public ConfigEntry ShowTriggersDistance; public ConfigEntry ShowTriggersSolid; public ConfigEntry ShowTriggersOpacity; public ConfigEntry HideViewmodels; public ConfigEntry ShowHitboxes; public ConfigEntry ShowPlayerHitbox; public ConfigEntry HudCorner; public ConfigEntry HudOffsetX; public ConfigEntry HudOffsetY; public ConfigEntry HudScale; public ConfigEntry HudOpacity; public ConfigEntry HudBackground; public ConfigEntry HudColor; public ConfigEntry HudGameFont; public ConfigEntry SpeedoEnabled; public ConfigEntry SpeedoMode; public ConfigEntry SpeedoDecimals; public ConfigEntry SpeedoSize; public ConfigEntry SpeedoOffsetX; public ConfigEntry SpeedoOffsetY; public ConfigEntry SpeedoColor; public ConfigEntry SpeedoColorByChange; public ConfigEntry SpeedoShadow; public ConfigEntry SpeedoUnit; public ConfigEntry SpeedoShowVertical; public ConfigEntry SpeedoShowPeak; public ConfigEntry SpeedoOpacity; public ConfigEntry PausedLabelEnabled; public ConfigEntry PausedLabelSize; public ConfigEntry PausedLabelOffsetY; public ConfigEntry KeyToggleGui; public ConfigEntry KeyPlayPause; public ConfigEntry KeyStep; public ConfigEntry KeyFastForward; public ConfigEntry KeySaveState; public ConfigEntry KeyLoadState; public ConfigEntry KeyRecord; public ConfigEntry KeyStop; public ConfigEntry KeyRewind; public ConfigEntry KeyToggleHud; public ConfigEntry KeyToggleFreecam; public ConfigEntry KeyCameraMode; public ConfigEntry KeyCameraReset; public ConfigEntry KeyFreecamCursor; public ConfigEntry KeyFreecamFaster; public ConfigEntry KeyFreecamSlower; public ConfigEntry KeyUndo; public ConfigEntry KeyReloadPlay; public ConfigEntry MenuUpKey; public ConfigEntry MenuDownKey; public ConfigEntry MenuLeftKey; public ConfigEntry MenuRightKey; public ConfigEntry MenuConfirmKey; public ConfigEntry MenuCancelKey; private double _guiMilliseconds; public static Plugin Instance { get; private set; } public static Plugin State { get; private set; } public static bool Quitting => _quitting; public TimeController Clock => _time; public InputPatcher Injector => _input; public string ScriptDirectory { get; private set; } public ConfigFile ConfigFile => ((BaseUnityPlugin)this).Config; public GuiManager Gui => _gui; public TrajectoryManager Trajectory { get; private set; } public CoinPathManager CoinPaths { get; private set; } public VideoRecorder Video { get; private set; } public TasCameraController Cameras { get; private set; } public bool CleanRecordingActive { get { if (Video != null && Video.IsRecording && RecordCleanRender != null) { return RecordCleanRender.Value; } return false; } } public BranchProject Project { get; set; } public TasEngine Engine => _engine; public GameBridge Bridge => _bridge; public RngController Rng => _rng; public bool FreecamActive { get { if (_input != null) { return _input.FreecamActive; } return false; } } public double LastGuiMilliseconds { get; private set; } public bool TryGetFreecamPose(out Vector3 position, out Quaternion rotation) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (_input != null) { return _input.TryGetFreecamPose(out position, out rotation); } position = Vector3.zero; rotation = Quaternion.identity; return false; } public TasCameraController.ViewScope ViewPose() { if (Cameras == null) { return default(TasCameraController.ViewScope); } return Cameras.ApplyView(); } public void ToggleFreecam() { SetFreecam(!FreecamActive); } public void SetFreecam(bool enabled) { if (_input == null) { return; } if (!enabled) { if (_input.FreecamActive) { _input.EndFreecam(); Toast("Freecam off.", error: false); } } else if (!_input.FreecamActive) { if (!_input.BeginFreecam()) { Toast("Freecam: no game camera is loaded.", error: true); } else { Toast("Freecam on: WASD, Space up, Q down; Shift fast, Ctrl slow.", error: false); } } } private void Awake() { Instance = this; State = this; ReadConfiguration(); ScriptDirectory = Path.Combine(Paths.ConfigPath, "ULTRAKILL-TAS"); try { Directory.CreateDirectory(ScriptDirectory); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Could not create script directory: " + ex.Message)); } _bridge = new GameBridge(this); WeaponUnlock.UnlockAll = UnlockAllWeapons.Value; FistHudDump.InstallTrace(); _rng = new RngController(this, _bridge); _rng.Initialize(ForceSystemRandomSeeds.Value); _time = new TimeController(this, _bridge); _time.SaveOriginals(); _time.PhysicsSubsteps = Mathf.Clamp(PhysicsSubsteps.Value, 1, 8); _time.SetHostFrametime(DefaultHostFrametime.Value); TimeControllerHitstopPatch.Install(this, _time); _input = new InputPatcher(this, _bridge); _input.Initialize(); _states = new SaveStateManager(this, _bridge, _rng); _states.ResetHitstop = _time.ResetHitstop; _engine = new TasEngine(this, _bridge, _time, _input, _states, _rng); _gui = new GuiManager(this, _engine, _time, _states, _bridge, _input, _rng); Trajectory = new TrajectoryManager(this); CoinPaths = new CoinPathManager(this); Video = new VideoRecorder(this); Cameras = new TasCameraController(this); CreateFrameEndObject(); HookSceneEvents(); LogInfo("ULTRAKILL TAS Tool 1.1.0 loaded."); LogInfo("Scripts: " + ScriptDirectory); LogInfo("Unity " + Application.unityVersion + ", game path " + Paths.GameRootPath); Toast("ULTRAKILL TAS Tool 1.1.0 loaded. Insert opens the TAS window.", error: false); ApplyStartupScript(); TasRuntime.Install(this); } private void CreateFrameEndObject() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _frameEndObject = new GameObject("ULTRAKILL_TAS_FrameEnd"); Object.DontDestroyOnLoad((Object)(object)_frameEndObject); _frameEnd = _frameEndObject.AddComponent(); _frameEnd.OnEndFrame = OnEndFrame; } public void HookSceneEvents() { if (!_sceneHooked) { SceneManager.sceneLoaded += OnSceneLoaded; _sceneHooked = true; } } public void EnsureFrameEnd() { if ((Object)(object)_frameEndObject == (Object)null) { CreateFrameEndObject(); LogWarning("Frame-end hook was missing; recreated it."); } } private void ReadConfiguration() { //IL_0915: Unknown result type (might be due to invalid IL or missing references) string text = "1. General"; string text2 = "2. Timing"; string text3 = "3. Keybinds"; string text4 = "4. Menu keys"; string text5 = "5. Overlays"; string text6 = "6. Advanced"; Autoload = ((BaseUnityPlugin)this).Config.Bind(text, "Autoload script", string.Empty, "Path to a .uktas or .hltas file loaded at boot. Relative paths resolve to the script directory. Empty = disabled."); Autoplay = ((BaseUnityPlugin)this).Config.Bind(text, "Autoplay on boot", false, "Start playing the autoload script as soon as BepInEx creates the plugin (splash screen / main menu)."); GuiVisibleOnStart = ((BaseUnityPlugin)this).Config.Bind(text, "Show GUI on start", false, "Show the TAS window immediately. Insert toggles it at any time."); UnlockAllWeapons = ((BaseUnityPlugin)this).Config.Bind(text, "Unlock all weapons", false, "Report every weapon and arm as owned, in memory only. Save files are never written. A script's weapons header takes priority while it plays."); WaitForPlayerControl = ((BaseUnityPlugin)this).Config.Bind(text, "Wait for player control", true, "Hold tick 1 while NewMovement.activated is false (elevator drops and intro cutscenes)."); SceneSettleFrames = ((BaseUnityPlugin)this).Config.Bind(text, "Scene settle frames", 2, "Rendered frames to wait after control is granted for room triggers and occlusion culling."); FreeLookSensitivity = ((BaseUnityPlugin)this).Config.Bind(text, "Free-look sensitivity", 2.5f, "Degrees of camera rotation per unit of raw mouse movement while paused."); FreecamSpeed = ((BaseUnityPlugin)this).Config.Bind(text, "Freecam speed", 12f, "Freecam movement in units per second. Shift is 4x faster, Ctrl is 4x slower."); FreecamShowV1Body = ((BaseUnityPlugin)this).Config.Bind(text, "Show V1 playermodel in freecam", false, "While freecam is on, enable V1's hidden body renderers so the full model is visible."); TrajectoryEnabled = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Record and draw path", true, "Sample the player once per simulation tick and draw the path in the world."); TrajectoryVisibilityMode = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Visibility (0 always, 1 freecam only, 2 hidden)", 0, "When the path is drawn."); TrajectoryGradient = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Speed gradient", true, "Colour by speed (green slow, yellow medium, magenta fast). Off uses the single colour."); TrajectoryColor = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Single colour", "#40FF60", "Hex colour used when the speed gradient is off."); TrajectoryThickness = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Line thickness", 2f, "Parallel GL lines drawn per segment (1 to 6)."); TrajectoryOpacity = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Opacity", 0.85f, "Line alpha, 0 to 1."); TrajectoryMarkerEvery = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Marker every N ticks", 0, "Draw a small cross every N ticks. 0 turns markers off."); TrajectoryMaxNodes = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Maximum nodes", 200000, "Oldest nodes are dropped past this count."); TrajectoryHoverHitbox = ((BaseUnityPlugin)this).Config.Bind("Trajectory", "Show player hitbox on hover", true, "Draw the same local player bounding box as Show player hitbox, at the tick under the path cursor."); CoinPathEnabled = ((BaseUnityPlugin)this).Config.Bind("Coin paths", "Show coin paths", true, "Record every coin once per simulation tick and draw its flight path. Yellow: in flight. Green: punched coin. Cyan: shot coin. Red: shot back by an enemy. Magenta: tracking an enemy. Clear with the 'clearcoinpaths' script command."); CoinPathOpacity = ((BaseUnityPlugin)this).Config.Bind("Coin paths", "Opacity", 0.9f, "Coin path alpha, 0 to 1."); CoinPathThickness = ((BaseUnityPlugin)this).Config.Bind("Coin paths", "Line thickness", 2f, "Parallel GL lines drawn per path segment (1 to 6)."); ThirdPersonDistance = ((BaseUnityPlugin)this).Config.Bind("Camera", "Third person distance", 4f, "Distance behind V1's head in units."); ThirdPersonHeight = ((BaseUnityPlugin)this).Config.Bind("Camera", "Third person height", 0.5f, "Height added above V1's head in third person."); FfmpegPath = ((BaseUnityPlugin)this).Config.Bind("Recording", "ffmpeg path", string.Empty, "Full path to ffmpeg.exe. Empty searches the game folder, then PATH."); RecordingDirectory = ((BaseUnityPlugin)this).Config.Bind("Recording", "Output directory", string.Empty, "Folder for recordings. Empty uses ScriptDirectory/Recordings."); RecordAudio = ((BaseUnityPlugin)this).Config.Bind("Recording", "Record audio", true, "Capture game audio with Unity's offline mixer (silent on speakers while recording) and mux it into the video."); RecordCleanRender = ((BaseUnityPlugin)this).Config.Bind("Recording", "Clean render while recording", true, "While recording, hide the TAS HUD, hitboxes, triggers and trajectory path and show viewmodels. Restored when the recording ends."); KillPlaneY = ((BaseUnityPlugin)this).Config.Bind(text, "Kill plane Y", -100f, "Player positions below this Y are treated as out of bounds; savestates are refused and diagnostics warn."); StepRecord = ((BaseUnityPlugin)this).Config.Bind(text, "Step-record staged input", false, "When enabled, F6 writes the staged input as the next one-tick frame before advancing."); RollingHistoryTicks = ((BaseUnityPlugin)this).Config.Bind(text, "Rolling history ticks", 120, "How many per-tick snapshots the in-memory ring buffer keeps for Undo Step (Ctrl+Z) and scrubbing."); HistoryDuringPlayback = ((BaseUnityPlugin)this).Config.Bind(text, "Rolling history while playing", false, "Also snapshot every tick of continuous playback (not only F6 steps). Costs one capture per tick."); UseNorefresh = ((BaseUnityPlugin)this).Config.Bind(text, "Use norefresh checkpoints", true, "When a script has norefresh lines and a cached state exists for one of them in the level that is loaded, Play restores that state and skips everything before it, including load_level. Otherwise the script plays normally."); NoRefreshFastForward = ((BaseUnityPlugin)this).Config.Bind(text, "Enable FFF NoRefresh Fast-Forward", true, "Run a script's FFF segments headless (GoldSrc r_norefresh): every tick before an FFF marker simulates with all cameras' culling masks cleared, so no 3D geometry, shadows or lighting reach the GPU, at uncapped CPU speed. Rendering comes back on the framebulk immediately after the marker. F5 or F11 aborts at the current tick."); PauseAtNoRefreshBreak = ((BaseUnityPlugin)this).Config.Bind(text, "Pause at the FFF breakpoint", false, "When a NoRefresh run reaches its FFF breakpoint, pause playback at that exact tick instead of continuing with normal rendering."); AutoReloadOnPlay = ((BaseUnityPlugin)this).Config.Bind(text, "Reload script on Play", true, "When the script file changed on disk since it was loaded or saved, Play (F5) reloads it first. Edit the .uktas in any editor and press Play; no need to click Load."); AutoSaveToDisk = ((BaseUnityPlugin)this).Config.Bind(text, "Auto-save to disk", false, "Write the active script to disk after step-record edits and when recording stops."); ActiveStateSlot = ((BaseUnityPlugin)this).Config.Bind(text, "Active savestate slot", 0, "Slot used by the quick save/load hotkeys (0-9). Scripts use load_state/save_state with explicit slots."); PlayStartMode = ((BaseUnityPlugin)this).Config.Bind(text, "On Play", "script", "Startup override: script (use header), current, restart, level, state, or menu (title screen). The GUI Startup tab edits this."); RestartLevelOnPlay = ((BaseUnityPlugin)this).Config.Bind(text, "Restart Level on Play", false, "When true, every Play restarts the current mission before frame 1 (overrides the other startup choices)."); PlayStartLevel = ((BaseUnityPlugin)this).Config.Bind(text, "Startup level scene", string.Empty, "Scene name used when On Play = level. Empty falls back to the script header's load_level."); PlayStartStateSlot = ((BaseUnityPlugin)this).Config.Bind(text, "Startup savestate slot", 0, "Slot restored before frame 1 when On Play = state (0-9)."); RecordingFile = ((BaseUnityPlugin)this).Config.Bind(text, "Recording file", "recording.uktas", "File name (or absolute path) a recording is saved to when no script file is loaded. Relative names go to the script directory."); LastScriptFile = ((BaseUnityPlugin)this).Config.Bind(text, "Last script file", string.Empty, "Script Editor path remembered across launches. Updated whenever a script is loaded, saved or created."); DefaultHostFrametime = ((BaseUnityPlugin)this).Config.Bind(text2, "host_frametime", 0.008f, "Virtual seconds per TAS tick. 0.008 = 125 ticks/s and one native physics step (default). 0.016 = two native steps per tick. Time.fixedDeltaTime is never changed."); FrameLockedPlayback = ((BaseUnityPlugin)this).Config.Bind(text2, "Frame-locked playback", true, "GoldSrc host_framerate behaviour: every rendered frame advances the script by exactly one tick of host_frametime, so a slow render means slow game time. Playback speed caps the frame rate to speed / host_frametime (1.0 = real time). Above 1.0 the cap is lifted."); PhysicsSubsteps = ((BaseUnityPlugin)this).Config.Bind(text2, "Physics substeps", 1, "Deprecated and ignored: the clock always keeps ULTRAKILL's native 0.008 s physics step. Kept so old config files still load."); DefaultSeed = ((BaseUnityPlugin)this).Config.Bind(text6, "Default seed", 0, "Seed written into new scripts and used before a script is loaded."); CaptureStartState = ((BaseUnityPlugin)this).Config.Bind(text6, "Capture start state on play", true, "Snapshot the game when Play starts so Rewind can restore it. Menu runs have no player and therefore no start state."); PauseOnSceneChange = ((BaseUnityPlugin)this).Config.Bind(text6, "Pause on scene change", false, "Pause playback when a new scene loads instead of continuing the script across the transition."); ForceSystemRandomSeeds = ((BaseUnityPlugin)this).Config.Bind(text6, "Force deterministic System.Random seeds", true, "Patch System.Random(int) so game-created Random instances get a reproducible seed stream."); DeterministicPhysics = ((BaseUnityPlugin)this).Config.Bind(text6, "Deterministic physics", true, "While a TAS is active: bodies never fall asleep (Physics.sleepThreshold = 0) and transform changes reach the physics scene immediately (Physics.autoSyncTransforms). Removes run-to-run differences from sleeping bodies and delayed syncs. Restored when the TAS stops."); AlignFixedStepPhase = ((BaseUnityPlugin)this).Config.Bind(text6, "Align physics step phase", true, "Before Play reloads the level, move Unity's leftover fixed-step time to a fixed value so every run starts at the same point in the 0.008 s physics step. Without it the leftover from the previous run shifts which tick a step lands on, and 0.001 s ticks give a different result each run."); TraceDeterminism = ((BaseUnityPlugin)this).Config.Bind(text6, "Trace determinism", false, "Write determinism_trace_