Decompiled source of Kelvin Fights v3.16.0

plugins/KelvinFights.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using Ashkatchap.AnimatorEvents;
using AzNean.SotfCommon;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Bolt;
using Endnight.Animation;
using Endnight.Rendering;
using Endnight.Types;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using KelvinFights.Logic;
using Microsoft.CodeAnalysis;
using Pathfinding;
using Sons.Ai.Vail;
using Sons.Ai.Vail.StimuliTypes;
using Sons.Animation.Mae;
using Sons.Gameplay;
using Sons.Gameplay.GameSetup;
using Sons.Gameplay.GrabBag;
using Sons.Gui;
using Sons.Inventory;
using Sons.Items.Core;
using Sons.Multiplayer;
using Sons.Player;
using Sons.Save;
using Sons.StatSystem;
using Sons.Weapon;
using Sons.Wearable.Armour;
using Steamworks;
using TheForest.UI;
using TheForest.Utils;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Playables;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("KelvinFights")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("3.16.0.0")]
[assembly: AssemblyInformationalVersion("3.16.0+1fa7409c2ce988b161a2356723d6220566d832f0")]
[assembly: AssemblyProduct("KelvinFights")]
[assembly: AssemblyTitle("KelvinFights")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.16.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class SettingMove
{
	internal static void Move(ConfigFile config, string oldSection, string oldKey, ConfigEntryBase to)
	{
		bool saveOnConfigSet = config.SaveOnConfigSet;
		config.SaveOnConfigSet = false;
		try
		{
			ConfigEntry<string> val = config.Bind<string>(oldSection, oldKey, "\u0001", "Old place of a moved setting.");
			bool num = val.Value != "\u0001";
			if (num)
			{
				to.SetSerializedValue(((ConfigEntryBase)val).GetSerializedValue());
			}
			config.Remove(((ConfigEntryBase)val).Definition);
			if (num)
			{
				config.Save();
			}
		}
		finally
		{
			config.SaveOnConfigSet = saveOnConfigSet;
		}
	}
}
namespace AzNean.SotfCommon
{
	internal static class ModLog
	{
		private static ManualLogSource _log;

		private static ConfigEntry<bool> _full;

		private static readonly HashSet<string> _once = new HashSet<string>();

		private static readonly Dictionary<(int, string), int> _state = new Dictionary<(int, string), int>();

		internal static bool Full => _full.Value;

		internal static void Init(ManualLogSource log, ConfigEntry<bool> full)
		{
			_log = log;
			_full = full;
		}

		internal static void Trace(string message)
		{
			if (_full.Value)
			{
				_log.LogInfo((object)message);
			}
		}

		internal static bool Changed(int id, string what, int state)
		{
			if (!_full.Value || (_state.TryGetValue((id, what), out var value) && value == state))
			{
				return false;
			}
			_state[(id, what)] = state;
			return true;
		}

		internal static void Once(string key, string message, LogLevel level = (LogLevel)16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_once.Add(key))
			{
				_log.Log(level, (object)message);
			}
		}
	}
	internal static class GameSlot
	{
		[HarmonyPatch(typeof(SaveGameManager), "Load", new Type[]
		{
			typeof(string),
			typeof(SaveGameType)
		})]
		private static class Loading
		{
			private static void Prefix(string dir, SaveGameType saveGameType)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Invalid comparison between Unknown and I4
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Invalid comparison between Unknown and I4
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				if ((int)saveGameType == 2)
				{
					ModLog.Trace("Game loads a guest's own character: not a world, save slot kept");
					return;
				}
				Slot = Of(dir);
				MultiplayerSave = (int)saveGameType == 1;
				_newKey = null;
				ModLog.Trace($"Game loads save slot {Slot} ({saveGameType})");
			}
		}

		[HarmonyPatch(typeof(SaveGameManager), "Save", new Type[]
		{
			typeof(string),
			typeof(string),
			typeof(bool)
		})]
		private static class Saving
		{
			private static void Postfix(string dir, bool savePlayerOnly)
			{
				if (savePlayerOnly)
				{
					ModLog.Trace("Game saved a guest's own character only: save slot kept");
					return;
				}
				uint num = Of(dir);
				if (num == 0)
				{
					ModLog.Once("noslot " + dir, "Game saved to a folder without a slot id ('" + dir + "'): this world's key stays " + Key, (LogLevel)4);
				}
				else if (num != Slot)
				{
					string key = Key;
					Slot = num;
					_newKey = null;
					ModLog.Trace($"Game saved to slot {num}: this world's key {key} -> {Key}");
					GameSlot.Moved?.Invoke(key, Key);
				}
			}
		}

		private static bool _inWorld;

		private static string _newKey;

		internal static uint Slot { get; private set; }

		internal static bool MultiplayerSave { get; private set; }

		internal static string Key
		{
			get
			{
				string text;
				if (Slot == 0)
				{
					text = _newKey;
					if (text == null)
					{
						return _newKey = "new-" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
					}
				}
				else
				{
					text = "slot-" + Slot.ToString(CultureInfo.InvariantCulture);
				}
				return text;
			}
		}

		internal static event Action<string, string> Moved;

		internal static uint Of(string dir)
		{
			if (!uint.TryParse(Path.GetFileName(dir?.TrimEnd('/', '\\')), NumberStyles.None, CultureInfo.InvariantCulture, out var result))
			{
				return 0u;
			}
			return result;
		}

		internal static void Track(bool inWorld)
		{
			if (_inWorld && !inWorld)
			{
				ModLog.Trace($"Left the world: save slot {Slot} forgotten");
				Slot = 0u;
				MultiplayerSave = false;
				_newKey = null;
			}
			_inWorld = inWorld;
		}
	}
}
namespace KelvinFights
{
	internal static class Kelvins
	{
		internal static KelvinChoices Choices;

		private static readonly List<VailActor> Known = new List<VailActor>();

		private static readonly Dictionary<IntPtr, Robby> Robbies = new Dictionary<IntPtr, Robby>();

		private static readonly Dictionary<IntPtr, string> Style = new Dictionary<IntPtr, string>();

		private static readonly HashSet<string> Adopted = new HashSet<string>();

		private static readonly Dictionary<int, string> ArmedByItem = new Dictionary<int, string>();

		internal static int Count => Known.Count;

		internal static void Reset()
		{
			Style.Clear();
			ArmedByItem.Clear();
		}

		public static bool Is(VailActor actor)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			if ((Object)(object)actor != (Object)null)
			{
				return (int)actor.TypeId == 9;
			}
			return false;
		}

		internal static string GameId()
		{
			if (Plugin.IsGuest)
			{
				string gameId = GameSetupManager.GetGameId();
				if (!string.IsNullOrEmpty(gameId))
				{
					return gameId.Replace(' ', '_');
				}
				return "0";
			}
			string key = GameSlot.Key;
			if (GameSlot.Slot != 0 && Adopted.Add(key) && !Choices.HasAny(key))
			{
				string text = (GameSlot.MultiplayerSave ? GameSetupManager.GetGameId() : null);
				string text2 = ((!string.IsNullOrEmpty(text) && Choices.HasAny(text.Replace(' ', '_'))) ? text.Replace(' ', '_') : (Choices.HasAny(GameSlot.Slot.ToString(CultureInfo.InvariantCulture)) ? GameSlot.Slot.ToString(CultureInfo.InvariantCulture) : "0"));
				int num = Choices.Adopt(text2, key);
				Plugin.Logger.LogInfo((object)((num > 0) ? $"{num} Kelvin choice(s) kept by 2.4.0 and before (under '{text2}') copied to save slot {GameSlot.Slot}" : $"Save slot {GameSlot.Slot}: no Kelvin choice kept by 2.4.0 and before to copy"));
			}
			return key;
		}

		internal static void SlotMoved(string from, string to)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			int num = Choices.Adopt(from, to);
			KelvinSettings.Rekey(from, to);
			Adopted.Add(to);
			if (num > 0)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(68, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Kelvin choice(s) copied from ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(from);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" to ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(to);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": the world was saved to that slot");
				}
				logger.LogInfo(val);
			}
			else
			{
				ModLog.Trace($"World saved to a new slot ({from} -> {to}): no Kelvin choice to copy");
			}
		}

		public static string StyleOf(VailActor actor)
		{
			if (Style.TryGetValue(((Il2CppObjectBase)actor).Pointer, out var value))
			{
				return value;
			}
			string text = Choices.StyleOf(GameId(), actor.UniqueId);
			text = ((text != null && Array.IndexOf(Styles.All, text) >= 0) ? text : Plugin.DefaultStyle);
			Style[((Il2CppObjectBase)actor).Pointer] = text;
			return text;
		}

		public static bool Fights(VailActor actor)
		{
			if (Plugin.Enabled.Value && Is(actor))
			{
				if (!(StyleOf(actor) != "none"))
				{
					if (Plugin.GivenWeaponFights.Value)
					{
						return ArmedFor(WeaponSlot.HeldItem(actor)) != null;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		private static string ArmedFor(int item)
		{
			if (item < 0)
			{
				return null;
			}
			if (ArmedByItem.TryGetValue(item, out var value))
			{
				return value;
			}
			ItemData val = ItemDatabaseManager.ItemById(item);
			string text = (((Object)(object)val != (Object)null) ? ArmedStyles.For(val.Name, Plugin.ArmedStyleMap) : null);
			if (text != null && Plugin.Strikes.Reach(text) <= 0f)
			{
				text = null;
			}
			return ArmedByItem[item] = text;
		}

		public static void SetStyle(VailActor actor, string style)
		{
			Choices.SetStyle(GameId(), actor.UniqueId, style);
			Style[((Il2CppObjectBase)actor).Pointer] = style;
			ModLog.Trace($"{((Object)actor).name} (id {actor.UniqueId}, game {GameId()}): style {style} (notepad), kept for this game");
			if (Fights(actor))
			{
				NoFlee.StopFear(actor);
			}
			ShowDemo(actor, style, withGesture: true);
		}

		public static void ShowDemo(VailActor actor, string style, bool withGesture)
		{
			if (!Plugin.DemoOnPick.Value || (Object)(object)actor == (Object)null)
			{
				return;
			}
			string[] value;
			if (style == "none")
			{
				if (withGesture)
				{
					MovePlayer.Pose(actor, Plugin.StopGesture.Value, Plugin.StopGestureSeconds.Value);
				}
			}
			else if (!TableDemo(actor, style) && Plugin.DemoMoves.TryGetValue(style, out value))
			{
				MovePlayer.Play(actor, value, Plugin.DemoDelaySeconds.Value);
				if (withGesture)
				{
					GuestView.Demo(actor, value);
				}
			}
		}

		private static bool TableDemo(VailActor actor, string style)
		{
			int num = WeaponSlot.HeldItem(actor);
			ItemData val = ((num >= 0) ? ItemDatabaseManager.ItemById(num) : null);
			string text = (((Object)(object)val != (Object)null) ? ArmedStyles.For(val.Name, Plugin.ArmedStyleMap) : null);
			string text2 = ((text != null && Plugin.Strikes.Reach(text) > 0f) ? text : style);
			if (text2 == style && style != "cannibal")
			{
				return false;
			}
			foreach (MoveTable.Strike item in Plugin.Strikes.Of(text2))
			{
				if (item.Strikes && MovePlayer.Playable(item))
				{
					if (!MovePlayer.Play(actor, item.Parts, Plugin.DemoDelaySeconds.Value, null, item))
					{
						return false;
					}
					GuestView.Strike(actor, text2, item, null);
					ModLog.Trace($"{((Object)actor).name} demo of {text2}: {item.Name}");
					return true;
				}
			}
			return false;
		}

		public static void Seen(VailActor actor)
		{
			if (!Known.Exists((VailActor k) => (Object)(object)k != (Object)null && ((Il2CppObjectBase)k).Pointer == ((Il2CppObjectBase)actor).Pointer))
			{
				Known.Add(actor);
				ModLog.Trace($"{((Object)actor).name} (id {actor.UniqueId}) started: listed for fights");
			}
		}

		public static void Track(VailActor actor, Robby robby)
		{
			Known.RemoveAll((VailActor k) => (Object)(object)k == (Object)null);
			Style.Remove(((Il2CppObjectBase)actor).Pointer);
			if (!Known.Exists((VailActor k) => ((Il2CppObjectBase)k).Pointer == ((Il2CppObjectBase)actor).Pointer))
			{
				Known.Add(actor);
			}
			ModLog.Trace($"{((Object)actor).name} (id {actor.UniqueId}) attached; game key {GameId()}, style {StyleOf(actor)}");
			if ((Object)(object)robby != (Object)null)
			{
				Robbies[((Il2CppObjectBase)actor).Pointer] = robby;
			}
			KelvinSettings.Attach(actor, GameId());
		}

		public static IEnumerable<VailActor> All()
		{
			Known.RemoveAll((VailActor k) => (Object)(object)k == (Object)null);
			return Known;
		}

		public static Robby RobbyOf(VailActor actor)
		{
			if (!((Object)(object)actor != (Object)null) || !Robbies.TryGetValue(((Il2CppObjectBase)actor).Pointer, out var value) || !((Object)(object)value != (Object)null))
			{
				return null;
			}
			return value;
		}
	}
	internal static class KelvinSettings
	{
		private sealed class Own
		{
			public int Number;

			public ConfigEntry<bool> On;

			public readonly Dictionary<ConfigEntryBase, ConfigEntryBase> Copies = new Dictionary<ConfigEntryBase, ConfigEntryBase>();

			public readonly ConfigEntry<BodyLevel>[] Levels = new ConfigEntry<BodyLevel>[15];
		}

		private const string NumberKey = "number";

		private const string OwnKey = "OwnSettings";

		private static readonly Dictionary<ConfigEntryBase, int> LayerOf = new Dictionary<ConfigEntryBase, int>();

		private static readonly Dictionary<int, Own> ByNumber = new Dictionary<int, Own>();

		private static readonly Dictionary<IntPtr, Own> ByKelvin = new Dictionary<IntPtr, Own>();

		private static readonly Dictionary<ConfigEntryBase, (string game, int kelvin)> Owner = new Dictionary<ConfigEntryBase, (string, int)>();

		private static bool _loading;

		internal static ConfigFile Config;

		internal static int LevelOf(VailActor kelvin, int layer)
		{
			if (!((Object)(object)kelvin != (Object)null) || !ByKelvin.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return 2;
			}
			return (int)value.Levels[layer].Value;
		}

		internal static int NumberOf(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !ByKelvin.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return 0;
			}
			return value.Number;
		}

		internal static T Get<T>(VailActor kelvin, ConfigEntry<T> shared)
		{
			if ((Object)(object)kelvin != (Object)null && ByKelvin.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value) && value.On.Value && value.Copies.TryGetValue((ConfigEntryBase)(object)shared, out var value2))
			{
				return ((ConfigEntry<T>)(object)value2).Value;
			}
			return shared.Value;
		}

		internal static void Attach(VailActor kelvin, string game)
		{
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Expected O, but got Unknown
			if ((Object)(object)kelvin == (Object)null || Plugin.IsGuest)
			{
				return;
			}
			try
			{
				KelvinChoices choices = Kelvins.Choices;
				int uniqueId = kelvin.UniqueId;
				if (!int.TryParse(choices.ValueOf(game, uniqueId, "number"), out var result))
				{
					result = NextNumber(game);
					choices.SetValue(game, uniqueId, "number", result.ToString());
				}
				if (!ByNumber.TryGetValue(result, out var value))
				{
					value = (ByNumber[result] = Bind(result));
				}
				ByKelvin[((Il2CppObjectBase)kelvin).Pointer] = value;
				_loading = true;
				try
				{
					Load((ConfigEntryBase)(object)value.On, choices.ValueOf(game, uniqueId, "OwnSettings"), false);
					Owner[(ConfigEntryBase)(object)value.On] = (game, uniqueId);
					foreach (KeyValuePair<ConfigEntryBase, ConfigEntryBase> copy in value.Copies)
					{
						Load(copy.Value, choices.ValueOf(game, uniqueId, copy.Value.Definition.Key), copy.Key.BoxedValue);
						Owner[copy.Value] = (game, uniqueId);
					}
					for (int i = 0; i < 15; i++)
					{
						value.Levels[i].Value = LiveLevels.FromStored(choices.ValueOf(game, uniqueId, LiveLevels.Keys[i]));
						Owner[(ConfigEntryBase)(object)value.Levels[i]] = (game, uniqueId);
					}
				}
				finally
				{
					_loading = false;
				}
				LiveBody.LevelsChanged(((Il2CppObjectBase)kelvin).Pointer);
				ModLog.Trace($"{((Object)kelvin).name} (id {uniqueId}) is Kelvin {result} in the Mods menu; own settings {(value.On.Value ? "on" : "off")}");
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(56, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)kelvin).name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": his own settings not set up, he uses the shared ones: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogError(val);
			}
		}

		private static int NextNumber(string game)
		{
			int num = 1;
			while (Kelvins.Choices.HasValue(game, "number", num.ToString()))
			{
				num++;
			}
			return num;
		}

		private static Own Bind(int number)
		{
			string text = $"Kelvin {number}";
			Own own = new Own
			{
				Number = number
			};
			ConfigFile config = Config;
			own.On = config.Bind<bool>(text, "OwnSettings", false, $"On: Kelvin {number} uses the settings below instead of the shared ones in [Fight] (his number shows with his style when you pick it in his notepad). Kept for this game. Host only. Default off.");
			own.On.SettingChanged += Changed;
			Copy<float>(own, config, text, Plugin.EngageMeters);
			Copy<bool>(own, config, text, Plugin.AttackFrozenEnemies);
			Copy<bool>(own, config, text, Plugin.CannibalSteps);
			Copy<bool>(own, config, text, Plugin.GuardStepsOn);
			Copy<float>(own, config, text, Plugin.FightHealthMultiplier);
			Copy<float>(own, config, text, Plugin.StrikeDamageMultiplier);
			Copy<float>(own, config, text, Plugin.BackOffBelowHealth);
			Copy<float>(own, config, text, Plugin.OrderPauseSeconds);
			for (int i = 0; i < 15; i++)
			{
				own.Levels[i] = config.Bind<BodyLevel>(text, LiveLevels.SettingKeys[i], BodyLevel.Normal, $"Kelvin {number}'s level of the {LiveBody.Names[i]}: Off = none, Soft = its shared setting × LiveNotepadSoftShare, Normal = its shared setting, Strong = × LiveNotepadStrongShare. Applies even with OwnSettings off. Kept for this game. Host only. Default Normal.");
				own.Levels[i].SettingChanged += Changed;
				LayerOf[(ConfigEntryBase)(object)own.Levels[i]] = i;
			}
			return own;
		}

		private static void Copy<T>(Own own, ConfigFile config, string section, ConfigEntry<T> shared)
		{
			ConfigEntry<T> val = config.Bind<T>(section, ((ConfigEntryBase)shared).Definition.Key, shared.Value, $"Kelvin {own.Number} only, when OwnSettings is on. {((ConfigEntryBase)shared).Description.Description}");
			val.SettingChanged += Changed;
			own.Copies[(ConfigEntryBase)(object)shared] = (ConfigEntryBase)(object)val;
		}

		private static void Load(ConfigEntryBase entry, string stored, object fallback)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			if (stored == null)
			{
				entry.BoxedValue = fallback;
				return;
			}
			try
			{
				entry.BoxedValue = TomlTypeConverter.ConvertToValue(stored, entry.SettingType);
			}
			catch (Exception)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(51, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Kelvin setting '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(entry.Definition.Key);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' = '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(stored);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' not understood: default kept");
				}
				logger.LogError(val);
				entry.BoxedValue = fallback;
			}
		}

		internal static void Rekey(string from, string to)
		{
			foreach (ConfigEntryBase item in new List<ConfigEntryBase>(Owner.Keys))
			{
				if (Owner[item].game == from)
				{
					Owner[item] = (to, Owner[item].kelvin);
				}
			}
		}

		private static void Changed(object sender, EventArgs e)
		{
			if (_loading)
			{
				return;
			}
			ConfigEntryBase val = (ConfigEntryBase)((sender is ConfigEntryBase) ? sender : null);
			if (val == null || !Owner.TryGetValue(val, out (string, int) value))
			{
				return;
			}
			if (LayerOf.TryGetValue(val, out var value2))
			{
				Kelvins.Choices.SetValue(value.Item1, value.Item2, LiveLevels.Keys[value2], LiveLevels.Stored((BodyLevel)val.BoxedValue));
				{
					foreach (KeyValuePair<IntPtr, Own> item in ByKelvin)
					{
						if ((object)item.Value.Levels[value2] == val)
						{
							LiveBody.LevelsChanged(item.Key);
						}
					}
					return;
				}
			}
			Kelvins.Choices.SetValue(value.Item1, value.Item2, val.Definition.Key, TomlTypeConverter.ConvertToString(val.BoxedValue, val.SettingType));
		}
	}
	internal static class ActionLog
	{
		[HarmonyPatch(typeof(VailActor), "PerformAction")]
		private static class ActionStarted
		{
			private static void Postfix(VailActor __instance, Group group, bool __3)
			{
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c1: Expected O, but got Unknown
				if ((Object)(object)group != (Object)null && (Object)(object)__instance != (Object)null && ((Il2CppObjectBase)__instance).Pointer == MovePlayer.LastStruck)
				{
					MovePlayer.LastStruck = IntPtr.Zero;
					if (ModLog.Full)
					{
						ModLog.Trace("After Kelvin's blow, " + Who(__instance) + " does: " + group._name);
					}
				}
				if ((Object)(object)group != (Object)null && (Object)(object)__instance != (Object)null && MovePlayer.BareHitAt.TryGetValue(((Il2CppObjectBase)__instance).Pointer, out var value) && Time.time - value < 1f && (group._name ?? "").Contains("Dismember"))
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(70, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Who(__instance));
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(group._name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Time.time - value, "0.00");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s after a bare-hand blow of Kelvin: a limb cut without a blade");
					}
					logger.LogWarning(val);
				}
				if (!((Object)(object)group == (Object)null) && Near(__instance, out var distance))
				{
					string value2 = (__3 ? ", next step of a sequence" : "");
					string value3 = (Kelvins.Is(__instance) ? (", style " + Kelvins.StyleOf(__instance)) : "");
					ModLog.Trace($"TEST action t={Time.time:0.00} {Who(__instance)} {distance:0.0}m from you: {group._name}{value2}{value3}");
				}
			}
		}

		[HarmonyPatch(typeof(VailActor), "SetMeleeWeaponEnabled")]
		private static class HitboxSwitched
		{
			private static void Postfix(VailActor __instance, string id, bool value)
			{
				if (value && (!Kelvins.Is(__instance) || !MovePlayer.IsPlaying(__instance)) && Near(__instance, out var distance))
				{
					ModLog.Trace($"TEST hitbox t={Time.time:0.00} {Who(__instance)} {distance:0.0}m from you: {id} ON");
				}
			}
		}

		private static bool Near(VailActor actor, out float distance)
		{
			//IL_003a: 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)
			distance = 0f;
			Transform transform = LocalPlayer.Transform;
			if ((Object)(object)transform == (Object)null || (Object)(object)actor == (Object)null || !ModLog.Full || (!Kelvins.Is(actor) && !FightDriver.IsFoe(actor)))
			{
				return false;
			}
			distance = Vector3.Distance(transform.position, ((Component)actor).transform.position);
			return true;
		}

		internal static string Who(VailActor actor)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (Kelvins.Is(actor))
			{
				return $"{((Object)actor).name} (id {actor.UniqueId})";
			}
			return $"{actor.TypeId}#{((Object)actor).GetInstanceID()}";
		}
	}
	internal static class BagPlaces
	{
		[HarmonyPatch(typeof(GrabBagController), "Close")]
		private static class BagClosed
		{
			private static void Postfix()
			{
				if (Made.Count > 0 || Hidden.Count > 0)
				{
					SetShown(on: false);
				}
			}
		}

		private const string Template = "CraftedAxeLayoutGroup";

		private const string Resource = "KelvinFights.bag-places.txt";

		private static List<BagPlace> _table;

		private static GrabBagController _builtFor;

		private static readonly List<GrabBagLayoutItemGroup> Made = new List<GrabBagLayoutItemGroup>();

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

		internal static void Hide(List<GrabBagLayoutItemGroup> groups)
		{
			if (groups == null)
			{
				return;
			}
			foreach (GrabBagLayoutItemGroup group in groups)
			{
				if ((Object)(object)group != (Object)null && ((Component)group).gameObject.activeSelf)
				{
					((Component)group).gameObject.SetActive(false);
					Hidden.Add(group);
				}
			}
			if (ModLog.Full)
			{
				ModLog.Trace($"Give bag: {Hidden.Count} of the game's places hidden for Kelvin (nothing he can fight with)");
			}
		}

		internal static bool Show(GrabBagController bag, bool forKelvin)
		{
			bool result = false;
			if (forKelvin && Plugin.WeaponPlaces.Value && (Object)(object)bag != (Object)null && ((Object)(object)_builtFor == (Object)null || ((Il2CppObjectBase)_builtFor).Pointer != ((Il2CppObjectBase)bag).Pointer))
			{
				result = Build(bag);
			}
			SetShown(forKelvin && Plugin.WeaponPlaces.Value);
			return result;
		}

		private static void SetShown(bool on)
		{
			int num = 0;
			foreach (GrabBagLayoutItemGroup item in Made)
			{
				if ((Object)(object)item != (Object)null)
				{
					((Component)item).gameObject.SetActive(on);
					num++;
				}
			}
			if (Made.Count > 0)
			{
				ModLog.Trace($"Give bag: {num} weapon places {(on ? "shown" : "hidden")}");
			}
			if (on)
			{
				return;
			}
			foreach (GrabBagLayoutItemGroup item2 in Hidden)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					((Component)item2).gameObject.SetActive(true);
				}
			}
			Hidden.Clear();
		}

		private static bool Build(GrabBagController bag)
		{
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_013f: 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_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			Made.Clear();
			_builtFor = bag;
			List<BagPlace> list = Table();
			if (list.Count == 0 || bag._categoryGroups == null)
			{
				return false;
			}
			List<GrabBagCategoryGroup> categoryGroups = bag._categoryGroups;
			GrabBagLayoutItemGroup val = null;
			for (int i = 0; i < categoryGroups.Count; i++)
			{
				if (!((Object)(object)val == (Object)null))
				{
					break;
				}
				int num = 0;
				while (true)
				{
					GrabBagCategoryGroup obj = categoryGroups[i];
					if (((obj != null) ? obj._layoutItemGroups : null) == null || num >= categoryGroups[i]._layoutItemGroups.Count)
					{
						break;
					}
					GrabBagLayoutItemGroup val2 = categoryGroups[i]._layoutItemGroups[num];
					if ((Object)(object)val2 != (Object)null && ((Object)((Component)val2).gameObject).name == "CraftedAxeLayoutGroup")
					{
						val = val2;
						break;
					}
					num++;
				}
			}
			bool flag = default(bool);
			if ((Object)(object)val == (Object)null)
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(75, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Give bag: its ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>("CraftedAxeLayoutGroup");
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" place was not found, the weapons keep only the game's places");
				}
				logger.LogWarning(val3);
				return false;
			}
			Dictionary<int, ItemRenderable> dictionary = new Dictionary<int, ItemRenderable>();
			foreach (InventoryLayoutItemGroup item in Resources.FindObjectsOfTypeAll<InventoryLayoutItemGroup>())
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				Scene scene = ((Component)item).gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && !dictionary.ContainsKey(((LayoutItemGroup<InventoryLayoutItem>)(object)item).ItemId))
				{
					ItemRenderable componentInChildren = ((Component)item).GetComponentInChildren<ItemRenderable>(true);
					if ((Object)(object)componentInChildren != (Object)null)
					{
						dictionary[((LayoutItemGroup<InventoryLayoutItem>)(object)item).ItemId] = componentInChildren;
					}
				}
			}
			GameObject val4 = new GameObject("KelvinFights bag places (asleep)");
			val4.SetActive(false);
			try
			{
				foreach (BagPlace item2 in list)
				{
					try
					{
						Make(item2, val, categoryGroups, dictionary, val4.transform);
					}
					catch (Exception ex)
					{
						ManualLogSource logger2 = Plugin.Logger;
						BepInExErrorLogInterpolatedStringHandler val5 = new BepInExErrorLogInterpolatedStringHandler(39, 3, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("Give bag: place of item ");
							((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<int>(item2.ItemId);
							((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" on ");
							((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<string>(item2.Page);
							((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" not made: ");
							((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<Exception>(ex);
						}
						logger2.LogError(val5);
					}
				}
			}
			finally
			{
				Object.Destroy((Object)(object)val4);
			}
			if (ModLog.Full)
			{
				ModLog.Trace($"Give bag: {Made.Count} of {list.Count} weapon places made (template {"CraftedAxeLayoutGroup"})");
			}
			return Made.Count > 0;
		}

		private static void Make(BagPlace p, GrabBagLayoutItemGroup template, List<GrabBagCategoryGroup> groups, Dictionary<int, ItemRenderable> backpack, Transform asleep)
		{
			//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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_0271: 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_02f6: 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_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: 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_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_0376: Unknown result type (might be due to invalid IL or missing references)
			GrabBagCategoryGroup val = null;
			for (int i = 0; i < groups.Count; i++)
			{
				if (groups[i] != null && ((object)groups[i]._categoryType/*cast due to .constrained prefix*/).ToString() == p.Page)
				{
					val = groups[i];
					break;
				}
			}
			bool flag = default(bool);
			if ((Object)(object)((val != null) ? val._layoutGroupRoot : null) == (Object)null || val._layoutItemGroups == null || !Hands.IsKelvinPage(p.Page))
			{
				ManualLogSource logger = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(61, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Give bag: page ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(p.Page);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" not found (or Virginia's): no place for item ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(p.ItemId);
				}
				logger.LogWarning(val2);
				return;
			}
			if (!backpack.TryGetValue(p.ItemId, out var value))
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(54, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Give bag: item ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(p.ItemId);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" has no backpack model: no place for it");
				}
				logger2.LogWarning(val2);
				return;
			}
			ItemData val3 = ItemDatabaseManager.ItemById(p.ItemId);
			if ((Object)(object)val3 == (Object)null)
			{
				ManualLogSource logger3 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(52, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Give bag: item ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(p.ItemId);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" unknown to the game: no place for it");
				}
				logger3.LogWarning(val2);
				return;
			}
			GameObject val4 = Object.Instantiate<GameObject>(((Component)template).gameObject, asleep, false);
			((Object)val4).name = "KelvinFights" + val3.Name + "LayoutGroup";
			val4.SetActive(false);
			GrabBagLayoutItemGroup component = val4.GetComponent<GrabBagLayoutItemGroup>();
			ItemRenderable componentInChildren = val4.GetComponentInChildren<ItemRenderable>(true);
			((LayoutItemGroup<GrabBagLayoutItem>)(object)component)._itemId = p.ItemId;
			((LayoutItemGroup<GrabBagLayoutItem>)(object)component)._itemData = val3;
			int childCount = ((Component)componentInChildren).transform.childCount;
			for (int num = childCount - 1; num >= 0; num--)
			{
				Object.DestroyImmediate((Object)(object)((Component)((Component)componentInChildren).transform.GetChild(num)).gameObject);
			}
			componentInChildren._itemId = value._itemId;
			((AssetReferenceRenderable)componentInChildren)._baseRenderable = ((AssetReferenceRenderable)value)._baseRenderable;
			componentInChildren._hasVariations = value._hasVariations;
			componentInChildren._useVariations = value._useVariations;
			componentInChildren._renderableVariations = value._renderableVariations;
			componentInChildren._useAnimated = value._useAnimated;
			componentInChildren._animatedRenderable = value._animatedRenderable;
			((AssetReferenceRenderable)componentInChildren)._applyScale = ((AssetReferenceRenderable)value)._applyScale;
			((AssetReferenceRenderable)componentInChildren)._scale = ((AssetReferenceRenderable)value)._scale;
			for (int j = 0; j < ((LayoutItemGroup<GrabBagLayoutItem>)(object)component)._layoutItems.Count; j++)
			{
				GrabBagLayoutItem obj = ((LayoutItemGroup<GrabBagLayoutItem>)(object)component)._layoutItems[j];
				if (obj != null)
				{
					((Component)obj).gameObject.SetActive(false);
				}
			}
			Transform transform = val._layoutGroupRoot.transform;
			val4.transform.SetParent(transform, false);
			Transform transform2 = ((Component)componentInChildren).transform;
			transform2.SetPositionAndRotation(transform.TransformPoint(p.X, p.Y, p.Z), transform.rotation * new Quaternion(p.Qx, p.Qy, p.Qz, p.Qw));
			transform2.localScale = Vector3.one * (p.Scale * transform.lossyScale.x / transform2.parent.lossyScale.x);
			foreach (VirtualCursorSnapAnchor componentsInChild in val4.GetComponentsInChildren<VirtualCursorSnapAnchor>(true))
			{
				((Component)componentsInChild).transform.position = transform2.position;
			}
			val._layoutItemGroups.Add(component);
			Made.Add(component);
			if (ModLog.Full)
			{
				ModLog.Trace($"Give bag: place made for {val3.Name} (item {p.ItemId}) on {p.Page} at ({p.X:0.###}, {p.Y:0.###}, {p.Z:0.###}), scale {p.Scale:0.###}; template model children removed: {childCount}");
			}
		}

		private static List<BagPlace> Table()
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			if (_table != null)
			{
				return _table;
			}
			_table = new List<BagPlace>();
			bool flag = default(bool);
			try
			{
				using Stream stream = typeof(BagPlaces).Assembly.GetManifestResourceStream("KelvinFights.bag-places.txt");
				using StreamReader streamReader = new StreamReader(stream);
				List<string> list = new List<string>();
				_table = BagPlaceTable.Parse(streamReader.ReadToEnd(), list);
				foreach (string item in list)
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(34, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Bag places: line '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' not understood");
					}
					logger.LogError(val);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(64, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Bag places not loaded, the weapons keep only the game's places: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				logger2.LogError(val);
			}
			return _table;
		}
	}
	internal static class BodyPose
	{
		private sealed class Body
		{
			public VailActor Kelvin;

			public Transform[] Bones;

			public int BonesFrame = -10;

			public int ShapedFrame = -10;

			public float Guard = 1f;

			public float Crouch;

			public float Hips;

			public float HipsVel;

			public float Spine;

			public float SpineVel;

			public float Bounce;

			public float BounceVel;

			public float Down;
		}

		private static readonly Dictionary<IntPtr, Body> Of = new Dictionary<IntPtr, Body>();

		private static readonly List<Body> Rest = new List<Body>();

		private const float AtRest = 0.0001f;

		private const string SpineBone = "Spine";

		private static Body Get(VailActor kelvin)
		{
			if (!Of.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value) || (Object)(object)value.Kelvin == (Object)null)
			{
				Dictionary<IntPtr, Body> of = Of;
				IntPtr pointer = ((Il2CppObjectBase)kelvin).Pointer;
				Body obj = new Body
				{
					Kelvin = kelvin
				};
				value = obj;
				of[pointer] = obj;
			}
			return value;
		}

		internal static bool Set(VailActor kelvin, float guard, float crouch)
		{
			if ((Object)(object)kelvin == (Object)null)
			{
				return false;
			}
			Body body = Get(kelvin);
			bool result = Math.Abs(body.Guard - guard) > 0.001f || Math.Abs(body.Crouch - crouch) > 0.001f;
			body.Guard = guard;
			body.Crouch = crouch;
			return result;
		}

		internal static float Guard(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !Of.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return 1f;
			}
			return value.Guard;
		}

		internal static void Guarded(VailActor kelvin, Transform[] bones)
		{
			if (!((Object)(object)kelvin == (Object)null) && bones != null)
			{
				Body body = Get(kelvin);
				body.Bones = bones;
				body.BonesFrame = Time.frameCount;
				LiveBody.Posed(kelvin, bones);
			}
		}

		internal static void Strike(VailActor kelvin, Transform[] bones, float hipsDrop, float spinePitch, float dt)
		{
			if (!((Object)(object)kelvin == (Object)null) && bones != null)
			{
				Body body = Get(kelvin);
				body.Bones = bones;
				body.BonesFrame = Time.frameCount;
				LiveBody.Posed(kelvin, bones);
				Shape(body, hipsDrop, spinePitch, dt);
			}
		}

		internal static void ApplyRest(float dt)
		{
			if (Of.Count == 0)
			{
				return;
			}
			int frameCount = Time.frameCount;
			Rest.Clear();
			foreach (Body value in Of.Values)
			{
				if ((Object)(object)value.Kelvin != (Object)null && value.BonesFrame == frameCount && value.ShapedFrame != frameCount)
				{
					Rest.Add(value);
				}
			}
			foreach (Body item in Rest)
			{
				int num = CannibalSteps.Posing(item.Kelvin);
				float num2 = BodyRules.StanceCrouch(item.Crouch, num == 1 || num == 3, OwnSteps.Velocity(item.Kelvin).HasValue, MovePlayer.IsPlaying(item.Kelvin));
				Shape(item, num2 * Plugin.CrouchMeters.Value, num2 * Plugin.CrouchDegrees.Value, dt);
			}
		}

		private static void Shape(Body b, float hipsTarget, float spineTarget, float dt)
		{
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: 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_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0187: 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_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_01b2: 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_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: 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_023b: 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)
			b.ShapedFrame = Time.frameCount;
			float value = Plugin.BodySpringAccel.Value;
			float value2 = Plugin.BodySpringInertia.Value;
			b.BounceVel += LiveBody.TakeKick(b.Kelvin);
			hipsTarget += LiveBody.BobDrop(b.Kelvin);
			BodyShape.Settle(ref b.Hips, ref b.HipsVel, hipsTarget, value, value2, dt);
			BodyShape.Settle(ref b.Spine, ref b.SpineVel, spineTarget, value, value2, dt);
			StepEngine.Spring(ref b.Bounce, ref b.BounceVel, 0f, value, value2, dt);
			b.Down = Math.Max(0f, b.Hips + b.Bounce);
			if (b.Down < 0.0001f && Math.Abs(b.Spine) < 0.0001f && hipsTarget == 0f && spineTarget == 0f)
			{
				return;
			}
			Transform[] bones = b.Bones;
			int[] array = CannibalSteps.Leg();
			int num = MovePlayer.Bone("Spine");
			if (array == null || (Object)(object)bones[0] == (Object)null)
			{
				return;
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] < 0 || array[i] >= bones.Length || (Object)(object)bones[array[i]] == (Object)null)
				{
					return;
				}
			}
			if (b.Down > 0.0001f && !PoseSmoother.StaleHips(b.Kelvin))
			{
				Transform val = bones[array[2]];
				Transform val2 = bones[array[5]];
				Vector3 position = val.position;
				Vector3 position2 = val2.position;
				Quaternion rotation = val.rotation;
				Quaternion rotation2 = val2.rotation;
				Transform obj = bones[0];
				obj.position -= Vector3.up * b.Down;
				StrikeAim.TwoBone(bones[array[0]], bones[array[1]], val, position, 1f);
				StrikeAim.TwoBone(bones[array[3]], bones[array[4]], val2, position2, 1f);
				val.rotation = rotation;
				val2.rotation = rotation2;
			}
			if (Math.Abs(b.Spine) > 0.0001f && num >= 0 && num < bones.Length && (Object)(object)bones[num] != (Object)null && !PoseSmoother.Stale(b.Kelvin, num))
			{
				bones[num].rotation = Quaternion.AngleAxis(b.Spine, ((Component)b.Kelvin).transform.right) * bones[num].rotation;
			}
		}

		internal static float HipsDrop(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !Of.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return 0f;
			}
			return value.Down;
		}

		internal static void Forget(VailActor kelvin)
		{
			if ((Object)(object)kelvin != (Object)null)
			{
				Of.Remove(((Il2CppObjectBase)kelvin).Pointer);
			}
		}
	}
	internal static class CannibalPose
	{
		private sealed class Skeleton
		{
			public string Name;

			public GameObject Root;

			public Transform RootBone;

			public Transform Hips;

			public CannibalRig Rig;

			public Dictionary<string, Transform> Made;

			public string[] BuiltFor;

			public Transform[] Sources;

			public int[] Parents;

			public Quaternion[] Offsets;

			public Quaternion[] Worked;

			public HumanRetarget.Body Human;

			public bool HumanTried;
		}

		private const string RigResource = "KelvinFights.cannibal-rig.txt";

		private const string CreatureRigPrefix = "KelvinFights.rig-";

		private const string LimitsResource = "KelvinFights.bone-limits.txt";

		internal static string RetargetName = "bone by bone";

		private static bool _tried;

		private static Skeleton _cannibal;

		private static readonly List<Skeleton> Creatures = new List<Skeleton>();

		private static readonly Dictionary<IntPtr, Skeleton> ByClip = new Dictionary<IntPtr, Skeleton>();

		private static readonly HashSet<IntPtr> BoundedClips = new HashSet<IntPtr>();

		private static BoneLimits _limits;

		internal static float RootYaw;

		internal static bool Ready => Build() != null;

		private static Skeleton Build()
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			if (_cannibal != null || _tried)
			{
				return _cannibal;
			}
			_tried = true;
			_cannibal = Make("KelvinFights.cannibal-rig.txt", "KelvinFightsCannibalRig");
			if (_cannibal == null)
			{
				return null;
			}
			try
			{
				using Stream stream = typeof(CannibalPose).Assembly.GetManifestResourceStream("KelvinFights.bone-limits.txt");
				using StreamReader streamReader = new StreamReader(stream);
				_limits = BoneLimits.Parse(streamReader.ReadToEnd());
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(67, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Bone limits not loaded, the creature clips that need them are off: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val);
			}
			string[] manifestResourceNames = typeof(CannibalPose).Assembly.GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				if (text.StartsWith("KelvinFights.rig-", StringComparison.Ordinal))
				{
					Skeleton skeleton = Make(text, "KelvinFightsRig_" + Path.GetFileNameWithoutExtension(text.Substring("KelvinFights.rig-".Length)));
					if (skeleton != null)
					{
						Creatures.Add(skeleton);
					}
				}
			}
			return _cannibal;
		}

		private static Skeleton Make(string resource, string objectName)
		{
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			try
			{
				string text;
				using (Stream stream = typeof(CannibalPose).Assembly.GetManifestResourceStream(resource))
				{
					using StreamReader streamReader = new StreamReader(stream);
					text = streamReader.ReadToEnd();
				}
				CannibalRig cannibalRig = CannibalRig.Parse(text);
				val = new GameObject(objectName);
				Object.DontDestroyOnLoad((Object)(object)val);
				((Object)val).hideFlags = (HideFlags)61;
				val.AddComponent<Animator>();
				Dictionary<string, Transform> dictionary = new Dictionary<string, Transform>();
				foreach (CannibalRig.Bone bone in cannibalRig.Bones)
				{
					int num = bone.Path.LastIndexOf('/');
					GameObject val2 = new GameObject((num < 0) ? bone.Path : bone.Path.Substring(num + 1));
					val2.transform.SetParent((num < 0) ? val.transform : dictionary[bone.Path.Substring(0, num)], false);
					val2.transform.localPosition = new Vector3(bone.Position[0], bone.Position[1], bone.Position[2]);
					val2.transform.localRotation = new Quaternion(bone.Rotation[0], bone.Rotation[1], bone.Rotation[2], bone.Rotation[3]);
					dictionary[bone.Path] = val2.transform;
				}
				Skeleton result = new Skeleton
				{
					Name = objectName,
					Root = val,
					Rig = cannibalRig,
					Made = dictionary,
					RootBone = dictionary[cannibalRig.RootPath],
					Hips = dictionary[cannibalRig.Follows.Find((CannibalRig.Follow f) => f.Kelvin == "Hips").Source]
				};
				if (ModLog.Full)
				{
					ModLog.Trace($"{objectName} for Kelvin's game-clip moves: {dictionary.Count} bones, {cannibalRig.Follows.Count} of his bones follow it, {cannibalRig.Clips.Count} clips of its own");
				}
				return result;
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(43, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(objectName);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" not built, the moves that use it are off: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val3);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				return null;
			}
		}

		private static Skeleton For(AnimationClip clip)
		{
			if (Build() == null)
			{
				return null;
			}
			if (ByClip.TryGetValue(((Il2CppObjectBase)clip).Pointer, out var value))
			{
				return value;
			}
			value = _cannibal;
			string name = ((Object)clip).name;
			foreach (Skeleton creature in Creatures)
			{
				if (creature.Rig.Clips.Contains(name))
				{
					value = creature;
					break;
				}
			}
			if (value.Rig.Bounded.Contains(name))
			{
				if (_limits == null)
				{
					ModLog.Once("bounded " + name, "Clip '" + name + "' needs the bone limits, which did not load: not played (logged once)", (LogLevel)4);
					ByClip[((Il2CppObjectBase)clip).Pointer] = null;
					return null;
				}
				BoundedClips.Add(((Il2CppObjectBase)clip).Pointer);
			}
			ByClip[((Il2CppObjectBase)clip).Pointer] = value;
			if (value != _cannibal)
			{
				ModLog.Trace($"Clip '{name}' plays on Kelvin through {value.Name}{(BoundedClips.Contains(((Il2CppObjectBase)clip).Pointer) ? ", each of his bones kept within a human joint's range" : "")}");
			}
			return value;
		}

		private static void Match(Skeleton s, string[] bonePaths)
		{
			//IL_007f: 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_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)
			if (s.BuiltFor == bonePaths)
			{
				return;
			}
			int num = bonePaths.Length;
			s.Sources = (Transform[])(object)new Transform[num];
			s.Parents = new int[num];
			s.Offsets = (Quaternion[])(object)new Quaternion[num];
			s.Worked = (Quaternion[])(object)new Quaternion[num];
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			for (int i = 0; i < num; i++)
			{
				dictionary[bonePaths[i].Substring(bonePaths[i].LastIndexOf('/') + 1)] = i;
			}
			for (int j = 0; j < num; j++)
			{
				s.Parents[j] = -1;
				s.Offsets[j] = Quaternion.identity;
			}
			foreach (CannibalRig.Follow follow in s.Rig.Follows)
			{
				if (dictionary.TryGetValue(follow.Kelvin, out var value))
				{
					s.Offsets[value] = new Quaternion(follow.Rotation[0], follow.Rotation[1], follow.Rotation[2], follow.Rotation[3]);
					if (follow.FromParent)
					{
						s.Parents[value] = (dictionary.TryGetValue(follow.Source, out var value2) ? value2 : (-1));
					}
					else
					{
						s.Made.TryGetValue(follow.Source, out s.Sources[value]);
					}
				}
			}
			s.BuiltFor = bonePaths;
		}

		internal static Quaternion Facing(AnimationClip clip, out Vector3 start)
		{
			//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_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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_0059: 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_0095: 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_008a: 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)
			start = Vector3.zero;
			Skeleton skeleton = For(clip);
			if (skeleton == null)
			{
				return Quaternion.identity;
			}
			clip.SampleAnimation(skeleton.Root, 0f);
			start = skeleton.Hips.position;
			Vector3 val = skeleton.RootBone.rotation * Vector3.forward;
			RootYaw = Mathf.Atan2(val.x, val.z) * 57.29578f;
			val.y = 0f;
			if (!(((Vector3)(ref val)).sqrMagnitude < 1E-06f))
			{
				return Quaternion.Inverse(Quaternion.LookRotation(val));
			}
			return Quaternion.identity;
		}

		private static HumanRetarget.Body Human(Skeleton s)
		{
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_0070: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			if (!Plugin.HumanoidRetarget.Value || !HumanRetarget.KelvinReady)
			{
				return null;
			}
			if (s.HumanTried)
			{
				return s.Human;
			}
			s.HumanTried = true;
			bool flag = default(bool);
			try
			{
				foreach (CannibalRig.Bone bone in s.Rig.Bones)
				{
					Transform obj = s.Made[bone.Path];
					obj.localPosition = new Vector3(bone.Position[0], bone.Position[1], bone.Position[2]);
					obj.localRotation = new Quaternion(bone.Rotation[0], bone.Rotation[1], bone.Rotation[2], bone.Rotation[3]);
				}
				s.Human = HumanRetarget.Make(s.Name, s.Root, s.Made, HumanMap.ForRig(s.Rig), out var why);
				if (s.Human == null)
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(76, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(s.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": no human avatar (");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(why);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): its clips keep the bone-by-bone retarget (logged once)");
					}
					logger.LogWarning(val);
				}
			}
			catch (Exception ex)
			{
				s.Human = null;
				ManualLogSource logger2 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(83, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(s.Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": human avatar not built (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): its clips keep the bone-by-bone retarget (logged once)");
				}
				logger2.LogWarning(val);
			}
			return s.Human;
		}

		internal static float Sample(AnimationClip clip, float t, Quaternion facing, Vector3 start, string[] bonePaths, float[] rotations, out float travelX, out float travelZ)
		{
			//IL_0047: 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)
			//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_0186: 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_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: 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_01b5: 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_01be: 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_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: 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_008e: 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_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_00aa: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: 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_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: 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_0130: Unknown result type (might be due to invalid IL or missing references)
			travelX = (travelZ = 0f);
			Skeleton skeleton = For(clip);
			if (skeleton == null)
			{
				return 1f;
			}
			Match(skeleton, bonePaths);
			HumanRetarget.Body body = Human(skeleton);
			clip.SampleAnimation(skeleton.Root, t);
			float num = ((body != null) ? HumanRetarget.Pose(body, facing, bonePaths, rotations) : float.NaN);
			RetargetName = (float.IsNaN(num) ? "bone by bone" : "humanoid");
			for (int i = 0; i < bonePaths.Length; i++)
			{
				if (!float.IsNaN(num))
				{
					break;
				}
				Quaternion val = ((!((Object)(object)skeleton.Sources[i] != (Object)null)) ? ((skeleton.Parents[i] < 0) ? Quaternion.identity : (skeleton.Worked[skeleton.Parents[i]] * skeleton.Offsets[i])) : (facing * skeleton.Sources[i].rotation * skeleton.Offsets[i]));
				skeleton.Worked[i] = val;
				rotations[4 * i] = val.x;
				rotations[4 * i + 1] = val.y;
				rotations[4 * i + 2] = val.z;
				rotations[4 * i + 3] = val.w;
			}
			if (BoundedClips.Contains(((Il2CppObjectBase)clip).Pointer))
			{
				_limits.Clamp(bonePaths, rotations);
			}
			Vector3 val2 = skeleton.RootBone.rotation * Vector3.forward;
			RootYaw = Mathf.Atan2(val2.x, val2.z) * 57.29578f;
			Vector3 val3 = facing * (skeleton.Hips.position - start);
			travelX = val3.x / skeleton.Rig.StandingHeight;
			travelZ = val3.z / skeleton.Rig.StandingHeight;
			if (!float.IsNaN(num))
			{
				return num;
			}
			return (skeleton.Hips.position.y - skeleton.Root.transform.position.y) / skeleton.Rig.StandingHeight;
		}
	}
	internal static class CannibalSteps
	{
		private sealed class Measured
		{
			public AnimationClip Clip;

			public MoveBank.Move Move;

			public Quaternion Facing;

			public Vector3 Start;

			public float DirX;

			public float DirZ;

			public float Share;

			public float[] Along;

			public string Name
			{
				get
				{
					if (!((Object)(object)Clip != (Object)null))
					{
						return Move.Id;
					}
					return ((Object)Clip).name;
				}
			}

			public float Length
			{
				get
				{
					if (!((Object)(object)Clip != (Object)null))
					{
						return Move.Duration;
					}
					return Clip.length;
				}
			}
		}

		private sealed class Stepping
		{
			public VailActor Kelvin;

			public Transform Rig;

			public Transform[] Bones;

			public Quaternion[] From;

			public float[] Rotations;

			public float[] Previous;

			public bool Fighting;

			public bool Whole;

			public Measured Now;

			public Measured Wanted;

			public float WantedSince;

			public float Phase;

			public float Weight;

			public float Switch = 1f;

			public float Speed;

			public bool SunkWarned;

			public bool LiftWarned;

			public MoveBank.Move[] StepsSaid;

			public Vector3 LastPosition;

			public Vector3 Heading;

			public Vector3 HipsWritten;

			public float NextFeetLog;

			public int Kind;
		}

		private sealed class Stand
		{
			public float LocalY = -1f;

			public float Hips;

			public float Foot;
		}

		private sealed class StepSet
		{
			public Measured[] Steps;

			public float[] DirX;

			public float[] DirZ;
		}

		private const int Samples = 32;

		private static readonly string[] LegBones = new string[6] { "LeftUpLeg", "LeftLeg", "LeftFoot", "RightUpLeg", "RightLeg", "RightFoot" };

		private static int[] _leg;

		private static readonly Dictionary<IntPtr, Stand> Standing = new Dictionary<IntPtr, Stand>();

		private static readonly HashSet<IntPtr> DropWarned = new HashSet<IntPtr>();

		private static readonly Dictionary<IntPtr, string> SinkWritten = new Dictionary<IntPtr, string>();

		private const float SinkLogMeters = 0.15f;

		internal const int NoLegs = 0;

		internal const int StanceLegs = 1;

		internal const int OwnFeet = 2;

		internal const int StepClip = 3;

		private const float NoTravel = 0.05f;

		private static readonly Dictionary<IntPtr, Stepping> On = new Dictionary<IntPtr, Stepping>();

		private static readonly Dictionary<string, Measured> Clips = new Dictionary<string, Measured>();

		private static readonly List<IntPtr> Gone = new List<IntPtr>();

		private static readonly List<Measured> Moving = new List<Measured>();

		private static string _runFor;

		private static string _moveFor;

		private static float _retryAt;

		private static readonly HashSet<IntPtr> WholeBody = new HashSet<IntPtr>();

		private static readonly Dictionary<MoveBank.Move, Measured> Footworks = new Dictionary<MoveBank.Move, Measured>();

		private static readonly Dictionary<MoveBank.Move[], StepSet> Sets = new Dictionary<MoveBank.Move[], StepSet>();

		internal static int[] Leg()
		{
			if (_leg != null || MovePlayer.Bank == null)
			{
				return _leg;
			}
			string[] bonePaths = MovePlayer.Bank.BonePaths;
			_leg = new int[LegBones.Length];
			for (int i = 0; i < LegBones.Length; i++)
			{
				_leg[i] = -1;
				for (int j = 0; j < bonePaths.Length; j++)
				{
					if (bonePaths[j].EndsWith("/" + LegBones[i]))
					{
						_leg[i] = j;
						break;
					}
				}
			}
			return _leg;
		}

		internal static bool HasStanding(VailActor kelvin)
		{
			if ((Object)(object)kelvin != (Object)null && Standing.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return value.LocalY > 0f;
			}
			return false;
		}

		internal static void SampleStanding(VailActor kelvin, Transform[] bones, Vector3 root)
		{
			//IL_002e: 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_007a: 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_00af: 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)
			if (!Standing.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				value = (Standing[((Il2CppObjectBase)kelvin).Pointer] = new Stand());
			}
			float y = bones[0].localPosition.y;
			if (!FeetFloor.Higher(y, value.LocalY))
			{
				return;
			}
			int[] array = Leg();
			if (array != null && array[2] >= 0 && array[5] >= 0 && array[5] < bones.Length)
			{
				float foot = Math.Min(bones[array[2]].position.y, bones[array[5]].position.y) - root.y;
				if (FeetFloor.OnGround(foot, Plugin.FeetFloorToleranceMeters.Value))
				{
					value.LocalY = y;
					value.Hips = bones[0].position.y - root.y;
					value.Foot = foot;
				}
			}
		}

		private static void SinkCheck(VailActor kelvin, float foot, bool guarded)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			if (0f - foot <= 0.15f)
			{
				return;
			}
			Stepping value;
			string text = MovePlayer.NowName(kelvin) ?? ((On.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out value) && value.Now != null) ? ("step " + value.Now.Name) : "none");
			if (!SinkWritten.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value2) || !(value2 == text))
			{
				SinkWritten[((Il2CppObjectBase)kelvin).Pointer] = text;
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(93, 5, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ActionLog.Who(kelvin));
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": SUNK after every writer, lower foot ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(0f - foot, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m under the ground during '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' ");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("(floor guard ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(guarded ? "on" : "off: no standing height yet");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", retarget ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(CannibalPose.RetargetName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")");
				}
				logger.LogWarning(val);
			}
		}

		internal static void KeepFeetUp(VailActor kelvin, Transform[] bones)
		{
			//IL_005e: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: 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_012e: 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_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)
			//IL_02c6: 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_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: 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_0317: Expected O, but got Unknown
			if ((Object)(object)kelvin == (Object)null || ((!On.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value) || !(value.Weight > 0f)) && !MovePlayer.IsPlaying(kelvin)))
			{
				return;
			}
			int[] array = Leg();
			if (array == null || array[2] < 0 || array[5] < 0 || array[5] >= bones.Length)
			{
				return;
			}
			float y = ((Component)kelvin).transform.position.y;
			float num = Math.Min(bones[array[2]].position.y, bones[array[5]].position.y) - y;
			if (!Standing.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value2) || !(value2.LocalY > 0f))
			{
				SinkCheck(kelvin, num, guarded: false);
				return;
			}
			float num2 = FeetFloor.Raise(num, value2.Foot, Plugin.FeetFloorToleranceMeters.Value);
			SinkCheck(kelvin, num + Math.Max(0f, num2) - value2.Foot, guarded: true);
			bool flag = default(bool);
			if (num2 <= 0f)
			{
				float num3 = FeetFloor.Drop(num, value2.Foot, Plugin.FeetFloorToleranceMeters.Value, MovePlayer.AirAllowed(kelvin));
				if (num3 <= 0f)
				{
					return;
				}
				Transform obj = bones[0];
				obj.position -= Vector3.up * num3;
				if (!DropWarned.Contains(((Il2CppObjectBase)kelvin).Pointer) && num3 > 0.1f)
				{
					DropWarned.Add(((Il2CppObjectBase)kelvin).Pointer);
					ManualLogSource logger = Plugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(112, 7, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ActionLog.Who(kelvin));
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": feet kept on the ground, hips lowered ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num3, "0.00");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m (striking ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(MovePlayer.IsPlaying(kelvin));
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("step '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>((value?.Now != null) ? value.Now.Name : "none");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("', standing hips ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(value2.LocalY, "0.00");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", lower foot ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num, "0.00");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m against ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(value2.Foot, "0.00");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" standing)");
					}
					logger.LogWarning(val);
				}
				return;
			}
			Transform obj2 = bones[0];
			obj2.position += Vector3.up * num2;
			if (value != null && !value.LiftWarned && num2 > 0.1f)
			{
				value.LiftWarned = true;
				float num4 = FightDriver.GroundUnder((bones[array[2]].position.y < bones[array[5]].position.y) ? bones[array[2]].position : bones[array[5]].position, kelvin, null) - y;
				ManualLogSource logger2 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(232, 11, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ActionLog.Who(kelvin));
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": feet kept above the ground, hips lifted ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num2, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m (striking ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(MovePlayer.IsPlaying(kelvin));
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("move '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(MovePlayer.NowName(kelvin) ?? "none");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("', last step '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>((value.Now != null) ? value.Now.Name : "none");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("', standing hips ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(value2.LocalY, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("lower foot ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m against ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(value2.Foot, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" standing, ground under it ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num4, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m from his root; ");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("hips ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(MovePlayer.ClipHips(kelvin), "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m up as the clip wrote them, ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(BodyPose.HipsDrop(kelvin), "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" m held down by his crouch spring)");
				}
				logger2.LogWarning(val);
			}
		}

		internal static int Posing(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !On.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value) || !(value.Weight > 0f))
			{
				return 0;
			}
			return value.Kind;
		}

		internal static object StepShown(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !On.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value) || !(value.Weight > 0f))
			{
				return null;
			}
			return value.Now;
		}

		internal static string StepName(object shown)
		{
			return (shown as Measured)?.Name;
		}

		internal static float StandFoot(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !Standing.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value) || !(value.LocalY > 0f))
			{
				return float.NaN;
			}
			return value.Foot;
		}

		internal static float StandLocalY(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !Standing.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return -1f;
			}
			return value.LocalY;
		}

		internal static float StandHips(VailActor kelvin)
		{
			if (!((Object)(object)kelvin != (Object)null) || !Standing.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				return 0f;
			}
			return Math.Max(0f, value.Hips);
		}

		internal static void Fight(VailActor kelvin, bool fighting)
		{
			//IL_00e5: 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)
			if ((Object)(object)kelvin == (Object)null)
			{
				return;
			}
			if (On.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				value.Fighting = fighting;
			}
			else
			{
				if (!fighting || !KelvinSettings.Get<bool>(kelvin, Plugin.CannibalSteps) || MovePlayer.Bank == null || !CannibalPose.Ready)
				{
					return;
				}
				_ = MovePlayer.Bank;
				Transform val = (((Object)(object)kelvin._animator != (Object)null) ? ((Component)kelvin._animator).transform : null);
				if (!((Object)(object)val == (Object)null))
				{
					HumanRetarget.Know(val);
					Transform[] array = MovePlayer.BonesOf(kelvin, val);
					if (array != null)
					{
						On[((Il2CppObjectBase)kelvin).Pointer] = new Stepping
						{
							Kelvin = kelvin,
							Rig = val,
							Bones = array,
							From = (Quaternion[])(object)new Quaternion[array.Length],
							Rotations = new float[4 * array.Length],
							Previous = new float[4 * array.Length],
							Fighting = true,
							LastPosition = ((Component)kelvin).transform.position
						};
						PoseSmoother.Watch(kelvin, array);
					}
				}
			}
		}

		internal static void Whole(VailActor kelvin, bool whole)
		{
			if (!((Object)(object)kelvin == (Object)null))
			{
				if (whole)
				{
					WholeBody.Add(((Il2CppObjectBase)kelvin).Pointer);
				}
				else
				{
					WholeBody.Remove(((Il2CppObjectBase)kelvin).Pointer);
				}
			}
		}

		internal static void HandedOver(VailActor kelvin, Vector3 shift)
		{
			//IL_0001: 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_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)
			FootPlant.HandedOver(kelvin, shift);
			if ((Object)(object)kelvin != (Object)null && On.TryGetValue(((Il2CppObjectBase)kelvin).Pointer, out var value))
			{
				Stepping stepping = value;
				stepping.LastPosition += shift;
			}
		}

		internal static void Forget(VailActor kelvin)
		{
			if ((Object)(object)kelvin != (Object)null)
			{
				On.Remove(((Il2CppObjectBase)kelvin).Pointer);
				Standing.Remove(((Il2CppObjectBase)kelvin).Pointer);
				WholeBody.Remove(((Il2CppObjectBase)kelvin).Pointer);
			}
		}

		private static Measured Measure(string name)
		{
			//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)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: 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)
			AnimationClip val = MovePlayer.GameClipOrNull(name);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if (Clips.TryGetValue(((Object)val).name, out var value) && (Object)(object)value.Clip == (Object)(object)val)
			{
				return value;
			}
			value = new Measured
			{
				Clip = val
			};
			value.Facing = CannibalPose.Facing(val, out value.Start);
			float[] rotations = new float[4 * MovePlayer.Bank.BonePaths.Length];
			CannibalPose.Sample(val, val.length, value.Facing, value.Start, MovePlayer.Bank.BonePaths, rotations, out var travelX, out var travelZ);
			value.Share = Mathf.Sqrt(travelX * travelX + travelZ * travelZ);
			if (value.Share > 0.0001f)
			{
				value.DirX = travelX / value.Share;
				value.DirZ = travelZ / value.Share;
			}
			if (value.Share > 0.05f)
			{
				value.Along = new float[33];
				for (int i = 1; i <= 32; i++)
				{
					CannibalPose.Sample(val, val.length * (float)i / 32f, value.Facing, value.Start, MovePlayer.Bank.BonePaths, rotations, out travelX, out travelZ);
					value.Along[i] = Math.Max(value.Along[i - 1], (travelX * value.DirX + travelZ * value.DirZ) / value.Share);
				}
				value.Along[32] = 1f;
			}
			Clips[((Object)val).name] = value;
			if (ModLog.Full)
			{
				ModLog.Trace($"Cannibal step '{((Object)val).name}': {val.length:0.00} s, travel {value.Share:0.00} x standing height per cycle toward ({value.DirX:0.00} right, {value.DirZ:0.00} forward)");
			}
			return value;
		}

		private static Measured Stance(MoveBank.Move move)
		{
			if (move == null)
			{
				return null;
			}
			if (!Footworks.TryGetValue(move, out var value))
			{
				Dictionary<MoveBank.Move, Measured> footworks = Footworks;
				Measured obj = new Measured
				{
					Move = move
				};
				value = obj;
				footworks[move] = obj;
			}
			return value;
		}

		private static StepSet SetOf(MoveBank.Move[] moves)
		{
			if (Sets.TryGetValue(moves, out var value))
			{
				return value;
			}
			List<Measured> list = new List<Measured>();
			foreach (MoveBank.Move move in moves)
			{
				Measured measured = new Measured
				{
					Move = move,
					Along = new float[33]
				};
				if (GuardSteps.Measure(move, measured.Along, out measured.DirX, out measured.DirZ, out measured.Share) && measured.Share > 0.05f)
				{
					list.Add(measured);
					continue;
				}
				ModLog.Once("guard-step-still-" + move.Id, $"Guard step '{move.Id}' carries him {measured.Share:0.00} of his hips height per cycle: not a step, left out", (LogLevel)4);
			}
			value = new StepSet
			{
				Steps = list.ToArray(),
				DirX = new float[list.Count],
				DirZ = new float[list.Count]
			};
			for (int j = 0; j < list.Count; j++)
			{
				value.DirX[j] = list[j].DirX;
				value.DirZ[j] = list[j].DirZ;
			}
			Sets[moves] = value;
			return value;
		}

		private static Measured BestGuardStep(Stepping s, MoveBank.Move[] moves, Vector3 heading, float speed)
		{
			//IL_0036: 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)
			if (moves == null || moves.Length == 0 || !KelvinSettings.Get<bool>(s.Kelvin, Plugin.GuardStepsOn))
			{
				return null;
			}
			StepSet stepSet = SetOf(moves);
			int num = GuardSteps.Nearest(stepSet.DirX, stepSet.DirZ, stepSet.Steps.Length, heading.x, heading.z);
			if (num < 0)
			{
				return null;
			}
			Measured measured = stepSet.Steps[num];
			float value = Plugin.GuardStepsUpTo.Value;
			if (!GuardSteps.Shows(speed, measured.Share * StandHips(s.Kelvin), measured.Length, value))
			{
				return null;
			}
			if (s.StepsSaid != moves)
			{
				s.StepsSaid = moves;
				ModLog.Once($"guard-steps-{((Il2CppObjectBase)s.Kelvin).Pointer}-{moves[0].Id}", $"{ActionLog.Who(s.Kelvin)} steps in his guard: {stepSet.Steps.Length} captured guard steps ({string.Join(", ", Array.ConvertAll(stepSet.Steps, (Measured x) => x.Move.Id))}), each up to {value:0.0} times its own speed; faster, he walks", (LogLevel)16);
			}
			return measured;
		}

		private static bool IsGuardStep(Measured m)
		{
			if (m != null && m.Move != null)
			{
				return m.Share > 0.05f;
			}
			return false;
		}

		private static float TimeAt(Measured m, float phase)
		{
			float[] along = m.Along;
			if (along == null)
			{
				return phase;
			}
			int i;
			for (i = 1; i < 32 && along[i] < phase; i++)
			{
			}
			float num = along[i] - along[i - 1];
			return ((float)(i - 1) + ((num > 1E-05f) ? ((phase - along[i - 1]) / num) : 0f)) / 32f;
		}

		private static List<Measured> MovingClips()
		{
			string value = Plugin.StepRunClip.Value;
			string value2 = Plugin.StepMoveClips.Value;
			if ((object)value == _runFor && (object)value2 == _moveFor && (_retryAt <= 0f || Time.time < _retryAt))
			{
				return Moving;
			}
			_runFor = value;
			_moveFor = value2;
			Moving.Clear();
			bool flag = true;
			string[] array = (value + "," + value2).Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0 && !text.Equals("None", StringComparison.OrdinalIgnoreCase))
				{
					Measured measured = Measure(text);
					if (measured == null)
					{
						flag = false;
					}
					else if (measured.Share > 0.05f)
					{
						Moving.Add(measured);
					}
				}
			}
			_retryAt = (flag ? 0f : (Time.time + Plugin.ClipSearchSeconds.Value));
			return Moving;
		}

		private static Measured Best(Stepping s, Vector3 heading, float speed)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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)
			Measured measured = null;
			float num = -2f;
			List<Measured> list = MovingClips();
			foreach (Measured item in list)
			{
				float num2 = item.DirX * heading.x + item.DirZ * heading.z;
				if (num2 > num)
				{
					num = num2;
					measured = item;
				}
			}
			if (measured == null)
			{
				return null;
			}
			float num3 = Mathf.Cos(Mathf.Acos(Mathf.Clamp(num, -1f, 1f)) + (float)Math.PI / 180f * Plugin.StepDirectionDegrees.Value);
			float num4 = float.MaxValue;
			foreach (Measured item2 in list)
			{
				if (!(item2.DirX * heading.x + item2.DirZ * heading.z < num3))
				{
					float num5 = Math.Abs(item2.Share * StandHips(s.Kelvin) / item2.Clip.length - speed);
					if (num5 < num4)
					{
						num4 = num5;
						measured = item2;
					}
				}
			}
			return measured;
		}

		private static void Show(Stepping s, Measured m)
		{
			if (m != s.Now)
			{
				if (s.Now != null)
				{
					Array.Copy(s.Rotations, s.Previous, s.Rotations.Length);
					s.Switch = 0f;
				}
				if (m == null || m.Share <= 0.05f || s.Now == null || s.Now.Share <= 0.05f)
				{
					s.Phase = 0f;
				}
				s.Now = m;
			}
		}

		internal static void Apply(float dt)
		{
			//IL_0a68: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a6f: Expected O, but got Unknown
			//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_0087: 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_0095: 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_00c1: 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_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: 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_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: 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_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: 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_05dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0514: Unknown result type (might be due to invalid IL or missing references)
			//IL_051b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0666: Unknown result type (might be due to invalid IL or missing references)
			//IL_066b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0785: 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_072e: 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_0735: Unknown result type (might be due to invalid IL or missing references)
			//IL_0737: Unknown result type (might be due to invalid IL or missing references)
			//IL_073e: Unknown result type (might be due to invalid IL or missing references)
			//IL_070b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0710: Unknown result type (might be due to invalid IL or missing references)
			//IL_0714: Unknown result type (might be due to invalid IL or missing references)
			//IL_0719: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_07db: Unknown result type (might be due to invalid IL or missing references)
			//IL_08a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0945: Unknown result type (might be due to invalid IL or missing references)
			//IL_094c: Unknown result type (might be due to invalid IL or missing references)
			//IL_09ec: Unknown result type (might be due to invalid IL or missing references)
			if (On.Count == 0)
			{
				return;
			}
			float value = Plugin.StanceBlendSeconds.Value;
			float time = Time.time;
			Quaternion val2 = default(Quaternion);
			bool flag7 = default(bool);
			foreach (KeyValuePair<IntPtr, Stepping> item in On)
			{
				Stepping value2 = item.Value;
				if ((Object)(object)value2.Kelvin == (Object)null || (Object)(object)value2.Rig == (Object)null)
				{
					Gone.Add(item.Key);
					continue;
				}
				try
				{
					Vector3 position = ((Component)value2.Kelvin).transform.position;
					Vector3 val = position - value2.LastPosition;
					val.y = 0f;
					value2.LastPosition = position;
					if (((Vector3)(ref val)).magnitude > Plugin.StepTeleportMeters.Value)
					{
						val = Vector3.zero;
					}
					float num = ((dt > 0f) ? (((Vector3)(ref val)).magnitude / dt) : 0f);
					float value3 = Plugin.FootSpeedSmoothingSeconds.Value;
					float num2 = ((value3 > 0f) ? Mathf.Clamp01(dt / value3) : 1f);
					value2.Speed = Mathf.Lerp(value2.Speed, num, num2);
					if (((Vector3)(ref val)).sqrMagnitude > 1E-08f)
					{
						value2.Heading = Vector3.Lerp(value2.Heading, Quaternion.Inverse(((Component)value2.Kelvin).transform.rotation) * ((Vector3)(ref val)).normalized, num2);
					}
					if (value2.Bones[0].localPosition != value2.HipsWritten)
					{
						SampleStanding(value2.Kelvin, value2.Bones, position);
					}
					if (!Standing.TryGetValue(((Il2CppObjectBase)value2.Kelvin).Pointer, out var value4) || value4.LocalY <= 0f)
					{
						continue;
					}
					float num3 = Math.Max(0.5f, value4.Hips);
					bool flag = value2.Fighting && KelvinSettings.Get<bool>(value2.Kelvin, Plugin.CannibalSteps) && (FightDriver.Engaged(value2.Kelvin) || GuestView.Fights(value2.Kelvin));
					Measured measured = null;
					if (flag)
					{
						Vector3 heading = value2.Heading;
						heading.y = 0f;
						bool flag2 = Plugin.StepRunClip.Value.Equals("None", StringComparison.OrdinalIgnoreCase) && value2.Speed > Plugin.StepOwnRunAboveMetersPerSecond.Value;
						if (value2.Speed > Plugin.StepRunAboveMetersPerSecond.Value && (!BodyRules.StepsAtContact(LiveBody.EnemyDistance(value2.Kelvin), Math.Max(Plugin.StanceMeters.Value, 2f)) || value2.Speed >= Plugin.GuardDropMetersPerSecond.Value))
						{
							flag2 = true;
						}
						measured = ((!flag2 && value2.Speed > Plugin.StepRunAboveMetersPerSecond.Value && ((Vector3)(ref heading)).sqrMagnitude > 0.01f) ? (BestGuardStep(value2, MovePlayer.GuardSteps(value2.Kelvin), ((Vector3)(ref heading)).normalized, value2.Speed) ?? Best(value2, ((Vector3)(ref heading)).normalized, value2.Speed)) : null);
						if (!flag2 && measured == null)
						{
							measured = Stance(MovePlayer.Footwork(value2.Kelvin)) ?? Measure(MovePlayer.StanceClip(value2.Kelvin)) ?? Measure(Plugin.StepStanceClip.Value);
						}
					}
					if (OwnSteps.Carries(value2.Kelvin) && !IsGuardStep(measured))
					{
						measured = null;
					}
					if (measured != value2.Wanted)
					{
						value2.Wanted = measured;
						value2.WantedSince = time;
					}
					bool flag3 = measured != null && value2.Now != null && measured.Share > 0.05f != value2.Now.Share > 0.05f;
					if (measured != null && (value2.Now == null || flag3 || time - value2.WantedSince >= Plugin.StepSwitchSeconds.Value))
					{
						Show(value2, measured);
					}
					float num4 = ((!flag || measured == null || value2.Now == null) ? 0f : 1f);
					value2.Weight = ((value <= 0f) ? num4 : Mathf.MoveTowards(value2.Weight, num4, dt / value));
					if (value2.Weight <= 0f)
					{
						if (!flag)
						{
							Gone.Add(item.Key);
						}
						continue;
					}
					value2.Switch = ((value <= 0f) ? 1f : Mathf.MoveTowards(value2.Switch, 1f, dt / value));
					Measured now = value2.Now;
					float num5 = now.Share * num3;
					float num6 = ((now.Share > 0.05f) ? (((Vector3)(ref val)).magnitude / num5) : (dt / now.Length));
					value2.Phase = (value2.Phase + num6) % 1f;
					float travelX;
					float travelZ;
					float num7 = (IsGuardStep(now) ? MovePlayer.Bank.Sample(now.Move, TimeAt(now, value2.Phase) * now.Move.Duration, value2.Rotations) : ((now.Move != null) ? MovePlayer.SampleLoop(now.Move, value2.Rotations) : CannibalPose.Sample(now.Clip, TimeAt(now, value2.Phase) * now.Clip.length, now.Facing, now.Start, MovePlayer.Bank.BonePaths, value2.Rotations, out travelX, out travelZ)));
					float num8 = value2.Weight * value2.Weight * (3f - 2f * value2.Weight);
					float num9 = value2.Switch * value2.Switch * (3f - 2f * value2.Switch);
					Quaternion rotation = value2.Rig.rotation;
					bool flag4 = WholeBody.Contains(item.Key);
					bool flag5 = Gait.WholeBody(flag4, Plugin.RunLikeCannibals.Value, value2.Speed, Plugin.GuardDropMetersPerSecond.Value);
					if (flag5 != value2.Whole)
					{
						value2.Whole = flag5;
						PoseSmoother.Mark(value2.Kelvin);
					}
					bool[] array = ((!flag5) ? MovePlayer.UpperBody() : (flag4 ? null : MovePlayer.Arms()));
					for (int i = 0; i < value2.Bones.Length; i++)
					{
						value2.From[i] = value2.Bones[i].rotation;
					}
					for (int j = 0; j < value2.Bones.Length; j++)
					{
						if (array == null || !array[j])
						{
							int num10 = 4 * j;
							((Quaternion)(ref val2))..ctor(value2.Rotations[num10], value2.Rotations[num10 + 1], value2.Rotations[num10 + 2], value2.Rotations[num10 + 3]);
							if (num9 < 1f)
							{
								val2 = Quaternion.Slerp(new Quaternion(value2.Previous[num10], value2.Previous[num10 + 1], value2.Previous[num10 + 2], value2.Previous[num10 + 3]), val2, num9);
							}
							value2.Bones[j].rotation = Quaternion.Slerp(value2.From[j], rotation * val2, num8);
						}
					}
					bool value5 = MovePlayer.IsPlaying(value2.Kelvin);
					if (!MovePlayer.IsPlaying(value2.Kelvin) && value2.Bones[0].localPosition != value2.HipsWritten)
					{
						Vector3 localPosition = value2.Bones[0].localPosition;
						localPosition.y = Mathf.Lerp(localPosition.y, value4.LocalY * num7, num8);
						value2.Bones[0].localPosition = localPosition;
						value2.HipsWritten = localPosition;
					}
					bool flag6 = now.Move != null && now.Share <