Decompiled source of Kratos Power Modes Companion v0.2.6

Mods/KratosPunchCompanion.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using BoneLib;
using BoneLib.BoneMenu;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Bonelab;
using Il2CppSLZ.Data;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.AI;
using Il2CppSLZ.Marrow.Combat;
using Il2CppSLZ.Marrow.Interaction;
using Il2CppSLZ.Marrow.Pool;
using Il2CppSLZ.Marrow.PuppetMasta;
using Il2CppSLZ.Marrow.Warehouse;
using Il2CppSLZ.UI;
using Il2CppSLZ.VRMK;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppUltEvents;
using KratosPunchCompanion;
using MelonLoader;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(KratosPowerModesCompanion), "Kratos Power Modes Companion", "0.2.6", "OC3AN_AV3NUE", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
[assembly: AssemblyCompany("KratosPunchCompanion")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.6.0")]
[assembly: AssemblyInformationalVersion("0.2.6")]
[assembly: AssemblyProduct("KratosPunchCompanion")]
[assembly: AssemblyTitle("KratosPunchCompanion")]
[assembly: AssemblyVersion("0.2.6.0")]
[module: RefSafetyRules(11)]
namespace KratosPunchCompanion;

internal static class KratosBoothCompactStrength
{
	private const string HarmonyOwner = "oc3anav3nue.kratos.boothcompactstrength";

	private static readonly Regex Rows = new Regex("(?m)^(?<label>[ \\t]*Strength (?:Upper|Lower):[ \\t]*)(?<value>[0-9]{1,18}(?:[.,][0-9]{1,2})?(?:[eE][+-]?[0-9]{1,2})?)(?=[ \\t]*\\r?$)", RegexOptions.CultureInvariant);

	private static Harmony? harmony;

	private static MethodInfo? getChartLabel;

	private static Action<string>? logger;

	private static AvatarsPanelView? panel;

	private static Component? writtenLabel;

	private static PropertyInfo? labelText;

	private static string? originalText;

	private static string? compactText;

	private static string? lastStockText;

	private static string? lastFormattedText;

	private static bool warned;

	internal static void Install(Action<string> log)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		if (harmony != null)
		{
			return;
		}
		logger = log;
		Harmony val = new Harmony("oc3anav3nue.kratos.boothcompactstrength");
		try
		{
			getChartLabel = AccessTools.PropertyGetter(typeof(SpiderChart), "statText") ?? throw new MissingMemberException("SpiderChart", "statText");
			Patch(val, typeof(AvatarsPanelView), "Activate", Array.Empty<Type>(), "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "StatsDetailButton", new Type[1] { typeof(int) }, "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "SelectItem", new Type[1] { typeof(int) }, "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "BackButton", Array.Empty<Type>(), "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "Deactivate", Array.Empty<Type>(), "ClosePanel");
			Patch(val, typeof(AvatarsPanelView), "OnDisable", Array.Empty<Type>(), "ClosePanel");
			Patch(val, typeof(_UpdateLoop_d__41), "MoveNext", Array.Empty<Type>(), "AfterStockPaint");
			harmony = val;
			log("Kratos Avatar Booth compact strength installed.");
		}
		catch (Exception error)
		{
			val.UnpatchSelf();
			getChartLabel = null;
			Report(error);
		}
	}

	internal static void Uninstall()
	{
		RestoreText();
		panel = null;
		Harmony? obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		harmony = null;
		getChartLabel = null;
		labelText = null;
		lastStockText = null;
		lastFormattedText = null;
		logger = null;
		warned = false;
	}

	private static void Patch(Harmony owner, Type type, string method, Type[] parameters, string postfix)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type, method, parameters, (Type[])null) ?? throw new MissingMethodException(type.FullName, method);
		owner.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(KratosBoothCompactStrength), postfix, (Type[])null)
		{
			priority = 0
		}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static void ObservePanel(AvatarsPanelView __instance)
	{
		try
		{
			if (Object.op_Implicit((Object)(object)__instance) && __instance.isBodyMall)
			{
				if ((Object)(object)panel != (Object)(object)__instance || !SelectedPreview(__instance, __instance.spiderChart))
				{
					RestoreText();
				}
				panel = __instance;
			}
		}
		catch (Exception error)
		{
			Report(error);
		}
	}

	private static void ClosePanel(AvatarsPanelView __instance)
	{
		if (!((Object)(object)panel != (Object)(object)__instance))
		{
			RestoreText();
			panel = null;
		}
	}

	private static bool SelectedPreview(AvatarsPanelView view, SpiderChart chart)
	{
		if (!Object.op_Implicit((Object)(object)chart) || !Object.op_Implicit((Object)(object)view) || !view.isBodyMall || !((Component)view).gameObject.activeInHierarchy || !Object.op_Implicit((Object)(object)view.canvas) || !view.canvas.activeInHierarchy || !Object.op_Implicit((Object)(object)view.statsPage) || !view.statsPage.activeInHierarchy || (Object)(object)chart != (Object)(object)view.spiderChart)
		{
			return false;
		}
		AvatarCrate avatarSelection = view.avatarSelection;
		Barcode val = (Object.op_Implicit((Object)(object)avatarSelection) ? ((Scannable)avatarSelection).Barcode : null);
		if (!KratosPunchMod.IsSupportedAvatar((val != null) ? val.ID : null))
		{
			return false;
		}
		Avatar previewAvatar = view.previewAvatar;
		Dictionary<Barcode, Avatar> cachedPreviews = view.cachedPreviews;
		Avatar val2 = default(Avatar);
		if (Object.op_Implicit((Object)(object)previewAvatar) && (Object)(object)previewAvatar == (Object)(object)chart.previewAvatar && cachedPreviews != null && cachedPreviews.TryGetValue(val, ref val2))
		{
			return (Object)(object)previewAvatar == (Object)(object)val2;
		}
		return false;
	}

	private static void AfterStockPaint(_UpdateLoop_d__41 __instance, bool __result)
	{
		try
		{
			AvatarsPanelView val = panel;
			if (harmony == null || val == null || !Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			SpiderChart _4__this = __instance.__4__this;
			if (!Object.op_Implicit((Object)(object)_4__this) || (Object)(object)_4__this != (Object)(object)val.spiderChart)
			{
				return;
			}
			if (!__result || !SelectedPreview(val, _4__this))
			{
				RestoreText();
				return;
			}
			object? obj = getChartLabel?.Invoke(_4__this, null);
			Component val2 = (Component)((obj is Component) ? obj : null);
			if (val2 == null || !Object.op_Implicit((Object)(object)val2) || !val2.gameObject.activeInHierarchy)
			{
				RestoreText();
				return;
			}
			if (Object.op_Implicit((Object)(object)writtenLabel) && (Object)(object)writtenLabel != (Object)(object)val2)
			{
				RestoreText();
			}
			PropertyInfo? propertyInfo = labelText;
			if ((object)propertyInfo == null || propertyInfo.DeclaringType?.IsInstanceOfType(val2) != true)
			{
				labelText = ((object)val2).GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
			}
			if (labelText?.PropertyType != typeof(string) || !labelText.CanRead || !labelText.CanWrite)
			{
				throw new MissingMemberException(((object)val2).GetType().FullName, "text");
			}
			string text = (string)labelText.GetValue(val2);
			if (text != null && text.Length <= 512 && (!((Object)(object)val2 == (Object)(object)writtenLabel) || !string.Equals(text, compactText, StringComparison.Ordinal)))
			{
				if (!string.Equals(text, lastStockText, StringComparison.Ordinal))
				{
					lastFormattedText = FormatStockText(text);
					lastStockText = text;
				}
				string text2 = lastFormattedText;
				if (text2 != null && !string.Equals(text, text2, StringComparison.Ordinal))
				{
					labelText.SetValue(val2, text2);
					writtenLabel = val2;
					originalText = text;
					compactText = text2;
				}
			}
		}
		catch (Exception error)
		{
			RestoreText();
			Report(error);
		}
	}

	private static string FormatStockText(string stock)
	{
		return Rows.Replace(stock, delegate(Match match)
		{
			string value = match.Groups["value"].Value;
			bool flag = value.Contains(',');
			if (float.TryParse(flag ? value.Replace(',', '.') : value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				string text = KratosPunchMod.CompactStrength(result);
				if (text != null)
				{
					if (flag)
					{
						text = text.Replace(",", "\u202f").Replace('.', ',');
					}
					return match.Groups["label"].Value + text;
				}
			}
			return match.Value;
		});
	}

	private static void RestoreText()
	{
		Component val = writtenLabel;
		string value = originalText;
		string b = compactText;
		writtenLabel = null;
		originalText = null;
		compactText = null;
		try
		{
			if (Object.op_Implicit((Object)(object)val) && (object)labelText != null && string.Equals((string)labelText.GetValue(val), b, StringComparison.Ordinal))
			{
				labelText.SetValue(val, value);
			}
		}
		catch (Exception error)
		{
			Report(error);
		}
	}

	private static void Report(Exception error)
	{
		if (!warned)
		{
			warned = true;
			logger?.Invoke("Kratos Avatar Booth compact strength unavailable: " + error.GetBaseException().Message);
		}
	}
}
internal static class KratosBoothStatsMirror
{
	private readonly record struct LiveStats(float Height, float Mass, float Agility, float Speed, float Upper, float Lower, float Vitality, float Intelligence);

	private sealed class Source(RigManager rig, Avatar avatar, PhysicsRig physics, Transform island)
	{
		public readonly RigManager Rig = rig;

		public readonly Avatar Avatar = avatar;

		public readonly PhysicsRig Physics = physics;

		public readonly Transform Island = island;

		public LiveStats Stats;

		public string? LastStockText;

		public string? FormattedText;

		public long NextRead;
	}

	private const string HarmonyOwner = "oc3anav3nue.kratos.boothstats";

	private const string NextRow = "[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*";

	private const string Decimal = "[0-9]+[.,][0-9]{2}";

	private static readonly Regex StockRows = new Regex("\\A[ \\t]*Height:[ \\t]*(?<cm>[0-9]+)[ \\t]+cm[ \\t]+(?<ft>[0-9]+)[ \\t]+ft[ \\t]+(?<in>[0-9]+)[ \\t]+in[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Mass:[ \\t]*(?<mass>[0-9]+[.,][0-9]{2})[ \\t]+kg[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Agility:[ \\t]*(?<agility>[0-9]+[.,][0-9]{2})[ \\t]+Ns[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Speed:[ \\t]*(?<speed>[0-9]+[.,][0-9]{2})[ \\t]+m/s[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Strength Upper:[ \\t]*(?<upper>[0-9]+[.,][0-9]{2})[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Strength Lower:[ \\t]*(?<lower>[0-9]+[.,][0-9]{2})[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Vitality:[ \\t]*(?<vitality>[0-9]+[.,][0-9]{2})[ \\t]*\\r?\\n(?:[ \\t]*\\r?\\n)*[ \\t]*Intelligence:[ \\t]*(?<intelligence>[0-9]+[.,][0-9]{2})[ \\t\\r\\n]*\\z", RegexOptions.CultureInvariant);

	private static Harmony? harmony;

	private static Action<string>? log;

	private static MethodInfo? getChartLabel;

	private static PropertyInfo? labelText;

	private static AvatarsPanelView? panel;

	private static Source? source;

	private static Component? writtenLabel;

	private static string? nativeText;

	private static string? writtenText;

	private static bool warned;

	public static void Install(Action<string> logger)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		if (harmony != null)
		{
			return;
		}
		log = logger;
		Harmony val = new Harmony("oc3anav3nue.kratos.boothstats");
		try
		{
			getChartLabel = AccessTools.PropertyGetter(typeof(SpiderChart), "statText") ?? throw new MissingMemberException("SpiderChart", "statText");
			Patch(val, typeof(AvatarsPanelView), "Activate", Type.EmptyTypes, "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "StatsDetailButton", new Type[1] { typeof(int) }, "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "SelectItem", new Type[1] { typeof(int) }, "ObservePanel");
			Patch(val, typeof(AvatarsPanelView), "Deactivate", Type.EmptyTypes, "ObserveClose");
			Patch(val, typeof(_UpdateLoop_d__41), "MoveNext", Type.EmptyTypes, "AfterStockPaint");
			harmony = val;
			logger("Kratos Body Mall stats mirror installed.");
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			harmony = null;
			logger("Kratos Body Mall stats mirror unavailable: " + ex.GetBaseException().Message);
		}
	}

	public static void Uninstall()
	{
		RestoreNativeText();
		panel = null;
		source = null;
		Harmony? obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		harmony = null;
		getChartLabel = null;
		labelText = null;
		log = null;
		warned = false;
	}

	private static void Patch(Harmony owner, Type type, string name, Type[] arguments, string after)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type, name, arguments, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
		HarmonyMethod val = new HarmonyMethod(typeof(KratosBoothStatsMirror), after, (Type[])null)
		{
			priority = 0
		};
		owner.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static void ObservePanel(AvatarsPanelView __instance)
	{
		if (harmony == null)
		{
			return;
		}
		try
		{
			if (Object.op_Implicit((Object)(object)__instance) && __instance.isBodyMall)
			{
				if ((Object)(object)panel != (Object)(object)__instance)
				{
					RestoreNativeText();
					source = null;
					panel = __instance;
				}
				if (!StatsVisible(__instance))
				{
					RestoreNativeText();
					source = null;
				}
				else
				{
					Mirror(__instance, __instance.spiderChart);
				}
			}
		}
		catch (Exception error)
		{
			RestoreNativeText();
			Report(error);
		}
	}

	private static void ObserveClose(AvatarsPanelView __instance)
	{
		if (!((Object)(object)panel != (Object)(object)__instance))
		{
			RestoreNativeText();
			panel = null;
			source = null;
		}
	}

	private static void AfterStockPaint(_UpdateLoop_d__41 __instance, bool __result)
	{
		AvatarsPanelView val = panel;
		if (harmony == null || val == null || !Object.op_Implicit((Object)(object)val))
		{
			return;
		}
		try
		{
			SpiderChart _4__this = __instance.__4__this;
			if (Object.op_Implicit((Object)(object)_4__this) && !((Object)(object)_4__this != (Object)(object)val.spiderChart))
			{
				if (!__result || !StatsVisible(val))
				{
					RestoreNativeText();
					source = null;
				}
				else
				{
					Mirror(val, _4__this);
				}
			}
		}
		catch (Exception error)
		{
			RestoreNativeText();
			Report(error);
		}
	}

	private static bool StatsVisible(AvatarsPanelView view)
	{
		if (Object.op_Implicit((Object)(object)view) && view.isBodyMall && ((Component)view).gameObject.activeInHierarchy && Object.op_Implicit((Object)(object)view.canvas) && view.canvas.activeInHierarchy && Object.op_Implicit((Object)(object)view.statsPage))
		{
			return view.statsPage.activeInHierarchy;
		}
		return false;
	}

	private static void Mirror(AvatarsPanelView view, SpiderChart chart)
	{
		RigManager rigManager = Player.RigManager;
		Avatar val = (Object.op_Implicit((Object)(object)rigManager) ? rigManager.avatar : null);
		AvatarCrate avatarSelection = view.avatarSelection;
		object obj;
		if (!Object.op_Implicit((Object)(object)avatarSelection))
		{
			obj = null;
		}
		else
		{
			Barcode barcode = ((Scannable)avatarSelection).Barcode;
			obj = ((barcode != null) ? barcode.ID : null);
		}
		string text;
		switch ((string)obj)
		{
		case "OC3ANAV3NUE.KratosPowerPlaytest.Avatar.KratosPowerPlaytest":
			if (((Scannable)avatarSelection).Title == "Kratos 1 Calm")
			{
				text = "1";
				break;
			}
			goto default;
		case "OC3ANAV3NUE.KratosPowerPlaytest.Avatar.Kratos2Angered":
			if (((Scannable)avatarSelection).Title == "Kratos 2 Angered")
			{
				text = "2";
				break;
			}
			goto default;
		case "OC3ANAV3NUE.KratosPowerPlaytest.Avatar.Kratos3SpartanFury":
			if (((Scannable)avatarSelection).Title == "Kratos 3 Spartan Fury")
			{
				text = "3";
				break;
			}
			goto default;
		case "OC3ANAV3NUE.KratosPowerPlaytest.Avatar.Kratos4GodOfWar":
			if (((Scannable)avatarSelection).Title == "Kratos 4 God of War")
			{
				text = "4";
				break;
			}
			goto default;
		case "OC3ANAV3NUE.KratosPowerPlaytest.Avatar.Kratos5LoreAccurate":
			if (((Scannable)avatarSelection).Title == "Kratos 5 Lore Accurate")
			{
				text = "5";
				break;
			}
			goto default;
		default:
			text = null;
			break;
		}
		string text2 = text;
		if (Object.op_Implicit((Object)(object)chart) && text2 != null && Object.op_Implicit((Object)(object)rigManager) && val != null && Object.op_Implicit((Object)(object)val) && ((Component)val).gameObject.activeInHierarchy && !rigManager._avatarDirty && !((Object)(object)view.rigManager != (Object)(object)rigManager))
		{
			AvatarCrateReference avatarCrate = rigManager.AvatarCrate;
			object barcode2;
			if (avatarCrate == null)
			{
				barcode2 = null;
			}
			else
			{
				Barcode barcode3 = ((ScannableReference)avatarCrate).Barcode;
				barcode2 = ((barcode3 != null) ? barcode3.ID : null);
			}
			if (KratosPunchMod.IsSupportedAvatar((string?)barcode2))
			{
				if (KratosBoothStatsMirror.source == null || (Object)(object)KratosBoothStatsMirror.source.avatar != (Object)(object)val || (Object)(object)KratosBoothStatsMirror.source.rig != (Object)(object)rigManager || (Object)(object)KratosBoothStatsMirror.source.physics != (Object)(object)rigManager.physicsRig || !Object.op_Implicit((Object)(object)KratosBoothStatsMirror.source.island))
				{
					KratosBoothStatsMirror.source = FindSource(rigManager, val);
				}
				Source source = KratosBoothStatsMirror.source;
				if (source == null || Record(source.island, "SelectedLevel") != text2 || !((Component)source.island).gameObject.activeInHierarchy || !ValidReadout(source.island))
				{
					RestoreNativeText();
					return;
				}
				object? obj2 = getChartLabel?.Invoke(chart, null);
				Component val2 = (Component)((obj2 is Component) ? obj2 : null);
				if (val2 == null || !Object.op_Implicit((Object)(object)val2) || !val2.gameObject.activeInHierarchy)
				{
					return;
				}
				if ((Object)(object)val2 != (Object)(object)writtenLabel)
				{
					RestoreNativeText();
				}
				if ((object)labelText == null)
				{
					labelText = ((object)val2).GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
				}
				if (labelText?.PropertyType != typeof(string) || !labelText.CanRead || !labelText.CanWrite)
				{
					throw new MissingMemberException(((object)val2).GetType().FullName, "text");
				}
				string text3 = (string)labelText.GetValue(val2);
				string text4 = (((Object)(object)val2 == (Object)(object)writtenLabel && string.Equals(text3, writtenText, StringComparison.Ordinal)) ? nativeText : text3);
				RefreshSnapshot(source);
				if (!string.Equals(text4, source.LastStockText, StringComparison.Ordinal))
				{
					source.LastStockText = text4;
					source.FormattedText = FormatStockRows(text4, source.Stats);
				}
				string formattedText = source.FormattedText;
				if (formattedText == null)
				{
					RestoreNativeText();
				}
				else if (!string.Equals(text3, formattedText, StringComparison.Ordinal))
				{
					if ((Object)(object)val2 != (Object)(object)writtenLabel || !string.Equals(text3, writtenText, StringComparison.Ordinal))
					{
						nativeText = text3;
					}
					labelText.SetValue(val2, formattedText);
					writtenLabel = val2;
					writtenText = formattedText;
				}
				return;
			}
		}
		RestoreNativeText();
		KratosBoothStatsMirror.source = null;
	}

	private static Source? FindSource(RigManager rig, Avatar avatar)
	{
		PhysicsRig physicsRig = rig.physicsRig;
		if (!Object.op_Implicit((Object)(object)physicsRig))
		{
			return null;
		}
		Transform val = KratosPunchMod.FindOwnedCleanupIsland(rig, avatar, physicsRig);
		if (val != null)
		{
			return new Source(rig, avatar, physicsRig, val);
		}
		return null;
	}

	private static void RefreshSnapshot(Source current)
	{
		long timestamp = Stopwatch.GetTimestamp();
		if (timestamp >= current.NextRead)
		{
			current.NextRead = timestamp + Stopwatch.Frequency / 2;
			Avatar avatar = current.avatar;
			LiveStats liveStats = new LiveStats(avatar.height, avatar.massTotal, avatar.agility, avatar.speed, avatar.strengthUpper, avatar.strengthLower, avatar.vitality, avatar.intelligence);
			if (!(current.Stats == liveStats))
			{
				current.Stats = liveStats;
				current.LastStockText = null;
				current.FormattedText = null;
			}
		}
	}

	private static bool ValidReadout(Transform island)
	{
		if (Flag(island, "OwnerValid", expected: true) && Flag(island, "Ready", expected: true) && Flag(island, "SessionActive", expected: true) && Flag(island, "SessionValid", expected: true) && Flag(island, "OwnReadValid", expected: true) && Flag(island, "Busy", expected: false) && Flag(island, "DeathPending", expected: false))
		{
			return Flag(island, "InternalHeightTransition", expected: false);
		}
		return false;
	}

	private static bool Flag(Transform island, string name, bool expected)
	{
		Transform val = island.Find("State/" + name);
		if (Object.op_Implicit((Object)(object)val))
		{
			return ((Component)val).gameObject.activeSelf == expected;
		}
		return false;
	}

	private static string? Record(Transform island, string name)
	{
		Transform val = island.Find("Variables/" + name);
		if (!Object.op_Implicit((Object)(object)val) || val.childCount != 1)
		{
			return null;
		}
		return ((Object)val.GetChild(0)).name;
	}

	private static string? FormatStockRows(string? stock, LiveStats stats)
	{
		if (stock == null || stock.Length > 512)
		{
			return null;
		}
		Match match = StockRows.Match(stock);
		if (!match.Success)
		{
			return null;
		}
		StringBuilder output = new StringBuilder(stock);
		DecimalRow("intelligence", stats.Intelligence);
		DecimalRow("vitality", stats.Vitality);
		DecimalRow("lower", stats.Lower);
		DecimalRow("upper", stats.Upper);
		DecimalRow("speed", stats.Speed);
		DecimalRow("agility", stats.Agility);
		DecimalRow("mass", stats.Mass);
		if (float.IsFinite(stats.Height))
		{
			float height = stats.Height;
			if (height > 0f && height < 100f)
			{
				float num = stats.Height * 100f;
				float num2 = num * 0.39370078f / 12f;
				float num3 = MathF.Floor(num2);
				float value = MathF.Floor((num2 - num3) * 12f);
				WholeRow("in", value);
				WholeRow("ft", num3);
				WholeRow("cm", num);
			}
		}
		return output.ToString();
		void DecimalRow(string name, float num4)
		{
			if (float.IsFinite(num4) && !(num4 < 0f))
			{
				Group obj = match.Groups[name];
				string text = num4.ToString("F2", CultureInfo.InvariantCulture);
				if (obj.Value.Contains(','))
				{
					text = text.Replace('.', ',');
				}
				output.Remove(obj.Index, obj.Length).Insert(obj.Index, text);
			}
		}
		void WholeRow(string name, float num4)
		{
			Group obj = match.Groups[name];
			output.Remove(obj.Index, obj.Length).Insert(obj.Index, num4.ToString("F0", CultureInfo.InvariantCulture));
		}
	}

	private static void RestoreNativeText()
	{
		Component val = writtenLabel;
		string value = nativeText;
		string b = writtenText;
		writtenLabel = null;
		nativeText = null;
		writtenText = null;
		try
		{
			if (val != null && Object.op_Implicit((Object)(object)val) && (object)labelText != null && string.Equals((string)labelText.GetValue(val), b, StringComparison.Ordinal))
			{
				labelText.SetValue(val, value);
			}
		}
		catch (Exception error)
		{
			Report(error);
		}
		labelText = null;
	}

	private static void Report(Exception error)
	{
		if (!warned)
		{
			warned = true;
			log?.Invoke("Kratos Body Mall stats read skipped: " + error.GetBaseException().Message);
		}
	}
}
internal static class KratosFusionNpcPunch
{
	private sealed class FusionApi
	{
		private readonly Func<bool> isHost;

		private readonly Func<bool> isLevelNetworked;

		private readonly Func<bool> isLoading;

		private readonly Func<bool> interactionDisabled;

		private readonly PropertyInfo lobbyInfo;

		private readonly PropertyInfo lobbyPrivacy;

		private readonly object privatePrivacy;

		private readonly PropertyInfo activeGamemode;

		private readonly Type puppetExtenderType;

		private readonly Type playerExtenderType;

		private readonly Type propExtenderType;

		private readonly object puppetCache;

		private readonly object pooleeCache;

		private readonly MethodInfo getPuppet;

		private readonly MethodInfo getPoolee;

		private readonly PropertyInfo isRegistered;

		private readonly PropertyInfo isQueued;

		private readonly PropertyInfo isDestroyed;

		private readonly PropertyInfo isOwner;

		private readonly PropertyInfo source;

		private readonly object playerSource;

		private readonly MethodInfo getExtender;

		private readonly PropertyInfo puppetComponent;

		private readonly PropertyInfo propMarrowEntity;

		public FusionApi(Assembly assembly)
		{
			isHost = StaticBool(Property(Find("Network.NetworkInfo"), "IsHost").GetMethod);
			isLevelNetworked = StaticBool(Property(Find("Scene.NetworkSceneManager"), "IsLevelNetworked").GetMethod);
			isLoading = StaticBool(Method(Find("Scene.FusionSceneManager"), "IsLoading", Array.Empty<Type>()));
			interactionDisabled = StaticBool(Property(Find("Player.LocalControls"), "DisableInteraction").GetMethod);
			lobbyInfo = Property(Find("Network.LobbyInfoManager"), "LobbyInfo");
			lobbyPrivacy = Property(lobbyInfo.PropertyType, "Privacy");
			privatePrivacy = Enum.Parse(lobbyPrivacy.PropertyType, "PRIVATE");
			activeGamemode = Property(Find("SDK.Gamemodes.GamemodeManager"), "ActiveGamemode");
			Type type = Find("Entities.NetworkEntity");
			puppetExtenderType = Find("Marrow.Extenders.PuppetMasterExtender");
			playerExtenderType = Find("Entities.NetworkPlayer");
			propExtenderType = Find("Entities.NetworkProp");
			puppetCache = Cache(puppetExtenderType);
			pooleeCache = Cache(Find("Marrow.Extenders.PooleeExtender"));
			getPuppet = Method(puppetCache.GetType(), "Get", new Type[1] { typeof(PuppetMaster) });
			getPoolee = Method(pooleeCache.GetType(), "Get", new Type[1] { typeof(Poolee) });
			isRegistered = Property(type, "IsRegistered");
			isQueued = Property(type, "IsQueued");
			isDestroyed = Property(type, "IsDestroyed");
			isOwner = Property(type, "IsOwner");
			source = Property(type, "Source");
			playerSource = Enum.Parse(source.PropertyType, "Player");
			getExtender = Method(type, "GetExtender", new Type[1] { typeof(Type) });
			puppetComponent = Property(puppetExtenderType, "Component");
			propMarrowEntity = Property(propExtenderType, "MarrowEntity");
			Type Find(string name)
			{
				return assembly.GetType("LabFusion." + name, throwOnError: true);
			}
		}

		internal bool TryGetOwnedNpc(PuppetMaster puppet, out object? entity)
		{
			entity = null;
			if (isHost() && isLevelNetworked() && !isLoading() && !interactionDisabled() && activeGamemode.GetValue(null) == null)
			{
				object value = lobbyInfo.GetValue(null);
				if (value != null && object.Equals(lobbyPrivacy.GetValue(value), privatePrivacy))
				{
					object obj = getPuppet.Invoke(puppetCache, new object[1] { puppet });
					if (obj != null)
					{
						object value2 = isRegistered.GetValue(obj);
						if (value2 is bool && (bool)value2)
						{
							value2 = isQueued.GetValue(obj);
							if (value2 is bool && !(bool)value2)
							{
								value2 = isDestroyed.GetValue(obj);
								if (value2 is bool && !(bool)value2)
								{
									value2 = isOwner.GetValue(obj);
									if (value2 is bool && (bool)value2 && object.Equals(source.GetValue(obj), playerSource) && getExtender.Invoke(obj, new object[1] { playerExtenderType }) == null)
									{
										object obj2 = getExtender.Invoke(obj, new object[1] { puppetExtenderType });
										object obj3 = getExtender.Invoke(obj, new object[1] { propExtenderType });
										if (obj2 != null)
										{
											object? value3 = puppetComponent.GetValue(obj2);
											PuppetMaster val = (PuppetMaster)((value3 is PuppetMaster) ? value3 : null);
											if (val != null && !((Object)(object)val != (Object)(object)puppet) && obj3 != null)
											{
												object? value4 = propMarrowEntity.GetValue(obj3);
												MarrowEntity val2 = (MarrowEntity)((value4 is MarrowEntity) ? value4 : null);
												if (val2 != null && Object.op_Implicit((Object)(object)val2))
												{
													Poolee componentInParent = ((Component)val2).GetComponentInParent<Poolee>();
													if (!Object.op_Implicit((Object)(object)componentInParent) || getPoolee.Invoke(pooleeCache, new object[1] { componentInParent }) != obj)
													{
														return false;
													}
													entity = obj;
													return true;
												}
											}
										}
										return false;
									}
								}
							}
						}
					}
					return false;
				}
			}
			return false;
		}

		private static Func<bool> StaticBool(MethodInfo method)
		{
			return method.CreateDelegate<Func<bool>>();
		}

		private static object Cache(Type extender)
		{
			return extender.GetField("Cache", BindingFlags.Static | BindingFlags.Public)?.GetValue(null) ?? throw new MissingFieldException(extender.FullName, "Cache");
		}

		private static PropertyInfo Property(Type type, string name)
		{
			return type.GetProperty(name) ?? throw new MissingMemberException(type.FullName, name);
		}

		private static MethodInfo Method(Type type, string name, Type[] parameters)
		{
			return type.GetMethod(name, parameters) ?? throw new MissingMethodException(type.FullName, name);
		}
	}

	private static Assembly? cachedAssembly;

	private static FusionApi? api;

	internal static bool TryGetOwnedNpc(Assembly assembly, PuppetMaster puppet, out object? entity)
	{
		entity = null;
		if (cachedAssembly != assembly)
		{
			cachedAssembly = assembly;
			api = null;
			try
			{
				api = new FusionApi(assembly);
			}
			catch (Exception)
			{
				return false;
			}
		}
		if (api != null)
		{
			return api.TryGetOwnedNpc(puppet, out entity);
		}
		return false;
	}
}
internal static class KratosFusionPlayerPunch
{
	private sealed class PlayerApi
	{
		public readonly Assembly Assembly;

		private readonly MethodInfo tryGetPlayer;

		private readonly MethodInfo canAttack;

		private readonly PropertyInfo networkEntity;

		private readonly PropertyInfo hasRig;

		private readonly PropertyInfo receivedPose;

		private readonly PropertyInfo registered;

		private readonly PropertyInfo destroyed;

		private readonly PropertyInfo isOwner;

		private readonly Func<bool> hasServer;

		private readonly Func<bool> isHost;

		private readonly Func<bool> isLevelNetworked;

		private readonly Func<bool> isLoading;

		private readonly Func<bool> interactionDisabled;

		private readonly PropertyInfo activeGamemode;

		private readonly PropertyInfo lobbyInfo;

		private readonly PropertyInfo privacy;

		private readonly PropertyInfo friendlyFire;

		private readonly PropertyInfo mortality;

		private readonly PropertyInfo knockout;

		private readonly object privatePrivacy;

		internal PlayerApi(Assembly assembly)
		{
			Assembly = assembly;
			Type type = Find("Entities.NetworkPlayer");
			Type type2 = Find("Entities.NetworkEntity");
			tryGetPlayer = Find("Entities.NetworkPlayerManager").GetMethod("TryGetPlayer", new Type[2]
			{
				typeof(RigManager),
				type.MakeByRefType()
			});
			canAttack = Find("Player.NetworkCombatManager").GetMethod("CanAttack", new Type[1] { type });
			networkEntity = Property(type, "NetworkEntity");
			hasRig = Property(type, "HasRig");
			receivedPose = Property(type, "ReceivedPose");
			registered = Property(type2, "IsRegistered");
			destroyed = Property(type2, "IsDestroyed");
			isOwner = Property(type2, "IsOwner");
			Type type3 = Find("Network.NetworkInfo");
			hasServer = ReadBool(type3, "HasServer");
			isHost = ReadBool(type3, "IsHost");
			isLevelNetworked = ReadBool(Find("Scene.NetworkSceneManager"), "IsLevelNetworked");
			isLoading = Find("Scene.FusionSceneManager").GetMethod("IsLoading", Type.EmptyTypes).CreateDelegate<Func<bool>>();
			interactionDisabled = ReadBool(Find("Player.LocalControls"), "DisableInteraction");
			activeGamemode = Property(Find("SDK.Gamemodes.GamemodeManager"), "ActiveGamemode");
			lobbyInfo = Property(Find("Network.LobbyInfoManager"), "LobbyInfo");
			privacy = Property(lobbyInfo.PropertyType, "Privacy");
			privatePrivacy = Enum.Parse(privacy.PropertyType, "PRIVATE");
			friendlyFire = Property(lobbyInfo.PropertyType, "FriendlyFire");
			mortality = Property(lobbyInfo.PropertyType, "Mortality");
			knockout = Property(lobbyInfo.PropertyType, "Knockout");
			Type Find(string name)
			{
				return assembly.GetType("LabFusion." + name, throwOnError: true);
			}
		}

		internal bool TryGetAllowedPlayer(RigManager target, out object player)
		{
			player = null;
			if (hasServer() && isHost() && isLevelNetworked() && !isLoading() && !interactionDisabled() && activeGamemode.GetValue(null) == null)
			{
				object value = lobbyInfo.GetValue(null);
				if (value != null && object.Equals(privacy.GetValue(value), privatePrivacy))
				{
					object value2 = friendlyFire.GetValue(value);
					if (value2 is bool && (bool)value2)
					{
						value2 = mortality.GetValue(value);
						if (value2 is bool && (bool)value2)
						{
							value2 = knockout.GetValue(value);
							if (value2 is bool && !(bool)value2)
							{
								object[] array = new object[2] { target, null };
								value2 = tryGetPlayer.Invoke(null, array);
								if (value2 is bool && (bool)value2)
								{
									object obj = array[1];
									if (obj != null)
									{
										value2 = hasRig.GetValue(obj);
										if (value2 is bool && (bool)value2)
										{
											value2 = receivedPose.GetValue(obj);
											if (value2 is bool && (bool)value2)
											{
												object value3 = networkEntity.GetValue(obj);
												if (value3 != null)
												{
													value2 = registered.GetValue(value3);
													if (value2 is bool && (bool)value2)
													{
														value2 = destroyed.GetValue(value3);
														if (value2 is bool && !(bool)value2)
														{
															value2 = isOwner.GetValue(value3);
															if (value2 is bool && !(bool)value2)
															{
																value2 = canAttack.Invoke(null, new object[1] { obj });
																if (value2 is bool && (bool)value2)
																{
																	player = obj;
																	return true;
																}
															}
														}
													}
												}
											}
										}
									}
								}
								return false;
							}
						}
					}
				}
			}
			return false;
		}

		private static PropertyInfo Property(Type type, string name)
		{
			return type.GetProperty(name) ?? throw new MissingMemberException(type.FullName, name);
		}

		private static Func<bool> ReadBool(Type type, string name)
		{
			return Property(type, name).GetMethod.CreateDelegate<Func<bool>>();
		}
	}

	private static Harmony? hooks;

	private static MethodInfo? receiver;

	private static PlayerApi? api;

	internal static bool IsInstalled => hooks != null;

	internal static void Install(Action<string> log)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Expected O, but got Unknown
		//IL_00e0: Expected O, but got Unknown
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Expected O, but got Unknown
		if (hooks != null || (int)Application.platform != 11)
		{
			return;
		}
		Harmony val = new Harmony("oc3anav3nue.kratos.fusionplayerpunch");
		try
		{
			receiver = AccessTools.DeclaredMethod(typeof(PlayerDamageReceiver), "ReceiveAttack", new Type[1] { typeof(Attack) }, (Type[])null);
			if (receiver?.ReturnType != typeof(void))
			{
				throw new MissingMethodException("ReceiveAttack");
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(KratosFusionPlayerPunch), "BeforePlayerAttack", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(KratosFusionPlayerPunch), "RestoreAfterFusion", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(KratosFusionPlayerPunch), "AfterPlayerAttack", (Type[])null, (Type[])null);
			val.Patch((MethodBase)receiver, new HarmonyMethod(methodInfo)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null);
			val.Patch((MethodBase)receiver, new HarmonyMethod(methodInfo2)
			{
				priority = 0
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			hooks = val;
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			receiver = null;
			log("Kratos private Fusion player punch unavailable: " + ex.GetBaseException().Message);
		}
	}

	internal static void Uninstall()
	{
		Harmony? obj = hooks;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		hooks = null;
		receiver = null;
		api = null;
	}

	private static void BeforePlayerAttack(PlayerDamageReceiver __instance, ref Attack __0, out Attack? __state)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Invalid comparison between Unknown and I4
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_027b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0285: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Expected O, but got Unknown
		__state = null;
		KratosPunchMod.PlayerPunch currentPlayerPunch = KratosPunchMod.CurrentPlayerPunch;
		if (hooks == null || currentPlayerPunch == null || currentPlayerPunch.Used)
		{
			return;
		}
		try
		{
			Attack val = __0;
			if (!Object.op_Implicit((Object)(object)__instance) || val == null || !Object.op_Implicit((Object)(object)currentPlayerPunch.Target) || (Object)(object)val.collider != (Object)(object)currentPlayerPunch.Target || (int)val.attackType != 2 || !float.IsFinite(val.damage) || val.damage <= 0f || (Object)(object)((Component)currentPlayerPunch.Target).GetComponentInParent<PlayerDamageReceiver>() != (Object)(object)__instance)
			{
				return;
			}
			TriggerRefProxy proxy = val.proxy;
			Health health = __instance.health;
			RigManager val2 = (Object.op_Implicit((Object)(object)health) ? health._rigManager : null);
			if (!Object.op_Implicit((Object)(object)proxy) || !Object.op_Implicit((Object)(object)proxy.root) || (Object)(object)RigManager.Cache.Get(proxy.root) != (Object)(object)currentPlayerPunch.Rig || !Object.op_Implicit((Object)(object)val2) || (Object)(object)val2 == (Object)(object)currentPlayerPunch.Rig || (Object)(object)val2.health != (Object)(object)health || val2._avatarDirty || (Object)(object)((Component)currentPlayerPunch.Target).GetComponentInParent<RigManager>() != (Object)(object)val2 || !KratosPunchMod.TryLocalLore(currentPlayerPunch.Source, currentPlayerPunch.SourceCollider, out RigManager rig, out Avatar avatar) || (Object)(object)rig != (Object)(object)currentPlayerPunch.Rig || (Object)(object)avatar != (Object)(object)currentPlayerPunch.Avatar || !KratosPunchMod.TryGetKnownFusion(out Assembly fusion) || (object)fusion == null)
			{
				return;
			}
			if (api?.Assembly != fusion)
			{
				api = new PlayerApi(fusion);
			}
			if (!api.TryGetAllowedPlayer(val2, out object player) || !KratosFusionPvpConsent.TargetHasOptedIn(fusion, player) || !RunsBeforeFusion(fusion))
			{
				return;
			}
			float max_Health = health.max_Health;
			float curr_Health = health.curr_Health;
			if (float.IsFinite(max_Health) && float.IsFinite(curr_Health) && !(max_Health <= 0f) && !(curr_Health <= 0f) && !(max_Health > 100000f) && !(curr_Health > 100000f))
			{
				float num = MathF.Max(max_Health, curr_Health) * 2f;
				if (!(val.damage >= num))
				{
					Attack val3 = new Attack
					{
						damage = num,
						normal = val.normal,
						origin = val.origin,
						direction = val.direction,
						backFacing = val.backFacing,
						OrderInPool = val.OrderInPool,
						collider = val.collider,
						attackType = val.attackType,
						proxy = proxy
					};
					currentPlayerPunch.Used = true;
					__state = val;
					__0 = val3;
				}
			}
		}
		catch (Exception)
		{
		}
	}

	private static Exception? AfterPlayerAttack(Exception? __exception, Attack? __state, ref Attack __0)
	{
		RestoreAfterFusion(__state, ref __0);
		return __exception;
	}

	private static void RestoreAfterFusion(Attack? __state, ref Attack __0)
	{
		if (__state != null)
		{
			__0 = __state;
		}
	}

	private static bool RunsBeforeFusion(Assembly assembly)
	{
		return (Harmony.GetPatchInfo((MethodBase)receiver)?.Prefixes)?.Any((Patch patch) => patch.PatchMethod.DeclaringType?.Assembly == assembly && patch.PatchMethod.DeclaringType.FullName == "LabFusion.Patching.PlayerDamageReceiverPatches" && patch.PatchMethod.Name == "ReceiveAttack" && patch.priority > 0 && patch.priority < 800 && !patch.before.Contains<string>(hooks.Id, StringComparer.Ordinal)) ?? false;
	}
}
internal static class KratosFusionPvpConsent
{
	private sealed record Connection(object Local, object Host, string LobbyId, string LobbyCode, bool IsHost);

	private sealed class FusionApi
	{
		private readonly Func<bool> hasServer;

		private readonly Func<bool> isHost;

		private readonly PropertyInfo lobby;

		private readonly PropertyInfo privacy;

		private readonly PropertyInfo lobbyId;

		private readonly PropertyInfo lobbyCode;

		private readonly PropertyInfo lobbyHostId;

		private readonly PropertyInfo local;

		private readonly PropertyInfo validId;

		private readonly PropertyInfo platformId;

		private readonly PropertyInfo smallId;

		private readonly PropertyInfo playerId;

		private readonly PropertyInfo hasRig;

		private readonly PropertyInfo entity;

		private readonly PropertyInfo registered;

		private readonly PropertyInfo queued;

		private readonly PropertyInfo destroyed;

		private readonly PropertyInfo localMetadata;

		private readonly PropertyInfo playerMetadata;

		private readonly PropertyInfo metadata;

		private readonly MethodInfo getHost;

		private readonly MethodInfo lookupPlayer;

		private readonly MethodInfo readMetadata;

		private readonly MethodInfo writeMetadata;

		private readonly MethodInfo removeLocalMetadata;

		private readonly object privateLobby;

		private readonly List<(EventInfo Event, Delegate Handler)> attached = new List<(EventInfo, Delegate)>();

		internal Assembly Assembly { get; }

		internal FusionApi(Assembly assembly)
		{
			Assembly assembly2 = assembly;
			base..ctor();
			Assembly = assembly2;
			Type type = Type("Network.NetworkInfo");
			hasServer = Property(type, "HasServer").GetMethod.CreateDelegate<Func<bool>>();
			isHost = Property(type, "IsHost").GetMethod.CreateDelegate<Func<bool>>();
			Type type2 = Type("Network.LobbyInfoManager");
			lobby = Property(type2, "LobbyInfo");
			privacy = Property(lobby.PropertyType, "Privacy");
			privateLobby = Enum.Parse(privacy.PropertyType, "PRIVATE");
			lobbyId = Property(lobby.PropertyType, "LobbyID");
			lobbyCode = Property(lobby.PropertyType, "LobbyCode");
			lobbyHostId = Property(lobby.PropertyType, "LobbyHostID");
			Type type3 = Type("Player.PlayerIDManager");
			local = Property(type3, "LocalID");
			getHost = Method(type3, "GetHostID", Array.Empty<Type>());
			validId = Property(local.PropertyType, "IsValid");
			platformId = Property(local.PropertyType, "PlatformID");
			smallId = Property(local.PropertyType, "SmallID");
			Type type4 = Type("Entities.NetworkPlayer");
			lookupPlayer = Method(Type("Entities.NetworkPlayerManager"), "TryGetPlayer", new Type[2]
			{
				typeof(byte),
				type4.MakeByRefType()
			});
			playerId = Property(type4, "PlayerID");
			hasRig = Property(type4, "HasRig");
			entity = Property(type4, "NetworkEntity");
			registered = Property(entity.PropertyType, "IsRegistered");
			queued = Property(entity.PropertyType, "IsQueued");
			destroyed = Property(entity.PropertyType, "IsDestroyed");
			Type type5 = Type("Player.LocalPlayer");
			localMetadata = Property(type5, "Metadata");
			playerMetadata = Property(local.PropertyType, "Metadata");
			metadata = Property(playerMetadata.PropertyType, "Metadata");
			readMetadata = Method(metadata.PropertyType, "GetMetadata", new Type[1] { typeof(string) });
			writeMetadata = Method(metadata.PropertyType, "TrySetMetadata", new Type[2]
			{
				typeof(string),
				typeof(string)
			});
			removeLocalMetadata = Method(metadata.PropertyType, "ForceRemoveLocalMetadata", new Type[1] { typeof(string) });
			try
			{
				Attach(Type("Utilities.MultiplayerHooking"), "OnDisconnected", ResetConnection);
				Attach(type5, "OnApplyInitialMetadata", ResetConnection);
				Attach(type2, "OnLobbyInfoChanged", LobbyChanged);
			}
			catch
			{
				Detach();
				throw;
			}
			Type Type(string name)
			{
				return assembly2.GetType("LabFusion." + name, throwOnError: true);
			}
		}

		internal Connection? ReadConnection()
		{
			if (hasServer())
			{
				object value = lobby.GetValue(null);
				if (value != null && object.Equals(privacy.GetValue(value), privateLobby) && lobbyId.GetValue(value) is string value2 && !string.IsNullOrWhiteSpace(value2) && lobbyCode.GetValue(value) is string value3 && !string.IsNullOrWhiteSpace(value3))
				{
					object value4 = local.GetValue(null);
					if (value4 != null)
					{
						object value5 = validId.GetValue(value4);
						if (value5 is bool && (bool)value5)
						{
							object obj = getHost.Invoke(null, null);
							if (obj != null)
							{
								value5 = validId.GetValue(obj);
								if (value5 is bool && (bool)value5 && lobbyHostId.GetValue(value) is string text && !string.IsNullOrWhiteSpace(text) && string.Equals(platformId.GetValue(obj) as string, text, StringComparison.Ordinal))
								{
									bool flag = isHost();
									if (flag != (value4 == obj))
									{
										return null;
									}
									return new Connection(value4, obj, value2, value3, flag);
								}
							}
						}
					}
				}
			}
			return null;
		}

		internal object? GetCurrentTargetId(object target)
		{
			if (!(target.GetType() != playerId.DeclaringType))
			{
				object value = hasRig.GetValue(target);
				if (value is bool && (bool)value)
				{
					object value2 = entity.GetValue(target);
					if (value2 != null)
					{
						value = registered.GetValue(value2);
						if (value is bool && (bool)value)
						{
							value = queued.GetValue(value2);
							if (value is bool && !(bool)value)
							{
								value = destroyed.GetValue(value2);
								if (value is bool && !(bool)value)
								{
									object value3 = playerId.GetValue(target);
									if (value3 != null)
									{
										value = validId.GetValue(value3);
										if (value is bool && (bool)value && smallId.GetValue(value3) is byte b)
										{
											object[] array = new object[2] { b, null };
											value = lookupPlayer.Invoke(null, array);
											if (!(value is bool) || !(bool)value || array[1] != target)
											{
												return null;
											}
											return value3;
										}
									}
								}
							}
						}
					}
				}
			}
			return null;
		}

		internal string? ReadPlayerMetadata(object id, string key)
		{
			object value = playerMetadata.GetValue(id);
			if (value != null)
			{
				object value2 = metadata.GetValue(value);
				if (value2 != null)
				{
					return readMetadata.Invoke(value2, new object[1] { key }) as string;
				}
			}
			return null;
		}

		internal bool WriteLocalMetadata(Connection owner, string key, string value)
		{
			if (hasServer() && local.GetValue(null) == owner.Local)
			{
				object value2 = localMetadata.GetValue(null);
				if (value2 != null)
				{
					object value3 = metadata.GetValue(value2);
					if (value3 != null)
					{
						try
						{
							object obj = writeMetadata.Invoke(value3, new object[2] { key, value });
							return obj is bool && (bool)obj;
						}
						finally
						{
							removeLocalMetadata.Invoke(value3, new object[1] { key });
						}
					}
				}
			}
			return false;
		}

		private void Attach(Type owner, string name, Action callback)
		{
			EventInfo eventInfo = owner.GetEvent(name, BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMemberException(owner.FullName, name);
			Delegate obj = callback.Method.CreateDelegate(eventInfo.EventHandlerType, callback.Target);
			eventInfo.AddEventHandler(null, obj);
			attached.Add((eventInfo, obj));
		}

		internal void Detach()
		{
			foreach (var (eventInfo, handler) in attached)
			{
				eventInfo.RemoveEventHandler(null, handler);
			}
			attached.Clear();
		}

		private static PropertyInfo Property(Type type, string name)
		{
			return type.GetProperty(name) ?? throw new MissingMemberException(type.FullName, name);
		}

		private static MethodInfo Method(Type type, string name, Type[] signature)
		{
			return type.GetMethod(name, signature) ?? throw new MissingMethodException(type.FullName, name);
		}
	}

	private const string SessionKey = "oc3anav3nue.kratos.pvp.session.v1";

	private const string ConsentKey = "oc3anav3nue.kratos.pvp.receive.v1";

	private const string Off = "off";

	private static readonly Version KnownVersion = new Version(1, 14, 2, 0);

	private static Action<string>? log;

	private static Page? menuRoot;

	private static Page? page;

	private static BoolElement? toggle;

	private static Assembly? attemptedAssembly;

	private static FusionApi? api;

	private static Connection? connection;

	private static string? hostNonce;

	private static string? optedNonce;

	private static float nextTick;

	private static bool warned;

	internal static void Install(Action<string> logger)
	{
		if (log == null)
		{
			log = logger;
			Tick();
		}
	}

	internal static void Uninstall()
	{
		ResetConnection();
		api?.Detach();
		api = null;
		attemptedAssembly = null;
		if (page != null)
		{
			Page? obj = menuRoot;
			if (obj != null)
			{
				obj.RemovePage(page);
			}
		}
		menuRoot = null;
		page = null;
		toggle = null;
		log = null;
		nextTick = 0f;
		warned = false;
	}

	internal static void Tick()
	{
		if (log == null || Time.realtimeSinceStartup < nextTick)
		{
			return;
		}
		nextTick = Time.realtimeSinceStartup + 0.5f;
		try
		{
			EnsureMenu();
			Assembly assembly = FindFusion();
			if (assembly != attemptedAssembly)
			{
				ResetConnection();
				api?.Detach();
				api = null;
				attemptedAssembly = assembly;
				if ((object)assembly != null)
				{
					api = new FusionApi(assembly);
				}
			}
			RefreshConnection();
		}
		catch (Exception)
		{
			Report();
		}
	}

	internal static bool TargetHasOptedIn(Assembly assembly, object networkPlayer)
	{
		try
		{
			FusionApi fusionApi = api;
			Connection connection = ((fusionApi?.Assembly == assembly) ? fusionApi.ReadConnection() : null);
			if (fusionApi != null && (object)connection != null && SameConnection(connection, KratosFusionPvpConsent.connection))
			{
				object currentTargetId = fusionApi.GetCurrentTargetId(networkPlayer);
				if (currentTargetId != null && currentTargetId != connection.Local)
				{
					string text = CurrentNonce(fusionApi, connection);
					if (text != null)
					{
						return string.Equals(fusionApi.ReadPlayerMetadata(currentTargetId, "oc3anav3nue.kratos.pvp.receive.v1"), text, StringComparison.Ordinal);
					}
				}
			}
			return false;
		}
		catch (Exception)
		{
			return false;
		}
	}

	internal static bool LocalHasOptedIn(Assembly assembly)
	{
		try
		{
			FusionApi fusionApi = api;
			Connection connection = ((fusionApi?.Assembly == assembly) ? fusionApi.ReadConnection() : null);
			int result;
			if (HasMortalHealth() && fusionApi != null && (object)connection != null && SameConnection(connection, KratosFusionPvpConsent.connection))
			{
				string text = optedNonce;
				if (text != null)
				{
					result = ((CurrentNonce(fusionApi, connection) == text) ? 1 : 0);
					goto IL_0057;
				}
			}
			result = 0;
			goto IL_0057;
			IL_0057:
			return (byte)result != 0;
		}
		catch (Exception)
		{
			return false;
		}
	}

	private static void EnsureMenu()
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		Page root = Page.Root;
		if (root == null || root == menuRoot)
		{
			return;
		}
		if (page != null)
		{
			Page? obj = menuRoot;
			if (obj != null)
			{
				obj.RemovePage(page);
			}
		}
		menuRoot = root;
		page = root.CreatePage("Kratos PvP Consent", Color.white, 0, true);
		toggle = page.CreateBool("Receive boosted PvP hits", Color.white, optedNonce != null, (Action<bool>)ToggleConsent);
		((Element)toggle).SetTooltip("Opt in for this private Fusion lobby. Leaving the lobby resets consent. The host needs this companion.");
	}

	private static void ToggleConsent(bool requested)
	{
		try
		{
			RefreshConnection();
			if (!requested)
			{
				RevokeConsent();
			}
			else
			{
				if (!HasMortalHealth())
				{
					return;
				}
				FusionApi fusionApi = api;
				if (fusionApi == null)
				{
					return;
				}
				Connection connection = KratosFusionPvpConsent.connection;
				if ((object)connection != null)
				{
					string text = CurrentNonce(fusionApi, connection);
					if (text != null && fusionApi.WriteLocalMetadata(connection, "oc3anav3nue.kratos.pvp.receive.v1", text))
					{
						optedNonce = text;
					}
				}
			}
		}
		catch (Exception)
		{
			Report();
		}
		finally
		{
			UpdateToggle();
		}
	}

	private static void RefreshConnection()
	{
		FusionApi fusionApi = api;
		if (fusionApi == null)
		{
			return;
		}
		Connection connection = fusionApi.ReadConnection();
		if (!SameConnection(connection, KratosFusionPvpConsent.connection))
		{
			ResetConnection();
			KratosFusionPvpConsent.connection = connection;
		}
		if ((object)connection == null)
		{
			return;
		}
		if (connection.IsHost && hostNonce == null)
		{
			string value = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
			if (fusionApi.WriteLocalMetadata(connection, "oc3anav3nue.kratos.pvp.session.v1", value))
			{
				hostNonce = value;
			}
		}
		string text = optedNonce;
		if (text != null && (!HasMortalHealth() || text != CurrentNonce(fusionApi, connection)))
		{
			RevokeConsent();
		}
	}

	private static string? CurrentNonce(FusionApi currentApi, Connection current)
	{
		string text = currentApi.ReadPlayerMetadata(current.Host, "oc3anav3nue.kratos.pvp.session.v1");
		if (text == null || text.Length != 32 || !text.All(char.IsAsciiHexDigitUpper))
		{
			return null;
		}
		if (!current.IsHost || !(text != hostNonce))
		{
			return text;
		}
		return null;
	}

	private static bool SameConnection(Connection? a, Connection? b)
	{
		if ((object)a != null)
		{
			if ((object)b != null && a.Local == b.Local && a.Host == b.Host && a.IsHost == b.IsHost && a.LobbyId == b.LobbyId)
			{
				return a.LobbyCode == b.LobbyCode;
			}
			return false;
		}
		return (object)b == null;
	}

	private static bool HasMortalHealth()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Invalid comparison between Unknown and I4
		RigManager rigManager = Player.RigManager;
		Health val = (Object.op_Implicit((Object)(object)rigManager) ? rigManager.health : null);
		if (val != null && Object.op_Implicit((Object)(object)val))
		{
			return (int)val.healthMode == 1;
		}
		return false;
	}

	private static void RevokeConsent()
	{
		bool flag = optedNonce != null;
		optedNonce = null;
		try
		{
			if (!flag)
			{
				return;
			}
			FusionApi fusionApi = api;
			if (fusionApi != null)
			{
				Connection connection = KratosFusionPvpConsent.connection;
				if ((object)connection != null)
				{
					fusionApi.WriteLocalMetadata(connection, "oc3anav3nue.kratos.pvp.receive.v1", "off");
				}
			}
		}
		finally
		{
			UpdateToggle();
		}
	}

	private static void ResetConnection()
	{
		try
		{
			RevokeConsent();
			if (hostNonce == null)
			{
				return;
			}
			FusionApi fusionApi = api;
			if (fusionApi != null)
			{
				Connection connection = KratosFusionPvpConsent.connection;
				if ((object)connection != null)
				{
					fusionApi.WriteLocalMetadata(connection, "oc3anav3nue.kratos.pvp.session.v1", "off");
				}
			}
		}
		catch (Exception)
		{
			Report();
		}
		finally
		{
			KratosFusionPvpConsent.connection = null;
			hostNonce = null;
		}
	}

	private static void LobbyChanged()
	{
		try
		{
			RefreshConnection();
		}
		catch (Exception)
		{
			ResetConnection();
			Report();
		}
	}

	private static void UpdateToggle()
	{
		BoolElement val = toggle;
		if (val != null && val.Value != (optedNonce != null))
		{
			val.Value = optedNonce != null;
		}
	}

	private static void Report()
	{
		if (!warned)
		{
			warned = true;
			log?.Invoke("Kratos private-lobby PvP consent could not be verified.");
		}
	}

	private static Assembly? FindFusion()
	{
		Assembly assembly = null;
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly2 in assemblies)
		{
			string? fullName = assembly2.FullName;
			if (fullName != null && fullName.StartsWith("LabFusion,", StringComparison.Ordinal))
			{
				if ((object)assembly != null || assembly2.GetName().Version != KnownVersion)
				{
					return null;
				}
				assembly = assembly2;
			}
		}
		return assembly;
	}
}
internal static class KratosGrabGuard
{
	private sealed class PointerBinding(UltEvent press, GameObject unconsumed, GameObject validHit, Transform point)
	{
		public readonly UltEvent Press = press;

		public readonly GameObject Unconsumed = unconsumed;

		public readonly GameObject ValidHit = validHit;

		public readonly Transform Point = point;

		public Action? Callback;
	}

	private sealed class MenuBinding(RigManager rig, Avatar avatar, PhysicsRig physics, Transform menu, Transform panel, RectTransform button, Text label, PointerBinding left, PointerBinding right)
	{
		public readonly RigManager Rig = rig;

		public readonly Avatar Avatar = avatar;

		public readonly PhysicsRig Physics = physics;

		public readonly Transform Menu = menu;

		public readonly Transform Panel = panel;

		public readonly RectTransform Button = button;

		public readonly Text Label = label;

		public readonly PointerBinding Left = left;

		public readonly PointerBinding Right = right;

		public bool On;

		public bool Solo;

		public int LastPressFrame = -1;
	}

	private const string MenuPath = "KratosNativeMenuIntegration_DRAFT";

	private const string PanelPath = "KratosPowerMenu";

	private const string ButtonPath = "KnockbackPlaceholder/KnockbackButton";

	private const string OriginalLabel = "KNOCKBACK\nLATER";

	private const string OffLabel = "KNOCKBACK\n(NPC) OFF";

	private const string OnLabel = "KNOCKBACK\n(NPC) ON";

	private const string SoloLabel = "KNOCKBACK\n(NPC) SOLO";

	private static Harmony? hooks;

	private static Action<string>? log;

	private static MenuBinding? binding;

	private static Avatar? observedAvatar;

	private static long nextCheck;

	private static int bindAttempts;

	internal static bool IsLocalGuardOn
	{
		get
		{
			MenuBinding menuBinding = binding;
			try
			{
				return hooks != null && menuBinding != null && menuBinding.On && menuBinding.Solo && OwnsCurrentSession(menuBinding) && KratosPunchMod.NoFusionSession();
			}
			catch
			{
				return false;
			}
		}
	}

	internal static void Install(Action<string> logger)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Expected O, but got Unknown
		if (hooks != null || (int)Application.platform != 11)
		{
			return;
		}
		Harmony val = new Harmony("oc3anav3nue.kratos.grabguard");
		try
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(BehaviourCrablet), "AttachToFace", new Type[4]
			{
				typeof(Rigidbody),
				typeof(TriggerRefProxy),
				typeof(bool),
				typeof(bool)
			}, (Type[])null);
			if (methodInfo?.ReturnType != typeof(bool))
			{
				throw new MissingMethodException("Expected the stock Crablet face attachment method.");
			}
			val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(KratosGrabGuard), "BeforeFaceAttach", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log = logger;
			hooks = val;
			nextCheck = 0L;
			logger("Kratos grab guard ready for the local avatar.");
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			hooks = null;
			log = null;
			logger("Kratos grab guard unavailable: " + ex.GetBaseException().Message);
		}
	}

	internal static void Uninstall()
	{
		ClearBinding();
		Harmony? obj = hooks;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		hooks = null;
		log = null;
		observedAvatar = null;
		bindAttempts = 0;
	}

	internal static void Update()
	{
		if (hooks == null)
		{
			return;
		}
		long timestamp = Stopwatch.GetTimestamp();
		if (timestamp < nextCheck)
		{
			return;
		}
		nextCheck = timestamp + Stopwatch.Frequency / 4;
		try
		{
			RigManager rigManager = Player.RigManager;
			Avatar val = (Object.op_Implicit((Object)(object)rigManager) ? rigManager.avatar : null);
			if ((Object)(object)val != (Object)(object)observedAvatar)
			{
				ClearBinding();
				observedAvatar = val;
				bindAttempts = 24;
			}
			MenuBinding menuBinding = binding;
			if (menuBinding != null)
			{
				if (!((Object)(object)rigManager != (Object)(object)menuBinding.rig) && Object.op_Implicit((Object)(object)val) && !((Object)(object)rigManager.physicsRig != (Object)(object)menuBinding.physics) && Object.op_Implicit((Object)(object)menuBinding.label) && Object.op_Implicit((Object)(object)menuBinding.button))
				{
					if (menuBinding.On || !menuBinding.Solo || ((Component)menuBinding.panel).gameObject.activeInHierarchy)
					{
						bool flag = KratosPunchMod.NoFusionSession();
						Health health = rigManager.health;
						bool flag2 = menuBinding.On && flag && Object.op_Implicit((Object)(object)health) && health.alive && !health.deathIsImminent;
						SetMode(menuBinding, flag2, flag);
					}
					return;
				}
				ClearBinding();
				bindAttempts = 24;
			}
			if (bindAttempts <= 0 || !Object.op_Implicit((Object)(object)rigManager) || !Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			bindAttempts--;
			if (!rigManager._avatarDirty)
			{
				AvatarCrateReference avatarCrate = rigManager.AvatarCrate;
				object barcode;
				if (avatarCrate == null)
				{
					barcode = null;
				}
				else
				{
					Barcode barcode2 = ((ScannableReference)avatarCrate).Barcode;
					barcode = ((barcode2 != null) ? barcode2.ID : null);
				}
				if (KratosPunchMod.IsSupportedAvatar((string?)barcode))
				{
					TryBind(rigManager, val);
				}
			}
		}
		catch (Exception ex)
		{
			ClearBinding();
			bindAttempts = 0;
			log?.Invoke("Kratos grab guard menu unavailable: " + ex.GetBaseException().Message);
		}
	}

	private static void TryBind(RigManager rig, Avatar avatar)
	{
		PhysicsRig physicsRig = rig.physicsRig;
		Transform val = ((Component)avatar).transform.Find("KratosNativeMenuIntegration_DRAFT");
		Transform val2 = (Object.op_Implicit((Object)(object)val) ? val.Find("KratosPowerMenu") : null);
		Transform val3 = (Object.op_Implicit((Object)(object)val2) ? val2.Find("KnockbackPlaceholder/KnockbackButton") : null);
		RectTransform val4 = (Object.op_Implicit((Object)(object)val3) ? ((Il2CppObjectBase)val3).TryCast<RectTransform>() : null);
		Button val5 = (Object.op_Implicit((Object)(object)val3) ? ((Component)val3).GetComponent<Button>() : null);
		object obj;
		if (!Object.op_Implicit((Object)(object)val3))
		{
			obj = null;
		}
		else
		{
			Transform obj2 = val3.Find("KnockbackLabel");
			obj = ((obj2 != null) ? ((Component)obj2).GetComponent<Text>() : null);
		}
		Text val6 = (Text)obj;
		if (Object.op_Implicit((Object)(object)physicsRig) && Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val4) && Object.op_Implicit((Object)(object)val5) && !((Selectable)val5).interactable && Object.op_Implicit((Object)(object)val6) && !(val6.text != "KNOCKBACK\nLATER") && KratosPunchMod.FindOwnedCleanupIsland(rig, avatar, physicsRig) != null)
		{
			PointerBinding pointerBinding = FindPointer(val, "Left");
			PointerBinding pointerBinding2 = FindPointer(val, "Right");
			if (pointerBinding != null && pointerBinding2 != null && ((Il2CppObjectBase)pointerBinding.press).Pointer != ((Il2CppObjectBase)pointerBinding2.press).Pointer)
			{
				MenuBinding menuBinding = (binding = new MenuBinding(rig, avatar, physicsRig, val, val2, val4, val6, pointerBinding, pointerBinding2)
				{
					Solo = KratosPunchMod.NoFusionSession()
				});
				Subscribe(menuBinding, pointerBinding);
				Subscribe(menuBinding, pointerBinding2);
				val6.text = (menuBinding.Solo ? "KNOCKBACK\n(NPC) OFF" : "KNOCKBACK\n(NPC) SOLO");
			}
		}
	}

	private static PointerBinding? FindPointer(Transform menu, string side)
	{
		Transform val = menu.Find("NativeOwnMathPointer_" + side + "NativePointer");
		if (!Object.op_Implicit((Object)(object)val))
		{
			return null;
		}
		Transform val2 = val.Find("UnconsumedPress");
		Transform val3 = val.Find("FiniteForwardPlaneHit");
		Transform val4 = val.Find("PlanePoint");
		Transform obj = val.Find("HitCandidatesOnPressOnly");
		UltEventHolder val5 = ((obj != null) ? ((Component)obj).GetComponent<UltEventHolder>() : null);
		UltEvent val6 = (Object.op_Implicit((Object)(object)val5) ? val5.Event : null);
		List<PersistentCall> val7 = ((val6 != null) ? ((UltEventBase)val6)._PersistentCalls : null);
		if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val3) || !Object.op_Implicit((Object)(object)val4) || val6 == null || val7 == null || val7.Count < 2 || val7[0].Target != (Object)(object)((Component)val2).gameObject || val7[0].MethodName != "SetActive" || ((Il2CppArrayBase<PersistentArgument>)(object)val7[0].PersistentArguments).Length != 1 || !((Il2CppArrayBase<PersistentArgument>)(object)val7[0].PersistentArguments)[0].Bool)
		{
			return null;
		}
		return new PointerBinding(val6, ((Component)val2).gameObject, ((Component)val3).gameObject, val4);
	}

	private static void Subscribe(MenuBinding current, PointerBinding pointer)
	{
		Action val = Action.op_Implicit((Action)delegate
		{
			AfterNativePress(current, pointer);
		});
		pointer.Callback = val;
		pointer.press.DynamicCalls += val;
	}

	private static void AfterNativePress(MenuBinding current, PointerBinding pointer)
	{
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (binding != current || !Object.op_Implicit((Object)(object)pointer.unconsumed) || !pointer.unconsumed.activeSelf || !Object.op_Implicit((Object)(object)pointer.validHit) || !pointer.validHit.activeSelf || !Object.op_Implicit((Object)(object)pointer.point) || !Object.op_Implicit((Object)(object)current.button) || !Object.op_Implicit((Object)(object)current.label) || !Object.op_Implicit((Object)(object)current.panel) || !((Component)current.panel).gameObject.activeInHierarchy || !Active(current.menu, "MenuOpenState") || !Active(current.menu, "LocalOwnerAndControllerReady") || !Active(current.menu, "UNVERIFIED_SelectionPermissionForControlledGameTest") || !Active(current.menu, "NativeOwnerMenuTranslationFollow/CanonicalCurrentAvatarValidation/ExactCurrentAvatarPermitted"))
			{
				return;
			}
			Vector3 val = ((Transform)current.button).InverseTransformPoint(pointer.point.position);
			Rect rect = current.button.rect;
			if (float.IsFinite(val.x) && float.IsFinite(val.y) && !(val.x < ((Rect)(ref rect)).xMin) && !(val.x > ((Rect)(ref rect)).xMax) && !(val.y < ((Rect)(ref rect)).yMin) && !(val.y > ((Rect)(ref rect)).yMax) && OwnsCurrentSession(current))
			{
				pointer.unconsumed.SetActive(false);
				int frameCount = Time.frameCount;
				if (current.LastPressFrame != frameCount)
				{
					current.LastPressFrame = frameCount;
					bool flag = KratosPunchMod.NoFusionSession();
					SetMode(current, flag && !current.On, flag);
				}
			}
		}
		catch (Exception ex)
		{
			ClearBinding();
			bindAttempts = 0;
			log?.Invoke("Kratos grab guard menu released after a failed press: " + ex.GetBaseException().Message);
		}
	}

	private static string LabelFor(bool on, bool solo)
	{
		if (!solo)
		{
			return "KNOCKBACK\n(NPC) SOLO";
		}
		if (!on)
		{
			return "KNOCKBACK\n(NPC) OFF";
		}
		return "KNOCKBACK\n(NPC) ON";
	}

	private static void SetMode(MenuBinding current, bool on, bool solo)
	{
		if (current.On != on || current.Solo != solo)
		{
			if (!Object.op_Implicit((Object)(object)current.label) || current.label.text != LabelFor(current.On, current.Solo))
			{
				current.On = false;
				return;
			}
			current.label.text = LabelFor(on, solo);
			current.On = on;
			current.Solo = solo;
		}
	}

	private static bool OwnsCurrentSession(MenuBinding current)
	{
		RigManager rigManager = Player.RigManager;
		if (Object.op_Implicit((Object)(object)rigManager) && !((Object)(object)rigManager != (Object)(object)current.rig) && !((Object)(object)rigManager.avatar != (Object)(object)current.avatar) && !((Object)(object)rigManager.physicsRig != (Object)(object)current.physics) && !rigManager._avatarDirty && Object.op_Implicit((Object)(object)current.avatar) && ((Component)current.avatar).gameObject.activeInHierarchy)
		{
			AvatarCrateReference avatarCrate = rigManager.AvatarCrate;
			object barcode;
			if (avatarCrate == null)
			{
				barcode = null;
			}
			else
			{
				Barcode barcode2 = ((ScannableReference)avatarCrate).Barcode;
				barcode = ((barcode2 != null) ? barcode2.ID : null);
			}
			if (KratosPunchMod.IsSupportedAvatar((string?)barcode))
			{
				Health health = rigManager.health;
				if (!Object.op_Implicit((Object)(object)health) || !health.alive || health.deathIsImminent)
				{
					return false;
				}
				Transform val = KratosPunchMod.FindOwnedCleanupIsland(rigManager, current.avatar, current.physics);
				if (Object.op_Implicit((Object)(object)val) && Active(val, "State/OwnerValid") && Active(val, "State/Ready") && Active(val, "State/SessionActive") && Active(val, "State/SessionValid") && Inactive(val, "State/Busy") && Inactive(val, "State/DeathPending"))
				{
					return Inactive(val, "State/InternalHeightTransition");
				}
				return false;
			}
		}
		return false;
	}

	private static bool Active(Transform root, string path)
	{
		Transform val = (Object.op_Implicit((Object)(object)root) ? root.Find(path) : null);
		if (Object.op_Implicit((Object)(object)val))
		{
			return ((Component)val).gameObject.activeSelf;
		}
		return false;
	}

	private static bool Inactive(Transform root, string path)
	{
		Transform val = (Object.op_Implicit((Object)(object)root) ? root.Find(path) : null);
		if (Object.op_Implicit((Object)(object)val))
		{
			return !((Component)val).gameObject.activeSelf;
		}
		return false;
	}

	private static bool BeforeFaceAttach(BehaviourCrablet __instance, Rigidbody __0, TriggerRefProxy __1, bool __3, ref bool __result)
	{
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		MenuBinding menuBinding = binding;
		if (menuBinding == null || !menuBinding.On || !menuBinding.Solo || !__3 || !Object.op_Implicit((Object)(object)__instance) || !Object.op_Implicit((Object)(object)__0) || !Object.op_Implicit((Object)(object)__1))
		{
			return true;
		}
		try
		{
			PhysTorso val = (Object.op_Implicit((Object)(object)menuBinding.physics) ? menuBinding.physics.torso : null);
			if (!Object.op_Implicit((Object)(object)val) || (Object)(object)val.rbHead != (Object)(object)__0 || (Object)(object)__1.targetHead != (Object)(object)__0 || (int)__1.triggerType != 0 || !OwnsCurrentSession(menuBinding) || !KratosPunchMod.NoFusionSession())
			{
				return true;
			}
			__result = false;
			return false;
		}
		catch
		{
			return true;
		}
	}

	private static void ClearBinding()
	{
		MenuBinding menuBinding = binding;
		binding = null;
		if (menuBinding == null)
		{
			return;
		}
		Unsubscribe(menuBinding.left);
		Unsubscribe(menuBinding.right);
		try
		{
			bool flag = Object.op_Implicit((Object)(object)menuBinding.label);
			if (flag)
			{
				bool flag2;
				switch (menuBinding.label.text)
				{
				case "KNOCKBACK\n(NPC) OFF":
				case "KNOCKBACK\n(NPC) ON":
				case "KNOCKBACK\n(NPC) SOLO":
					flag2 = true;
					break;
				default:
					flag2 = false;
					break;
				}
				flag = flag2;
			}
			if (flag)
			{
				menuBinding.label.text = "KNOCKBACK\nLATER";
			}
		}
		catch (Exception ex)
		{
			log?.Invoke("Kratos grab guard label restore skipped: " + ex.GetBaseException().Message);
		}
	}

	private static void Unsubscribe(PointerBinding pointer)
	{
		Action callback = pointer.Callback;
		if (callback == null)
		{
			return;
		}
		pointer.Callback = null;
		try
		{
			pointer.press.DynamicCalls -= callback;
		}
		catch (Exception ex)
		{
			log?.Invoke("Kratos grab guard press listener restore skipped: " + ex.GetBaseException().Message);
		}
	}
}
internal static class KratosHeightMenuHandoff
{
	private sealed record Handoff(RigManager Rig, PhysicsRig Physics, Avatar Source, Avatar Destination, Transform Island, GameObject SourceOpen, GameObject SourcePanel, string Level, float Height, float Expires);

	private const string MenuPath = "KratosNativeMenuIntegration_DRAFT";

	private const string PanelName = "KratosPowerMenu";

	private const string Waiting = "waiting-for-native-avatar-and-profile";

	private const float HeightTolerance = 0.005f;

	private const float Timeout = 5f;

	private static Harmony? hooks;

	private static Action<string>? log;

	private static Handoff? pending;

	internal static void Install(Action<string> logger)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Expected O, but got Unknown
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Expected O, but got Unknown
		if (hooks != null)
		{
			return;
		}
		Harmony val = new Harmony("oc3anav3nue.kratos.heightmenu");
		try
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(RigManager), "SwapAvatar", new Type[1] { typeof(Avatar) }, (Type[])null);
			if (methodInfo?.ReturnType != typeof(void))
			{
				throw new MissingMethodException("Expected the stock Avatar overload of RigManager.SwapAvatar.");
			}
			val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(KratosHeightMenuHandoff), "BeforeSwap", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log = logger;
			hooks = val;
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			logger("Kratos height menu handoff unavailable: " + ex.GetBaseException().Message);
		}
	}

	internal static void Uninstall()
	{
		pending = null;
		Harmony? obj = hooks;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		hooks = null;
		log = null;
	}

	internal static bool IsTracking(Transform island)
	{
		return (Object)(object)pending?.Island == (Object)(object)island;
	}

	private static void BeforeSwap(RigManager __instance, Avatar __0)
	{
		try
		{
			if (hooks == null || !Object.op_Implicit((Object)(object)__instance) || (Object)(object)Player.RigManager != (Object)(object)__instance)
			{
				return;
			}
			pending = null;
			Avatar avatar = __instance.avatar;
			PhysicsRig physicsRig = __instance.physicsRig;
			if (!Object.op_Implicit((Object)(object)avatar) || !Object.op_Implicit((Object)(object)__0) || (Object)(object)avatar == (Object)(object)__0 || !Object.op_Implicit((Object)(object)physicsRig) || __instance._avatarDirty || !LivingKratos(__instance) || ((Component)__0).gameObject.activeSelf || (Object)(object)((Component)__0).transform.parent != (Object)(object)((Component)__instance).transform)
			{
				return;
			}
			Transform val = ((Component)avatar).transform.Find("KratosNativeMenuIntegration_DRAFT");
			Transform val2 = (Object.op_Implicit((Object)(object)val) ? val.Find("MenuOpenState") : null);
			if (!Object.op_Implicit((Object)(object)val2) || !((Component)val2).gameObject.activeInHierarchy || !TryFindMenuCommand(val, out UltEventHolder _, out GameObject panel) || !panel.activeInHierarchy)
			{
				return;
			}
			Transform val3 = KratosPunchMod.FindOwnedCleanupIsland(__instance, avatar, physicsRig);
			string text = (Object.op_Implicit((Object)(object)val3) ? KratosPunchMod.Record(val3, "SelectedLevel") : null);
			bool flag = !Object.op_Implicit((Object)(object)val3) || !KratosPunchMod.Flag(val3, "InternalHeightTransition", expected: true) || !KratosPunchMod.Flag(val3, "SessionActive", expected: true);
			if (!flag)
			{
				bool flag2;
				switch (text)
				{
				case "1":
				case "2":
				case "3":
				case "4":
				case "5":
					flag2 = true;
					break;
				default:
					flag2 = false;
					break;
				}
				flag = !flag2;
			}
			if (flag)
			{
				return;
			}
			Transform val4 = FindHeightTransaction(__instance, avatar, __0);
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (Object.op_Implicit((Object)(object)val4) && TryGetHeightRequest(val4, realtimeSinceStartup, out var height, out var expires))
			{
				Transform val5 = ((Component)__0).transform.Find("NativePowerProfiles/CleanupIsland");
				if (Object.op_Implicit((Object)(object)val5) && KratosPunchMod.Flag(val5, "TransferAuthorized", expected: true) && MatchesReference(val5, "TransferSelfRef", (Object)(object)__0) && !(KratosPunchMod.Record(val5, "TransferLevel") != text) && !(KratosPunchMod.Record(val5, "TransferExpires") != KratosPunchMod.Record(val4, "Expiry")))
				{
					pending = new Handoff(__instance, physicsRig, avatar, __0, val4, ((Component)val2).gameObject, panel, text, height, expires);
				}
			}
		}
		catch (Exception ex)
		{
			pending = null;
			log?.Invoke("Kratos height menu handoff skipped: " + ex.GetBaseException().Message);
		}
	}

	internal static void Update()
	{
		Handoff handoff = pending;
		if ((object)handoff == null)
		{
			return;
		}
		try
		{
			RigManager rigManager = Player.RigManager;
			if (!Object.op_Implicit((Object)(object)rigManager) || (Object)(object)rigManager != (Object)(object)handoff.Rig || !LivingKratos(rigManager) || (Object)(object)rigManager.physicsRig != (Object)(object)handoff.Physics || !Object.op_Implicit((Object)(object)handoff.Island) || !Object.op_Implicit((Object)(object)handoff.Destination) || Time.realtimeSinceStartup >= handoff.Expires)
			{
				pending = null;
				return;
			}
			string text = KratosPunchMod.Record(handoff.Island, "Status");
			Avatar avatar = rigManager.avatar;
			if ((Object)(object)avatar == (Object)(object)handoff.Source)
			{
				if (text != "waiting-for-native-avatar-and-profile" || !Object.op_Implicit((Object)(object)handoff.SourceOpen) || !handoff.SourceOpen.activeInHierarchy || !Object.op_Implicit((Object)(object)handoff.SourcePanel) || !handoff.SourcePanel.activeInHierarchy)
				{
					pending = null;
				}
				return;
			}
			bool flag = (Object)(object)avatar != (Object)(object)handoff.Destination;
			if (!flag)
			{
				bool flag2 = ((text == "waiting-for-native-avatar-and-profile" || text == "committed") ? true : false);
				flag = !flag2;
			}
			if (flag)
			{
				pending = null;
			}
			else
			{
				if (rigManager._avatarDirty || text != "committed")
				{
					return;
				}
				float height = avatar.height;
				if (!float.IsFinite(height) || MathF.Abs(height - handoff.Height) > 0.005f)
				{
					pending = null;
					return;
				}
				Transform val = KratosPunchMod.FindOwnedCleanupIsland(rigManager, avatar, handoff.Physics);
				Transform val2 = ((Component)avatar).transform.Find("KratosNativeMenuIntegration_DRAFT");
				if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val2) && ((Component)val2).gameObject.activeInHierarchy && KratosPunchMod.Flag(val, "OwnerValid", expected: true) && KratosPunchMod.Flag(val, "Ready", expected: true) && KratosPunchMod.Flag(val, "SessionActive", expected: true) && KratosPunchMod.Flag(val, "SessionValid", expected: true) && !(KratosPunchMod.Record(val, "SelectedLevel") != handoff.Level) && Active(val2, "LocalOwnerAndControllerReady"))
				{
					pending = null;
					if (!Active(val2, "MenuOpenState") && TryFindMenuCommand(val2, out UltEventHolder open, out GameObject _))
					{
						open.Invoke();
					}
				}
			}
		}
		catch (Exception ex)
		{
			pending = null;
			log?.Invoke("Kratos height menu handoff stopped: " + ex.GetBaseException().Message);
		}
	}

	private static bool LivingKratos(RigManager rig)
	{
		Health health = rig.health;
		if (Object.op_Implicit((Object)(object)health) && health.alive && !health.deathIsImminent)
		{
			AvatarCrateReference avatarCrate = rig.AvatarCrate;
			object barcode;
			if (avatarCrate == null)
			{
				barcode = null;
			}
			else
			{
				Barcode barcode2 = ((ScannableReference)avatarCrate).Barcode;
				barcode = ((barcode2 != null) ? barcode2.ID : null);
			}
			return KratosPunchMod.IsSupportedAvatar((string?)barcode);
		}
		return false;
	}

	private static Transform? FindHeightTransaction(RigManager rig, Avatar source, Avatar destination)
	{
		Transform transform = ((Component)rig).transform;
		Transform val = null;
		for (int i = 0; i < transform.childCount; i++)
		{
			Transform child = transform.GetChild(i);
			if (Object.op_Implicit((Object)(object)child) && !(((Object)child).name != "HeightIsland") && Active(child, "Pending") && !(KratosPunchMod.Record(child, "Status") != "waiting-for-native-avatar-and-profile") && MatchesReference(child, "SourceAvatarRef", (Object)(object)source) && MatchesReference(child, "IncomingAvatarRef", (Object)(object)destination) && MatchesReference(child, "IncomingRootRef", (Object)(object)((Component)destination).gameObject) && MatchesReference(child, "RigReference", (Object)(object)rig))
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					return null;
				}
				val = child;
			}
		}
		return val;
	}

	private static bool TryGetHeightRequest(Transform island, float now, out float height, out float expires)
	{
		height = (expires = 0f);
		if (!int.TryParse(KratosPunchMod.Record(island, "RequestedIndex"), NumberStyles.None, CultureInfo.InvariantCulture, out var result) || result < 0 || result > 44 || !float.TryParse(KratosPunchMod.Record(island, "RequestedMeters"), NumberStyles.Float, CultureInfo.InvariantCulture, out height) || !float.IsFinite(height) || MathF.Abs(height - (float)(76 + result) * 0.0254f) > 0.005f || !float.TryParse(KratosPunchMod.Record(island, "Expiry"), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) || !float.IsFinite(result2) || !float.IsFinite(now) || result2 <= now)
		{
			return false;
		}
		expires = MathF.Min(result2, now + 5f);
		return true;
	}

	private static bool MatchesReference(Transform island, string record, Object value)
	{
		string text = KratosPunchMod.Record(island, record);
		if (text != null && text.Length <= 128)
		{
			return KratosPunchMod.ParseReference(text, value.GetInstanceID());
		}
		return false;
	}

	private static bool Active(Transform parent, string path)
	{
		Transform val = parent.Find(path);
		if (Object.op_Implicit((Object)(object)val))
		{
			return ((Component)val).gameObject.activeInHierarchy;
		}
		return false;
	}

	internal static bool TryFindMenuCommand(Transform menu, out UltEventHolder open, out GameObject panel)
	{
		Transform obj = menu.Find("OpenMenu");
		open = ((obj != null) ? ((Component)obj).GetComponent<UltEventHolder>() : null);
		panel = null;
		object obj2;
		if (!Object.op_Implicit((Object)(object)open))
		{
			obj2 = null;
		}
		else
		{
			UltEvent obj3 = open.Event;
			obj2 = ((obj3 != null) ? ((UltEventBase)obj3)._PersistentCalls : null);
		}
		List<PersistentCall> val = (List<PersistentCall>)obj2;
		if (val == null || val.Count == 0 || val.Count > 32)
		{
			return false;
		}
		for (int i = 0; i < val.Count; i++)
		{
			PersistentCall val2 = val[i];
			Il2CppReferenceArray<PersistentArgument> persistentArguments = val2.PersistentArguments;
			if (val2.MethodName != "SetActive" || persistentArguments == null || ((Il2CppArrayBase<PersistentArgument>)(object)persistentArguments).Length != 1 || !((Il2CppArrayBase<PersistentArgument>)(object)persistentArguments)[0].Bool)
			{
				continue;
			}
			Object target = val2.Target;
			GameObject val3 = ((target != null) ? ((Il2CppObjectBase)target).TryCast<GameObject>() : null);
			if (val3 != null && Object.op_Implicit((Object)(object)val3) && !(((Object)val3).name != "KratosPowerMenu"))
			{
				if (Object.op_Implicit((Object)(object)panel))
				{
					return false;
				}
				panel = val3;
			}
		}
		return Object.op_Implicit((Object)(object)panel);
	}
}
internal static class KratosHeightMenuPreview
{
	private sealed record EventEdit(UltEvent Event, List<PersistentCall> Before, List<PersistentCall> After, Action Callback);

	private sealed record Pointer(UltEvent Event, GameObject Available, GameObject Hit, Transform Point)
	{
		internal Action? Callback;

		[CompilerGenerated]
		private bool PrintMembers(StringBuilder builder)
		{
			RuntimeHelpers.EnsureSufficientExecutionStack();
			builder.Append("Event = ");
			builder.Append(Event);
			builder.Append(", Available = ");
			builder.Append(Available);
			builder.Append(", Hit = ");
			builder.Append(Hit);
			builder.Append(", Point = ");
			builder.Append(Point);
			return true;
		}
	}

	private sealed class Binding
	{
		internal required RigManager Rig;

		internal required Avatar Avatar;

		internal required GameObject Panel;

		internal required GameObject Open;

		internal required GameObject Owner;

		internal required GameObject Ready;

		internal required GameObject SliderLease;

		internal required Slider Slider;

		internal required Text Heading;

		internal required Text Value;

		internal required Text MinimumText;

		internal required Text MaximumText;

		internal required Pointer[] Pointers;

		internal readonly List<GameObject> Created = new List<GameObject>(3);

		internal readonly List<EventEdit> Edits = new List<EventEdit>(3);

		internal readonly List<(RectTransform Rect, Vector2 Position)> Positions = new List<(RectTransform, Vector2)>(7);

		internal RectTransform? Apply;

		internal UnityAction<float>? SliderChanged;

		internal float OriginalSlider;

		internal bool OriginalWholeNumbers;

		internal string OriginalHeading = "";

		internal string OriginalValue = "";

		internal string OriginalMinimum = "";

		internal string OriginalMaximum = "";

		internal int OriginalFontSize;

		internal int Applied;

		internal int Preview;

		internal int LastPress = -1;

		internal bool WasOpen;
	}

	private const string MenuPath = "KratosNativeMenuIntegration_DRAFT";

	private const string HeightPath = "NativeHeightCoordinator/";

	private const string InterfacePath = "IntegrationInterfaces_UNCONNECTED/";

	private const int Minimum = 76;

	private const int Normal = 92;

	private const int Maximum = 120;

	private const float SliderMidpoint = 8f;

	private const float SliderMaximum = 16f;

	private static Action<string>? log;

	private static RigManager? observedRig;

	private static Avatar? observedAvatar;

	private static Binding? binding;

	private static long nextCheck;

	private static int attempts;

	internal static void Install(Action<string> logger)
	{
		log = logger;
	}

	internal static void Uninstall()
	{
		Release();
		observedRig = null;
		observedAvatar = null;
		attempts = 0;
		nextCheck = 0L;
		log = null;
	}

	internal static void Update()
	{
		long timestamp = Stopwatch.GetTimestamp();
		if (log == null || timestamp < nextCheck)
		{
			return;
		}
		nextCheck = timestamp + Stopwatch.Frequency / 10;
		try
		{
			RigManager rigManager = Player.RigManager;
			Avatar val = (Object.op_Implicit((Object)(object)rigManager) ? rigManager.avatar : null);
			if ((Object)(object)rigManager != (Object)(object)observedRig || (Object)(object)val != (Object)(object)observedAvatar)
			{
				Release();
				observedRig = rigManager;
				observedAvatar = val;
				attempts = 40;
			}
			Binding binding = KratosHeightMenuPreview.binding;
			if (binding != null)
			{
				bool flag = binding.Open.activeSelf && binding.Panel.activeInHierarchy;
				if (TryMeasuredInches(binding.Avatar, out var inches) && inches != binding.Applied)
				{
					binding.Applied = inches;
					Preview(binding, inches, snap: true);
				}
				else if (binding.WasOpen && !flag)
				{
					Preview(binding, binding.Applied, snap: true);
				}
				else if (flag && !binding.SliderLease.activeSelf && binding.Slider.value != SliderValue(binding.Preview))
				{
					binding.Slider.SetValueWithoutNotify(SliderValue(binding.Preview));
				}
				binding.WasOpen = flag;
			}
			else if (attempts > 0 && Object.op_Implicit((Object)(object)rigManager) && Object.op_Implicit((Object)(object)val) && !rigManager._avatarDirty)
			{
				AvatarCrateReference avatarCrate = rigManager.AvatarCrate;
				object barcode;
				if (avatarCrate == null)
				{
					barcode = null;
				}
				else
				{
					Barcode barcode2 = ((ScannableReference)avatarCrate).Barcode;
					barcode = ((barcode2 != null) ? barcode2.ID : null);
				}
				if (KratosPunchMod.IsSupportedAvatar((string?)barcode) && KratosHeightRequest.IsSupported(val))
				{
					attempts--;
					Bind(rigManager, val);
				}
			}
		}
		catch (Exception ex)
		{
			Release();
			attempts = 0;
			log?.Invoke("Kratos height preview unavailable: " + ex.GetBaseException().Message);
		}
	}

	private static void Bind(RigManager rig, Avatar avatar)
	{
		Transform val = ((Component)avatar).transform.Find("KratosNativeMenuIntegration_DRAFT");
		if (!Object.op_Implicit((Object)(object)val) || !KratosHeightMenuHandoff.TryFindMenuCommand(val, out UltEventHolder _, out GameObject panel) || !TryMeasuredInches(avatar, out var inches))
		{
			return;
		}
		Transform transform = panel.transform;
		Slider val2 = Part<Slider>(transform, "HeightSlider");
		Text val3 = Part<Text>(transform, "CurrentHeightHeading");
		Text val4 = Part<Text>(transform, "HeightValue");
		Text val5 = Part<Text>(transform, "HeightMinimum");
		Text val6 = Part<Text>(transform, "HeightMaximum");
		Transform val7 = val.Find("MenuOpenState");
		Transform val8 = val.Find("LocalOwnerAndControllerReady");
		Transform val9 = val.Find("NativeOwnSliderDragLease");
		Transform val10 = val.Find("NativeOwnerMenuTranslationFollow/CanonicalCurrentAvatarValidation/ExactCurrentAvatarPermitted");
		Pointer pointer = FindPointer(val, "Left");
		Pointer pointer2 = FindPointer(val, "Right");
		if (!Object.op_Implicit((Object)(object)val2) || val2.minValue != 0f || val2.maxValue != 16f || !Object.op_Implicit((Object)(object)val3) || !Object.op_Implicit((Object)(object)val4) || !Object.op_Implicit((Object)(object)val5) || !Object.op_Implicit((Object)(object)val6) || !Object.op_Implicit((Object)(object)val7) || !Object.op_Implicit((Object)(object)val8) || !Object.op_Implicit((Object)(object)val9) || !Object.op_Implicit((Object)(object)val10) || (object)pointer == null || (object)pointer2 == null || ((Il2CppObjectBase)pointer.Event).Pointer == ((Il2CppObjectBase)pointer2.Event).Pointer)
		{
			return;
		}
		UltEvent val11 = FindHeightEvent(val, avatar, "HeightUpRequested", "HeightOneInchHigher");
		UltEvent val12 = FindHeightEvent(val, avatar, "HeightDownRequested", "HeightOneInchLower");
		UltEvent val13 = FindHeightEvent(val, avatar, "HeightSliderRequested_ReadNativeSliderValue", "CommitHeightSliderOnRelease");
		if (val11 == null || val12 == null || val13 == null)
		{
			return;
		}
		Binding current = new Binding
		{
			Rig = rig,
			Avatar = avatar,
			Panel = panel,
			Open = ((Component)val7).gameObject,
			Owner = ((Component)val10).gameObject,
			Ready = ((Component)val8).gameObject,
			SliderLease = ((Component)val9).gameObject,
			Slider = val2,
			Heading = val3,
			Value = val4,
			MinimumText = val5,
			MaximumText = val6,
			Pointers = new Pointer[2] { pointer, pointer2 },
			Applied = inches,
			Preview = inches,
			OriginalSlider = val2.value,
			OriginalWholeNumbers = val2.wholeNumbers,
			OriginalHeading = val3.text,
			OriginalValue = val4.text,
			OriginalMinimum = val5.text,
			OriginalMaximum = val6.text,
			OriginalFontSize = val4.fontSize,
			WasOpen = (((Component)val7).gameObject.activeSelf && panel.activeInHierarchy)
		};
		binding = current;
		AddApplyControls(current, transform);
		Replace(current, val11, delegate
		{
			Step(current, 1);
		});
		Replace(current, val12, delegate
		{
			Step(current, -1);
		});
		Replace(current, val13, delegate
		{
			if (OwnsOpenMenu(current))
			{
				current.Slider.SetValueWithoutNotify(SliderValue(current.Preview));
			}
		});
		val2.wholeNumbers = false;
		current.SliderChanged = UnityAction<float>.op_Implicit((Action<float>)delegate(float raw)
		{
			if (float.IsFinite(raw))
			{
				int num2 = FromSlider(raw);
				if (num2 != current.Preview && OwnsOpenMenu(current))
				{
					Preview(current, num2, snap: false);
				}
			}
		});
		((UnityEvent<float>)(object)val2.onValueChanged).AddListener(current.SliderChanged);
		Pointer[] pointers = current.Pointers;
		foreach (Pointer pointer3 in pointers)
		{
			pointer3.Callback = Action.op_Implicit((Action)delegate
			{
				PressApply(current, pointer3);
			});
			pointer3.Event.DynamicCalls += pointer3.Callback;
		}
		val5.text = Format(76) + "  MIN";
		val6.text = Format(120) + "  MAX";
		Preview(current, inches, snap: true);
	}

	private static T? Part<T>(Transform parent, string path) where T : Component
	{
		Transform obj = parent.Find(path);
		if (obj == null)
		{
			return default(T);
		}
		return ((Component)obj).GetComponent<T>();
	}

	private static Pointer? FindPointer(Transform menu, string side)
	{
		Transform val = menu.Find("NativeOwnMathPointer_" + side + "NativePointer");
		if (!Object.op_Implicit((Object)(object)val))
		{
			return null;
		}
		Transform val2 = val.Find("UnconsumedPress");
		Transform val3 = val.Find("FiniteForwardPlaneHit");
		Transform val4 = val.Find("PlanePoint");
		UltEventHolder? obj = Part<UltEventHolder>(val, "HitCandidatesOnPressOnly");
		UltEvent val5 = ((obj != null) ? obj.Event : null);
		List<PersistentCall> val6 = ((val5 != null) ? ((UltEventBase)val5)._PersistentCalls : null);
		if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val3) || !Object.op_Implicit((Object)(object)val4) || val5 == null || val6 == null || val6.Count < 2 || val6[0].Target != (Object)(object)((Component)val2).gameObject || val6[0].MethodName != "SetActive" || ((Il2CppArrayBase<PersistentArgument>)(object)val6[0].PersistentArguments).Length != 1 || !((Il2CppArrayBase<PersistentArgument>)(object)val6[0].PersistentArguments)[0].Bool)
		{
			return null;
		}
		return new Pointer(val5, ((Component)val2).gameObject, ((Component)val3).gameObject, val4);
	}

	private static UltEvent? FindHeightEvent(Transform menu, Avatar avatar, string name, string destination)
	{
		UltEventHolder? obj = Part<UltEventHolder>(menu, "IntegrationInterfaces_UNCONNECTED/" + name);
		UltEvent val = ((obj != null) ? obj.Event : null);
		UltEventHolder val2 = Part<UltEventHolder>(((Component)avatar).transform, "NativeHeightCoordinator/" + destination);
		List<PersistentCall> val3 = ((val != null) ? ((UltEventBase)val)._PersistentCalls : null);
		if (!Object.op_Implicit((Object)(object)val2) || val3 == null || val3.Count != 1 || !(val3[0].Target == (Object)(object)val2) || !(val3[0].MethodName == "Invoke") || ((Il2CppArrayBase<PersistentArgument>)(object)val3[0].PersistentArguments).Length != 0)
		{
			return null;
		}
		return val;
	}

	private static void Replace(Binding current, UltEvent source, Action callback)
	{
		Action val = Action.op_Implicit(callback);
		EventEdit eventEdit = new EventEdit(source, ((UltEventBase)source)._PersistentCalls, new List<PersistentCall>(), val);
		current.Edits.Add(eventEdit);
		source.DynamicCalls += val;
		((UltEventBase)source)._PersistentCalls = eventEdit.After;
	}

	private static void AddApplyControls(Binding current, Transform panel)
	{
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b2: Expected O, but got Unknown
		//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
		RectTransform val = RequireRect(panel, "HeightHeading");
		RectTransform val2 = RequireRect(panel, "HeightSlider");
		RectTransform val3 = RequireRect(panel, "HeightUp");
		RectTransform val4 = RequireRect(panel, "HeightUpBorder");
		RectTransform val5 = RequireRect(panel, "HeightUpLabel");
		RectTransform val6 = RequireRect(panel, "HeightDown");
		RectTransform val7 = RequireRect(panel, "HeightDownBorder");
		RectTransform val8 = RequireRect(panel, "HeightDownLabel");
		fl