Decompiled source of CustomCrest v4.0.0

plugins/CrestComposition.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx.Logging;
using GlobalEnums;
using GlobalSettings;
using HarmonyLib;
using HutongGames.PlayMaker;
using HutongGames.PlayMaker.Actions;
using InControl;
using Microsoft.CodeAnalysis;
using Needleforge;
using Needleforge.Attacks;
using Needleforge.Components;
using Needleforge.Data;
using Silksong.FsmUtil;
using Silksong.FsmUtil.Actions;
using TeamCherry.SharedUtils;
using UnityEngine;

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

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

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CrestComposition
{
	public static class AnimationLibraryLookup
	{
		private const BindingFlags InstanceFieldFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly FieldInfo? _animLookupField = typeof(tk2dSpriteAnimation).GetField("lookup", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly FieldInfo? _animIsValidField = typeof(tk2dSpriteAnimation).GetField("isValid", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly Type? _animInfoType = typeof(tk2dSpriteAnimation).GetNestedType("AnimationInfo", BindingFlags.NonPublic);

		public static void Refresh(tk2dSpriteAnimation? animLib)
		{
			if ((Object)(object)animLib == (Object)null)
			{
				return;
			}
			if (_animLookupField != null && _animInfoType != null)
			{
				object obj = Activator.CreateInstance(typeof(Dictionary<, >).MakeGenericType(typeof(string), _animInfoType));
				if (obj is IDictionary)
				{
					_animLookupField.SetValue(animLib, obj);
				}
			}
			if (_animIsValidField != null)
			{
				_animIsValidField.SetValue(animLib, false);
			}
			animLib.ValidateLookup();
		}
	}
	public sealed class AttackSource
	{
		private readonly CrestData? _crest;

		public string Id { get; }

		public VanillaCrestType? VanillaType { get; }

		public bool IsVanilla => VanillaType.HasValue;

		public bool HasPlayableDashAttack
		{
			get
			{
				CrestData? crest = _crest;
				DashAttack val = ((crest != null) ? crest.Moveset.DashSlash : null);
				if (val == null)
				{
					return true;
				}
				if (((MultiStepAttack<Step>)(object)val).Steps != null && ((MultiStepAttack<Step>)(object)val).Steps.Length != 0)
				{
					return Array.TrueForAll(((MultiStepAttack<Step>)(object)val).Steps, (Step step) => (Object)(object)((AttackBase)step).AnimLibrary != (Object)null && ((AttackBase)step).AnimLibrary.GetClipByName(((AttackBase)step).AnimName) != null);
				}
				return false;
			}
		}

		internal AttackSource(VanillaCrestType vanillaType)
		{
			Id = vanillaType.ToString();
			VanillaType = vanillaType;
		}

		internal AttackSource(CrestData crest)
		{
			Id = crest.name;
			_crest = crest;
		}

		public ConfigGroup? FindConfigGroup(HeroController hc)
		{
			if (!VanillaType.HasValue)
			{
				CrestData? crest = _crest;
				if (crest == null)
				{
					return null;
				}
				return crest.Moveset.ConfigGroup;
			}
			return VanillaCrestCatalog.FindVanillaConfigGroup(hc, VanillaType.Value);
		}
	}
	public static class AttackSourceCatalog
	{
		private static readonly FieldInfo? _needleforgeCrestsField = typeof(NeedleforgePlugin).GetField("newCrestData", BindingFlags.Static | BindingFlags.NonPublic);

		internal static CrestData? FindNeedleforgeCrest(string crestName)
		{
			if (!(_needleforgeCrestsField?.GetValue(null) is List<CrestData> list))
			{
				return null;
			}
			return list.Find((CrestData crest) => string.Equals(crest.name, crestName, StringComparison.Ordinal));
		}

		public static List<AttackSource> GetAvailable(ManualLogSource? logger = null)
		{
			List<AttackSource> list = new List<AttackSource>();
			foreach (VanillaCrestType key in VanillaCrestCatalog.All.Keys)
			{
				list.Add(new AttackSource(key));
			}
			if (!(_needleforgeCrestsField?.GetValue(null) is List<CrestData> list2))
			{
				if (logger != null)
				{
					logger.LogWarning((object)"[CrestComposition] Could not read Needleforge's crest list; only vanilla crests can be borrowed.");
				}
				return list;
			}
			foreach (CrestData crest in list2)
			{
				if (!CrestMovesetComposer.IsComposed(crest) && list.FindIndex((AttackSource source) => string.Equals(source.Id, crest.name, StringComparison.Ordinal)) < 0)
				{
					list.Add(new AttackSource(crest));
				}
			}
			return list;
		}
	}
	public sealed class BindOutcomeComposer
	{
		private const string BindSharedState = "Bind Shared";

		private const string QuickCraftStartState = "Quick Craft Start";

		private const string EndBindState = "End Bind";

		private readonly CrestComposerContext _context;

		private VanillaCrestType _activeOutcome;

		private VoidBindBridge? _voidBind;

		public VanillaCrestType ActiveOutcome => _activeOutcome;

		public string ActiveOutcomeId
		{
			get
			{
				if (_voidBind == null)
				{
					return _activeOutcome.ToString();
				}
				return "Void";
			}
		}

		internal bool IsVoidActive => _voidBind != null;

		private string RageBindEvent => _context.CrestData.name + " RAGE BIND";

		private string QuickCraftEvent => _context.CrestData.name + " QUICK CRAFT";

		private string VoidSpecialEvent => _context.CrestData.name + " VOID SPECIAL";

		internal BindOutcomeComposer(CrestComposerContext context, VanillaCrestType initialOutcome)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			_context = context;
			_activeOutcome = initialOutcome;
			_context.CrestData.BindEvent = new BindEventHandler(HandleBindStarted);
			_context.CrestData.BindCompleteEvent = HandleBindCompleted;
		}

		internal void InitializeOnHeroAwake()
		{
			ApplyOutcome(_activeOutcome, _voidBind);
		}

		internal void InitializeOnHeroStart(HeroController hc)
		{
			PlayMakerFSM bind = FsmUtil.GetFsmPreprocessed(((Component)hc).gameObject, "Bind");
			PlayMakerFSM obj = bind;
			FsmState val = ((obj != null) ? FsmUtil.GetState(obj, _context.CrestData.name + " Bind") : null);
			PlayMakerFSM obj2 = bind;
			FsmState val2 = ((obj2 != null) ? FsmUtil.GetState(obj2, "Which Crest?") : null);
			if ((Object)(object)bind == (Object)null || val == null || val2 == null)
			{
				ManualLogSource? logger = _context.Logger;
				if (logger != null)
				{
					logger.LogError((object)("[CrestComposition] Could not find the bind states for '" + _context.CrestData.name + "'."));
				}
				return;
			}
			FsmUtil.AddTransition(val, RageBindEvent, "Bind Shared");
			FsmUtil.AddTransition(val2, QuickCraftEvent, "Quick Craft Start");
			AddVoidSpecialBind(bind, val2);
			if (_voidBind != null)
			{
				SyncVoidButtonHint();
			}
			FsmBool wasUpPressed = FsmUtil.GetBoolVariable(bind, "Was Up Pressed");
			FsmBool isBinding = FsmUtil.GetBoolVariable(bind, "Is Binding");
			FsmUtil.InsertMethod(val2, (Action)delegate
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				if (_voidBind != null && _context.CrestData.IsEquipped && VoidBindBridge.IsDirectionPressed(hc, _voidBind.SpecialBind.Direction))
				{
					bind.Fsm.Event(VoidSpecialEvent);
				}
				else if (_activeOutcome == VanillaCrestType.Toolmaster && _context.CrestData.IsEquipped && wasUpPressed.Value && ToolItemManager.TryReplenishTools(false, (ReplenishMethod)1))
				{
					isBinding.Value = true;
					bind.Fsm.Event(QuickCraftEvent);
				}
			}, 0, false);
		}

		public List<string> GetAvailableOutcomes()
		{
			List<string> list = new List<string>();
			foreach (VanillaCrestType key in VanillaCrestCatalog.All.Keys)
			{
				list.Add(key.ToString());
			}
			if (VoidBindBridge.Resolve(_context.Logger) != null)
			{
				list.Add("Void");
			}
			return list;
		}

		public void ApplyBindOutcome(VanillaCrestType crestType)
		{
			ApplyOutcome(crestType, null);
		}

		public void ApplyBindOutcome(string outcomeId)
		{
			VoidBindBridge voidBindBridge = (string.Equals(outcomeId, "Void", StringComparison.Ordinal) ? VoidBindBridge.Resolve(_context.Logger) : null);
			if (voidBindBridge != null)
			{
				ApplyOutcome(VanillaCrestType.Hunter, voidBindBridge);
				return;
			}
			if (Enum.TryParse<VanillaCrestType>(outcomeId, out var result) && VanillaCrestCatalog.All.ContainsKey(result))
			{
				ApplyOutcome(result, null);
				return;
			}
			ManualLogSource? logger = _context.Logger;
			if (logger != null)
			{
				logger.LogWarning((object)("[CrestComposition] Bind outcome '" + outcomeId + "' is not available; using Hunter."));
			}
			ApplyOutcome(VanillaCrestType.Hunter, null);
		}

		private void ApplyOutcome(VanillaCrestType crestType, VoidBindBridge? voidBind)
		{
			bool flag = _activeOutcome != crestType || _voidBind != voidBind;
			VoidBindBridge voidBind2 = _voidBind;
			_activeOutcome = crestType;
			_voidBind = voidBind;
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (voidBind != null || voidBind2 != null)
			{
				SyncVoidButtonHint();
			}
			if (voidBind == null && voidBind2 != null && _context.IsCustomCrestEquipped(instance))
			{
				voidBind2.SetSpoolVisible(visible: false);
			}
			_context.SetSlotClips(AttackSlot.Bind, CrestComposerContext.CollectClips(instance, new AttackSource(crestType), GetClipFilter(crestType)));
			if (!((MonoBehaviour)instance).didStart)
			{
				_context.RebuildAnimations();
				return;
			}
			if (flag && _context.IsCustomCrestEquipped(instance))
			{
				instance.ResetAllCrestState();
			}
			_context.RefreshConfigGroup(instance);
			ManualLogSource? logger = _context.Logger;
			if (logger != null)
			{
				logger.LogInfo((object)("[CrestComposition] Applied bind outcome '" + ActiveOutcomeId + "' to '" + _context.CrestData.name + "'."));
			}
		}

		internal void HandleEnemyDamaged(HealthManager enemy, HitInstance hit)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Invalid comparison between Unknown and I4
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Invalid comparison between Unknown and I4
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Invalid comparison between Unknown and I4
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			HeroController instance = HeroController.instance;
			if (_activeOutcome == VanillaCrestType.Reaper && !((Object)(object)instance == (Object)null) && _context.CrestData.IsEquipped && instance.ReaperState.IsInReaperMode && (int)hit.SilkGeneration != 2 && !enemy.DoNotGiveSilk && (int)enemy.enemyType != 3 && (int)enemy.enemyType != 6 && ((int)hit.AttackType == 0 || ((int)hit.AttackType == 16 && hit.IsNailTag)))
			{
				int reaperOrbCount = GetReaperOrbCount(instance, enemy);
				if (reaperOrbCount > 0)
				{
					SpawnReaperOrbs(enemy, hit, reaperOrbCount);
				}
			}
		}

		private void AddVoidSpecialBind(PlayMakerFSM bind, FsmState whichCrestState)
		{
			VoidBindBridge voidBindBridge = VoidBindBridge.Resolve(_context.Logger);
			if (voidBindBridge != null)
			{
				FsmState val = FsmUtil.AddState(bind, _context.CrestData.name + " Void Special");
				FsmUtil.AddLambdaMethod(val, voidBindBridge.SpecialBind.lambdaMethod);
				FsmUtil.AddTransition(val, "FINISHED", "End Bind");
				FsmUtil.AddTransition(whichCrestState, VoidSpecialEvent, val.Name);
			}
		}

		private void SyncVoidButtonHint()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			ToolCrest toolCrest = _context.CrestData.ToolCrest;
			if (!((Object)(object)toolCrest == (Object)null))
			{
				VoidBindBridge? voidBind = _voidBind;
				ToolCrest val = ((voidBind != null) ? voidBind.Crest.ToolCrest : null);
				toolCrest.hasCustomAction = (Object)(object)val != (Object)null && val.hasCustomAction;
				toolCrest.customButtonCombo = (Display)(((Object)(object)val != (Object)null) ? val.customButtonCombo : default(Display));
			}
		}

		private void HandleBindStarted(FsmInt healAmount, FsmInt bindAmount, FsmFloat bindTime, PlayMakerFSM fsm)
		{
			if (_voidBind != null)
			{
				_voidBind.StartBind(healAmount, bindAmount, bindTime, fsm);
				return;
			}
			switch (_activeOutcome)
			{
			case VanillaCrestType.Warrior:
				DeactivateFsmObjects(fsm, "Warrior_Bind_antic_silk", "Bind Silk", "Pt Charge");
				healAmount.Value = 0;
				bindAmount.Value = 1;
				bindTime.Value = 0.2f;
				FsmUtil.GetFloatVariable(fsm, "Quick Bind Effect Delay").Value = 0f;
				FsmUtil.GetBoolVariable(fsm, "Is Warrior Equipped").Value = true;
				fsm.Fsm.Event(RageBindEvent);
				break;
			case VanillaCrestType.Witch:
				DeactivateFsmObjects(fsm, "Whip_Bind_silk_antic", "Witch Bind", "Witch Bind Maggot Cleanse", "Bind Silk", "Pt Charge");
				healAmount.Value = (((ToolBase)Gameplay.MultibindTool).IsEquipped ? 4 : 3);
				bindAmount.Value = 1;
				bindTime.Value = 0.2f;
				FsmUtil.GetFloatVariable(fsm, "Quick Bind Effect Delay").Value = 0f;
				FsmUtil.GetBoolVariable(fsm, "Is Witch Equipped").Value = true;
				break;
			case VanillaCrestType.Spell:
				DeactivateFsmObjects(fsm, "Shaman_Bind_antic_silk");
				SetFsmObjectActive(fsm, "Shaman_Bind_antic_silk", active: true);
				FsmUtil.GetBoolVariable(fsm, "Is Shaman Equipped").Value = true;
				FsmUtil.GetFloatVariable(fsm, "Quick Bind Effect Delay").Value = 0.3f;
				FsmUtil.GetStringVariable(fsm, "Air BindCharge Anim").Value = "BindCharge Air";
				FsmUtil.GetStringVariable(fsm, "Ground BindCharge Anim").Value = "BindCharge Ground";
				ApplyMultibind(healAmount, bindAmount, bindTime);
				break;
			default:
				ApplyMultibind(healAmount, bindAmount, bindTime);
				break;
			}
		}

		private void HandleBindCompleted()
		{
			HeroController instance = HeroController.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (_activeOutcome == VanillaCrestType.Warrior)
				{
					StartRage(instance);
				}
				else if (_activeOutcome == VanillaCrestType.Reaper)
				{
					StartReaperMode(instance);
				}
			}
		}

		private static void StartRage(HeroController hc)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!hc.warriorState.IsInRageMode)
			{
				hc.AddFrost(-15f);
				StatusVignette.AddStatus((StatusTypes)3);
			}
			hc.warriorState = default(WarriorCrestStateInfo);
			hc.warriorState.IsInRageMode = true;
			hc.warriorState.RageEffectTimeLeft = Gameplay.WarriorRageDuration;
			hc.warriorState.RageHealTimeLeft = Gameplay.WarriorRageDuration + Gameplay.WarriorRageGraceTime;
			hc.RestartWarriorRageEffect();
			BrightnessEffect component = ((Component)hc.gm.cameraCtrl).GetComponent<BrightnessEffect>();
			component.ExtraEffectFadeTo(1.15f, 1.15f, 0f, 0f);
			component.ExtraEffectFadeTo(1f, 1f, 2f, 0.3f);
			EventRegister.SendEvent(EventRegisterEvents.WarriorRageStarted, (GameObject)null);
		}

		private static void StartReaperMode(HeroController hc)
		{
			hc.reaperState.IsInReaperMode = true;
			hc.reaperState.ReaperModeDurationLeft = Gameplay.ReaperModeDuration;
			if (Object.op_Implicit((Object)(object)hc.reaperModeEffect))
			{
				((Component)hc.reaperModeEffect).gameObject.SetActive(false);
				((Component)hc.reaperModeEffect).gameObject.SetActive(true);
			}
		}

		private static int GetReaperOrbCount(HeroController hc, HealthManager enemy)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			ReaperBundleTiers reaperBundles = enemy.reaperBundles;
			if ((int)reaperBundles != 0)
			{
				if ((int)reaperBundles == 1)
				{
					return 1;
				}
				return 0;
			}
			return hc.GetReaperPayout();
		}

		private static void SpawnReaperOrbs(HealthManager enemy, HitInstance hit, int orbCount)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			float num;
			float angleMin;
			float angleMax;
			if ((Object)(object)enemy.flingSilkOrbsAimObject != (Object)null)
			{
				Vector3 val = enemy.flingSilkOrbsAimObject.transform.position - ((Component)enemy).transform.position;
				num = Mathf.Atan2(val.y, val.x) * 57.29578f;
				angleMin = num - 45f;
				angleMax = num + 45f;
			}
			else if (enemy.flingSilkOrbsDown)
			{
				num = 270f;
				angleMin = 225f;
				angleMax = 315f;
			}
			else
			{
				switch (DirectionUtils.GetCardinalDirection(((HitInstance)(ref hit)).GetActualDirection(((Component)enemy).transform, (TargetType)0)))
				{
				case 2:
					num = 180f;
					angleMin = 125f;
					angleMax = 225f;
					break;
				case 1:
					num = 90f;
					angleMin = 45f;
					angleMax = 135f;
					break;
				case 3:
					num = 270f;
					angleMin = 225f;
					angleMax = 315f;
					break;
				default:
					num = 0f;
					angleMin = 315f;
					angleMax = 415f;
					break;
				}
			}
			FlingUtils.SpawnAndFling(new Config
			{
				Prefab = Gameplay.ReaperBundlePrefab,
				AmountMin = orbCount,
				AmountMax = orbCount,
				SpeedMin = 25f,
				SpeedMax = 50f,
				AngleMin = angleMin,
				AngleMax = angleMax
			}, ((Component)enemy).transform, enemy.effectOrigin, (List<GameObject>)null, -1f);
			SpawnReapHitEffect(enemy, num);
		}

		private static void SpawnReapHitEffect(HealthManager enemy, float degrees)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			GameObject reapHitEffectPrefab = Effects.ReapHitEffectPrefab;
			if (Object.op_Implicit((Object)(object)reapHitEffectPrefab))
			{
				Vector2 val = default(Vector2);
				float num;
				switch (DirectionUtils.GetCardinalDirection(degrees))
				{
				case 1:
					((Vector2)(ref val))..ctor(1f, 1f);
					num = 90f;
					break;
				case 2:
					((Vector2)(ref val))..ctor(-1f, 1f);
					num = 0f;
					break;
				case 3:
					((Vector2)(ref val))..ctor(1f, -1f);
					num = 90f;
					break;
				default:
					((Vector2)(ref val))..ctor(1f, 1f);
					num = 0f;
					break;
				}
				GameObject val2 = ObjectPoolExtensions.Spawn(reapHitEffectPrefab, ((Component)enemy).transform.TransformPoint(enemy.effectOrigin));
				Extensions.SetRotation2D(val2.transform, num);
				val2.transform.localScale = Extensions.ToVector3(val, val2.transform.localScale.z);
			}
		}

		private static void ApplyMultibind(FsmInt healAmount, FsmInt bindAmount, FsmFloat bindTime)
		{
			if (((ToolBase)Gameplay.MultibindTool).IsEquipped)
			{
				healAmount.Value = 2;
				bindAmount.Value = 2;
				bindTime.Value = 0.8f;
			}
		}

		private static void DeactivateFsmObjects(PlayMakerFSM fsm, params string[] variableNames)
		{
			foreach (string variableName in variableNames)
			{
				SetFsmObjectActive(fsm, variableName, active: false);
			}
		}

		private static void SetFsmObjectActive(PlayMakerFSM fsm, string variableName, bool active)
		{
			FsmGameObject obj = fsm.FsmVariables.FindFsmGameObject(variableName);
			GameObject val = ((obj != null) ? obj.Value : null);
			if ((Object)(object)val != (Object)null)
			{
				val.SetActive(active);
			}
		}

		private static Predicate<string> GetClipFilter(VanillaCrestType crestType)
		{
			return crestType switch
			{
				VanillaCrestType.Warrior => (string clipName) => clipName.StartsWith("Rage Bind", StringComparison.Ordinal), 
				VanillaCrestType.Spell => (string clipName) => clipName.StartsWith("BindCharge", StringComparison.Ordinal), 
				_ => (string _) => false, 
			};
		}
	}
	internal static class BorrowedAttackEffects
	{
		private static readonly FieldInfo? _attackStartingField = typeof(NailAttackBase).GetField("AttackStarting", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		public static void CarryOver(GameObject source, GameObject clone, TintRendererGroup? rootTint)
		{
			NailAttackBase[] componentsInChildren = source.GetComponentsInChildren<NailAttackBase>(true);
			NailAttackBase[] componentsInChildren2 = clone.GetComponentsInChildren<NailAttackBase>(true);
			for (int i = 0; i < componentsInChildren.Length && i < componentsInChildren2.Length; i++)
			{
				foreach (AttackBase item in FindNeedleforgeAttacks(componentsInChildren[i]))
				{
					AddStartEffects(componentsInChildren2[i], item);
				}
			}
			ChargedAttackAutoTrigger component = source.GetComponent<ChargedAttackAutoTrigger>();
			if ((Object)(object)component != (Object)null && component.attack != null)
			{
				clone.AddComponent<BorrowedChargedTrigger>().Source = component.attack;
			}
			if ((Object)(object)rootTint != (Object)null)
			{
				clone.AddComponent<BorrowedRootTint>().Source = rootTint;
			}
		}

		private static HashSet<AttackBase> FindNeedleforgeAttacks(NailAttackBase sourceAttack)
		{
			HashSet<AttackBase> hashSet = new HashSet<AttackBase>();
			if (_attackStartingField?.GetValue(sourceAttack) is Delegate obj)
			{
				Delegate[] invocationList = obj.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					object? target = invocationList[i].Target;
					AttackBase val = (AttackBase)((target is AttackBase) ? target : null);
					if (val != null)
					{
						hashSet.Add(val);
					}
				}
			}
			return hashSet;
		}

		private static void AddStartEffects(NailAttackBase cloneAttack, AttackBase attack)
		{
			DamageEnemies damager = ((Component)cloneAttack).GetComponent<DamageEnemies>();
			tk2dSprite sprite = ((Component)cloneAttack).GetComponent<tk2dSprite>();
			cloneAttack.AttackStarting += delegate
			{
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)damager != (Object)null && (Object)(object)sprite != (Object)null && (int)damager.NailElement == 0)
				{
					((tk2dBaseSprite)sprite).color = attack.Color;
				}
			};
			Step step = default(Step);
			ref Step reference = ref step;
			AttackBase obj = attack;
			reference = (Step)(object)((obj is Step) ? obj : null);
			if (step != null)
			{
				Transform parent = ((Component)cloneAttack).transform.parent;
				cloneAttack.AttackStarting += delegate
				{
					SendScreenEffects(parent, step);
				};
			}
		}

		private static void SendScreenEffects(Transform parent, Step step)
		{
			if (step.CameraShakeIndex.HasValue)
			{
				((Component)parent).SendMessage("DoCameraShake", (object)step.CameraShakeIndex.Value, (SendMessageOptions)1);
			}
			if (step.ScreenFlashIndex.HasValue)
			{
				((Component)parent).SendMessage("DoScreenFlash", (object)step.ScreenFlashIndex.Value, (SendMessageOptions)1);
			}
		}
	}
	internal sealed class BorrowedChargedTrigger : MonoBehaviour
	{
		public ChargedAttack? Source;

		private void OnEnable()
		{
			if (Source != null && Source.PlayOnActivation && ((MultiStepAttack<Step>)(object)Source).Steps != null && ((MultiStepAttack<Step>)(object)Source).Steps.Length != 0)
			{
				((MonoBehaviour)this).StartCoroutine(PlaySteps(Source));
			}
		}

		private void OnDisable()
		{
			((MonoBehaviour)this).StopAllCoroutines();
		}

		private IEnumerator PlaySteps(ChargedAttack attack)
		{
			yield return null;
			Step[] steps = ((MultiStepAttack<Step>)(object)attack).Steps;
			foreach (Step step in steps)
			{
				NailSlash slash = FindClonedStep(step);
				if (!((Object)(object)slash == (Object)null))
				{
					slash.StartSlash();
					yield return null;
					tk2dSpriteAnimator animator = ((Component)slash).GetComponent<tk2dSpriteAnimator>();
					while ((Object)(object)animator != (Object)null && animator.Playing && animator.CurrentClip != null)
					{
						yield return null;
					}
					if (!attack.PlayStepsInSequence)
					{
						break;
					}
				}
			}
			if (attack.DisableAfterLastStep)
			{
				((Component)this).gameObject.SetActive(false);
			}
		}

		private NailSlash? FindClonedStep(Step step)
		{
			if ((Object)(object)((GameObjectProxy)step).GameObject == (Object)null)
			{
				return null;
			}
			int siblingIndex = ((GameObjectProxy)step).GameObject.transform.GetSiblingIndex();
			if (siblingIndex >= ((Component)this).transform.childCount)
			{
				return null;
			}
			return ((Component)((Component)this).transform.GetChild(siblingIndex)).GetComponent<NailSlash>();
		}
	}
	internal sealed class BorrowedRootTint : MonoBehaviour
	{
		public TintRendererGroup? Source;

		private SpriteRenderer[] _sprites = Array.Empty<SpriteRenderer>();

		private IVertexColor[] _vertexColors = Array.Empty<IVertexColor>();

		private void OnEnable()
		{
			_sprites = ((Component)this).GetComponentsInChildren<SpriteRenderer>(true);
			_vertexColors = ((Component)this).GetComponentsInChildren<IVertexColor>(true);
		}

		private void LateUpdate()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			HeroController instance = HeroController.instance;
			if (!((Object)(object)Source == (Object)null) && !((Object)(object)instance == (Object)null) && (int)instance.NailImbuement.CurrentElement == 0)
			{
				Color color = Source.Color;
				SpriteRenderer[] sprites = _sprites;
				foreach (SpriteRenderer val in sprites)
				{
					color.a = val.color.a;
					val.color = color;
				}
				IVertexColor[] vertexColors = _vertexColors;
				foreach (IVertexColor val2 in vertexColors)
				{
					color.a = val2.VertexColor.a;
					val2.VertexColor = color;
				}
			}
		}
	}
	internal enum AttackSlot
	{
		Neutral,
		Up,
		Down,
		Dash,
		Bind
	}
	internal sealed class CrestComposerContext
	{
		internal static readonly FieldInfo? ActivateOnSlashField = typeof(NailAttackBase).GetField("activateOnSlash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private readonly List<tk2dSpriteAnimationClip> _baseOverrideClips = new List<tk2dSpriteAnimationClip>();

		private readonly Dictionary<AttackSlot, List<tk2dSpriteAnimationClip>> _slotClips = new Dictionary<AttackSlot, List<tk2dSpriteAnimationClip>>();

		private readonly Dictionary<GameObject, GameObject> _cloneBySource = new Dictionary<GameObject, GameObject>();

		private readonly Dictionary<GameObject, bool> _restActiveByClone = new Dictionary<GameObject, bool>();

		private readonly List<GameObject> _allClones = new List<GameObject>();

		private tk2dSpriteAnimation? _overrideAnimLibrary;

		private GameObject? _rageNormal;

		private GameObject? _rageAlternate;

		private GameObject? _rageWall;

		private GameObject? _rageUp;

		public CrestData CrestData { get; }

		public ManualLogSource? Logger { get; }

		public IReadOnlyList<AttackSource> Sources { get; private set; } = Array.Empty<AttackSource>();

		public IReadOnlyList<GameObject> AllClones => _allClones;

		public ConfigGroup? RageAttacks { get; private set; }

		public CrestComposerContext(CrestData crestData, ManualLogSource? logger)
		{
			CrestData = crestData;
			Logger = logger;
		}

		public void BeginHeroAwake()
		{
			_cloneBySource.Clear();
			_restActiveByClone.Clear();
			_allClones.Clear();
			_rageNormal = null;
			_rageAlternate = null;
			_rageWall = null;
			_rageUp = null;
			RageAttacks = null;
			Sources = AttackSourceCatalog.GetAvailable(Logger);
			ConfigGroup configGroup = CrestData.Moveset.ConfigGroup;
			if ((Object)(object)configGroup?.ActiveRoot != (Object)null)
			{
				configGroup.ActiveRoot.SetActive(false);
			}
			tk2dSpriteAnimation val = ((HeroControllerConfig)(CrestData.Moveset.HeroConfig?)).heroAnimOverrideLib;
			if (_baseOverrideClips.Count == 0 && (Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)_overrideAnimLibrary && val.clips != null)
			{
				AddValidClips(_baseOverrideClips, val.clips);
			}
		}

		public FsmEdit GuardFsmEdit(string slotName, FsmEdit edit)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			return (FsmEdit)delegate(PlayMakerFSM fsm, FsmState startState, out FsmState[] endStates)
			{
				try
				{
					edit.Invoke(fsm, startState, ref endStates);
				}
				catch (Exception arg)
				{
					ManualLogSource? logger = Logger;
					if (logger != null)
					{
						logger.LogError((object)$"[CrestComposition] Building the {slotName} FSM for '{CrestData.name}' failed: {arg}");
					}
					endStates = (FsmState[])(object)new FsmState[1] { startState };
				}
			};
		}

		public AttackSource? FindSource(string sourceId)
		{
			foreach (AttackSource source in Sources)
			{
				if (string.Equals(source.Id, sourceId, StringComparison.Ordinal))
				{
					return source;
				}
			}
			return null;
		}

		public void SetBaseOverrideClips(IEnumerable<tk2dSpriteAnimationClip>? baseClips)
		{
			_baseOverrideClips.Clear();
			if (baseClips != null)
			{
				AddValidClips(_baseOverrideClips, baseClips);
			}
			if ((Object)(object)_overrideAnimLibrary != (Object)null)
			{
				RebuildAnimations();
			}
		}

		public void SetSlotClips(AttackSlot slot, List<tk2dSpriteAnimationClip> clips)
		{
			_slotClips[slot] = clips;
		}

		public static List<tk2dSpriteAnimationClip> CollectClips(HeroController hc, AttackSource source, Predicate<string> nameFilter)
		{
			List<tk2dSpriteAnimationClip> list = new List<tk2dSpriteAnimationClip>();
			if (source.VanillaType == VanillaCrestType.Hunter)
			{
				return list;
			}
			tk2dSpriteAnimation val = source.FindConfigGroup(hc)?.Config?.heroAnimOverrideLib;
			if ((Object)(object)val == (Object)null || val.clips == null)
			{
				return list;
			}
			tk2dSpriteAnimationClip[] clips = val.clips;
			foreach (tk2dSpriteAnimationClip val2 in clips)
			{
				if (val2 != null && !string.IsNullOrEmpty(val2.name) && nameFilter(val2.name))
				{
					list.Add(val2);
				}
			}
			return list;
		}

		public void RebuildAnimations()
		{
			HeroConfigNeedleforge heroConfig = CrestData.Moveset.HeroConfig;
			if ((Object)(object)heroConfig == (Object)null)
			{
				return;
			}
			EnsureOverrideAnimationLibrary();
			List<tk2dSpriteAnimationClip> list = new List<tk2dSpriteAnimationClip>(_baseOverrideClips);
			AttackSlot[] array = new AttackSlot[5]
			{
				AttackSlot.Neutral,
				AttackSlot.Up,
				AttackSlot.Down,
				AttackSlot.Dash,
				AttackSlot.Bind
			};
			foreach (AttackSlot key in array)
			{
				if (!_slotClips.TryGetValue(key, out List<tk2dSpriteAnimationClip> value))
				{
					continue;
				}
				foreach (tk2dSpriteAnimationClip clip in value)
				{
					int num = list.FindIndex((tk2dSpriteAnimationClip c) => c != null && string.Equals(c.name, clip.name, StringComparison.Ordinal));
					if (num >= 0)
					{
						list[num] = clip;
					}
					else
					{
						list.Add(clip);
					}
				}
			}
			_overrideAnimLibrary.clips = list.ToArray();
			AnimationLibraryLookup.Refresh(_overrideAnimLibrary);
			((HeroControllerConfig)heroConfig).heroAnimOverrideLib = _overrideAnimLibrary;
		}

		public void RefreshConfigGroup(HeroController hc)
		{
			ConfigGroup configGroup = CrestData.Moveset.ConfigGroup;
			HeroConfigNeedleforge heroConfig = CrestData.Moveset.HeroConfig;
			if (configGroup == null || (Object)(object)heroConfig == (Object)null)
			{
				return;
			}
			bool flag = (Object)(object)configGroup.ActiveRoot != (Object)null && configGroup.ActiveRoot.activeSelf;
			configGroup.Setup();
			bool flag2 = IsCustomCrestEquipped(hc);
			if ((Object)(object)configGroup.ActiveRoot != (Object)null)
			{
				configGroup.ActiveRoot.SetActive(flag || flag2);
			}
			RebuildAnimations();
			if (flag2)
			{
				hc.crestConfig = (HeroControllerConfig)(object)heroConfig;
				hc.UpdateConfig();
				HeroAnimationController animCtrl = hc.AnimCtrl;
				if (animCtrl != null)
				{
					animCtrl.SetHeroControllerConfig((HeroControllerConfig)(object)heroConfig);
				}
			}
		}

		public void SetRageNeutralAttacks(GameObject? normal, GameObject? alternate, GameObject? wall)
		{
			_rageNormal = normal;
			_rageAlternate = alternate;
			_rageWall = wall;
			RebuildRageAttacks();
		}

		public void SetRageUpAttack(GameObject? up)
		{
			_rageUp = up;
			RebuildRageAttacks();
		}

		public static void ApplyAttackTiming(HeroConfigNeedleforge heroConfig, HeroControllerConfig source)
		{
			heroConfig.SetAttackFields((float?)source.AttackDuration, (float?)source.AttackRecoveryTime, (float?)source.AttackCooldownTime, (float?)source.QuickAttackSpeedMult, (float?)source.QuickAttackCooldownTime);
		}

		public bool IsCustomCrestEquipped(HeroController hc)
		{
			if (CrestData.IsEquipped)
			{
				return true;
			}
			if (string.Equals(PlayerData.instance?.CurrentCrestID, CrestData.name, StringComparison.Ordinal))
			{
				return true;
			}
			if (hc.CurrentConfigGroup != null)
			{
				return hc.CurrentConfigGroup == CrestData.Moveset.ConfigGroup;
			}
			return false;
		}

		public GameObject CloneOnce(HeroController hc, GameObject source, string cloneName)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			if (_cloneBySource.TryGetValue(source, out GameObject value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			GameObject val = Object.Instantiate<GameObject>(source, CrestData.Moveset.ConfigGroup.ActiveRoot.transform);
			((Object)val).name = cloneName;
			val.transform.SetLocalPositionAndRotation(source.transform.localPosition, source.transform.localRotation);
			val.transform.localScale = source.transform.localScale;
			_cloneBySource[source] = val;
			_restActiveByClone[val] = source.activeSelf;
			_allClones.Add(val);
			BorrowedAttackEffects.CarryOver(source, val, FindBorrowedRootTint(hc, source));
			RewireChildFsmsToHero(val, ((Component)hc).gameObject);
			RebindActivateOnSlashTargets(hc, val);
			return val;
		}

		public Dictionary<string, FsmGameObject> BuildVariableRemap(PlayMakerFSM fsm, HeroController hc, string sourceId, IEnumerable<FsmAttackObjectBinding> bindings)
		{
			Dictionary<string, FsmGameObject> dictionary = new Dictionary<string, FsmGameObject>(StringComparer.Ordinal);
			foreach (FsmAttackObjectBinding binding in bindings)
			{
				GameObject val = CloneBinding(hc, sourceId, binding);
				if ((Object)(object)val != (Object)null && binding.ChildPath != null)
				{
					Transform obj = val.transform.Find(binding.ChildPath);
					val = ((obj != null) ? ((Component)obj).gameObject : null);
				}
				if ((Object)(object)val == (Object)null)
				{
					ManualLogSource? logger = Logger;
					if (logger != null)
					{
						logger.LogError((object)("[CrestComposition] Could not resolve '" + binding.FsmVariableName + "' for '" + sourceId + "'."));
					}
				}
				else
				{
					dictionary[binding.FsmVariableName] = CreateBranchVariable(fsm, sourceId, binding.FsmVariableName, val);
				}
			}
			return dictionary;
		}

		public GameObject? CloneBinding(HeroController hc, string sourceId, FsmAttackObjectBinding binding)
		{
			Transform obj = hc.transform.Find("Attacks");
			object obj2;
			if (obj == null)
			{
				obj2 = null;
			}
			else
			{
				Transform obj3 = obj.Find(binding.AttacksPath);
				obj2 = ((obj3 != null) ? ((Component)obj3).gameObject : null);
			}
			GameObject val = (GameObject)obj2;
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return CloneOnce(hc, val, sourceId + "_" + binding.AttacksPath.Replace('/', '_'));
		}

		public FsmGameObject CreateBranchVariable(PlayMakerFSM fsm, string sourceId, string variableName, GameObject? value)
		{
			FsmGameObject gameObjectVariable = FsmUtil.GetGameObjectVariable(fsm, CrestData.name + "_" + sourceId + "_" + variableName);
			gameObjectVariable.Value = value;
			return gameObjectVariable;
		}

		public List<Transform> GetSourceAttackRoots(HeroController hc)
		{
			List<Transform> allVanillaAttackRoots = VanillaCrestCatalog.GetAllVanillaAttackRoots(hc);
			foreach (AttackSource source in Sources)
			{
				GameObject val = (source.IsVanilla ? null : source.FindConfigGroup(hc)?.ActiveRoot);
				if ((Object)(object)val != (Object)null)
				{
					allVanillaAttackRoots.Add(val.transform);
				}
			}
			return allVanillaAttackRoots;
		}

		public void ActivateSelection(IEnumerable<GameObject> slotClones, params GameObject?[] selected)
		{
			foreach (GameObject slotClone in slotClones)
			{
				slotClone.SetActive(false);
			}
			foreach (GameObject val in selected)
			{
				if ((Object)(object)val != (Object)null && _restActiveByClone.TryGetValue(val, out var value))
				{
					val.SetActive(value);
				}
			}
		}

		public static void DestroyDefaultAttack(GameObject? attack)
		{
			if (!((Object)(object)attack == (Object)null))
			{
				attack.transform.SetParent((Transform)null, false);
				Object.Destroy((Object)(object)attack);
			}
		}

		public static void RewireChildFsmsToHero(GameObject rootObject, GameObject heroObject)
		{
			PlayMakerFSM[] componentsInChildren = rootObject.GetComponentsInChildren<PlayMakerFSM>(true);
			foreach (PlayMakerFSM val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null || val.Fsm == null)
				{
					continue;
				}
				FsmVariables fsmVariables = val.FsmVariables;
				if (fsmVariables != null)
				{
					FsmGameObject val2 = fsmVariables.FindFsmGameObject("Hero") ?? fsmVariables.FindFsmGameObject("Player");
					if (val2 != null)
					{
						val2.Value = heroObject;
					}
				}
			}
		}

		private TintRendererGroup? FindBorrowedRootTint(HeroController hc, GameObject source)
		{
			foreach (AttackSource source2 in Sources)
			{
				GameObject val = (source2.IsVanilla ? null : source2.FindConfigGroup(hc)?.ActiveRoot);
				if ((Object)(object)val != (Object)null && source.transform.IsChildOf(val.transform))
				{
					return val.GetComponent<TintRendererGroup>();
				}
			}
			return null;
		}

		private void RebuildRageAttacks()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			if ((Object)(object)_rageNormal == (Object)null && (Object)(object)_rageAlternate == (Object)null && (Object)(object)_rageWall == (Object)null && (Object)(object)_rageUp == (Object)null)
			{
				RageAttacks = null;
				return;
			}
			RageAttacks = new ConfigGroup
			{
				Config = (HeroControllerConfig)(object)CrestData.Moveset.HeroConfig,
				NormalSlashObject = _rageNormal,
				AlternateSlashObject = _rageAlternate,
				WallSlashObject = _rageWall,
				UpSlashObject = _rageUp
			};
			RageAttacks.Setup();
		}

		private void RebindActivateOnSlashTargets(HeroController hc, GameObject clone)
		{
			if (ActivateOnSlashField == null)
			{
				return;
			}
			NailAttackBase[] componentsInChildren = clone.GetComponentsInChildren<NailAttackBase>(true);
			foreach (NailAttackBase obj in componentsInChildren)
			{
				if (!(ActivateOnSlashField.GetValue(obj) is GameObject[] array))
				{
					continue;
				}
				GameObject[] array2 = (GameObject[])(object)new GameObject[array.Length];
				for (int j = 0; j < array.Length; j++)
				{
					GameObject val = array[j];
					if ((Object)(object)val == (Object)null || val.transform.IsChildOf(clone.transform))
					{
						array2[j] = val;
						continue;
					}
					GameObject val2 = CloneOnce(hc, val, ((Object)clone).name + "_" + ((Object)val).name);
					val2.SetActive(false);
					_restActiveByClone[val2] = false;
					array2[j] = val2;
				}
				ActivateOnSlashField.SetValue(obj, array2);
			}
		}

		private void EnsureOverrideAnimationLibrary()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			if (!((Object)(object)_overrideAnimLibrary != (Object)null))
			{
				GameObject val = new GameObject(CrestData.name + "_OverrideAnimations");
				Object.DontDestroyOnLoad((Object)(object)val);
				_overrideAnimLibrary = val.AddComponent<tk2dSpriteAnimation>();
				_overrideAnimLibrary.clips = Array.Empty<tk2dSpriteAnimationClip>();
			}
		}

		private static void AddValidClips(List<tk2dSpriteAnimationClip> target, IEnumerable<tk2dSpriteAnimationClip> clips)
		{
			foreach (tk2dSpriteAnimationClip clip in clips)
			{
				if (clip != null && !string.IsNullOrEmpty(clip.name))
				{
					target.Add(clip);
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class CrestCompositionPatches
	{
		private const string HarmonyId = "com.zorkats.silksong.crestcomposition";

		private const string NeedleforgeHarmonyId = "io.github.needleforge";

		private static Harmony? _harmony;

		private static ManualLogSource? _logger;

		internal static void EnsureApplied(ManualLogSource? logger)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (_harmony == null)
			{
				_logger = logger;
				_harmony = new Harmony("com.zorkats.silksong.crestcomposition");
				_harmony.PatchAll(typeof(CrestCompositionPatches));
			}
		}

		internal static void PatchVoidFocusGate(MethodInfo focusGate)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.Patch((MethodBase)focusGate, (HarmonyMethod)null, new HarmonyMethod(typeof(CrestCompositionPatches), "AfterVoidFocusEnabled", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static void AfterVoidFocusEnabled(ref bool __result)
		{
			__result = __result || CrestMovesetComposer.IsVoidBinding(HeroController.instance);
		}

		[HarmonyPatch(typeof(HeroController), "Awake")]
		[HarmonyPostfix]
		[HarmonyAfter(new string[] { "io.github.needleforge" })]
		private static void AfterHeroAwake()
		{
			CrestMovesetComposer.InitializeAllOnHeroAwake();
		}

		[HarmonyPatch(typeof(HeroController), "Start")]
		[HarmonyPrefix]
		[HarmonyAfter(new string[] { "io.github.needleforge" })]
		private static void BeforeHeroStart(HeroController __instance)
		{
			CrestMovesetComposer.InitializeAllOnHeroStart(__instance);
		}

		[HarmonyPatch(typeof(HeroController), "Attack", new Type[] { typeof(AttackDirection) })]
		[HarmonyPrefix]
		private static void BeforeAttack(HeroController __instance, AttackDirection attackDir)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			CrestMovesetComposer.ApplyAttackTiming(__instance, attackDir);
		}

		[HarmonyPatch(typeof(HeroController), "Attack", new Type[] { typeof(AttackDirection) })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> AddWandererComboCheck(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Expected O, but got Unknown
			FieldInfo comboTimer = AccessTools.Field(typeof(HeroController), "wandererDashComboWindowTimer");
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int num = list.FindIndex((CodeInstruction instruction) => CodeInstructionExtensions.LoadsField(instruction, comboTimer, false));
			if (num < 1 || list[num - 1].opcode != OpCodes.Ldarg_0)
			{
				ManualLogSource? logger = _logger;
				if (logger != null)
				{
					logger.LogWarning((object)"[CrestComposition] HeroController.Attack has changed; the Wanderer combo will not start.");
				}
				return list;
			}
			CodeInstruction val = list[num - 1];
			Label label = generator.DefineLabel();
			CodeInstruction val2 = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), val);
			val.labels.Add(label);
			list.InsertRange(num - 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4]
			{
				val2,
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(CrestMovesetComposer), "TryStartWandererCombo", (Type[])null, (Type[])null)),
				new CodeInstruction(OpCodes.Brfalse, (object)label),
				new CodeInstruction(OpCodes.Ret, (object)null)
			});
			return list;
		}

		[HarmonyPatch(typeof(HeroController), "UpdateConfig")]
		[HarmonyPostfix]
		private static void AfterUpdateConfig(HeroController __instance)
		{
			CrestMovesetComposer.ApplyRageAttacks(__instance);
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		private static void AfterIsWandererLucky(HeroController __instance, ref bool __result)
		{
			__result = __result || CrestMovesetComposer.HasWandererLuck(__instance);
		}

		[HarmonyPatch(typeof(HealthManager), "TakeDamage", new Type[] { typeof(HitInstance) })]
		[HarmonyPrefix]
		private static void BeforeTakeDamage(HealthManager __instance, out int __state)
		{
			__state = GetDamageTarget(__instance).hp;
		}

		[HarmonyPatch(typeof(HealthManager), "TakeDamage", new Type[] { typeof(HitInstance) })]
		[HarmonyPostfix]
		private static void AfterTakeDamage(HealthManager __instance, HitInstance hitInstance, int __state)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (GetDamageTarget(__instance).hp < __state)
			{
				CrestMovesetComposer.NotifyEnemyDamaged(__instance, hitInstance);
			}
		}

		private static HealthManager GetDamageTarget(HealthManager enemy)
		{
			if (!((Object)(object)enemy.SendDamageTo != (Object)null))
			{
				return enemy;
			}
			return enemy.SendDamageTo;
		}
	}
	public sealed class CrestMovesetComposer
	{
		private static readonly List<CrestMovesetComposer> _composers = new List<CrestMovesetComposer>();

		private readonly CrestComposerContext _context;

		public CrestData CrestData { get; }

		public NeutralAttackComposer NeutralAttacks { get; }

		public UpAttackComposer UpAttacks { get; }

		public DownAttackComposer DownAttacks { get; }

		public DashAttackComposer DashAttacks { get; }

		public BindOutcomeComposer BindOutcome { get; }

		public bool LastSelfCheckPassed
		{
			get
			{
				if (NeutralAttacks.LastSelfCheckPassed && DownAttacks.LastSelfCheckPassed)
				{
					return DashAttacks.LastSelfCheckPassed;
				}
				return false;
			}
		}

		public event Action? OnMovesetInitialized;

		public CrestMovesetComposer(CrestData crestData, VanillaCrestType initialNeutralAttack, VanillaCrestType initialUpAttack, VanillaCrestType initialDownAttack, ManualLogSource? logger = null)
		{
			CrestData = crestData ?? throw new ArgumentNullException("crestData");
			_context = new CrestComposerContext(crestData, logger);
			NeutralAttacks = new NeutralAttackComposer(_context, initialNeutralAttack.ToString());
			UpAttacks = new UpAttackComposer(_context, initialUpAttack.ToString());
			DownAttacks = new DownAttackComposer(_context, initialDownAttack);
			DashAttacks = new DashAttackComposer(_context, VanillaCrestType.Hunter.ToString());
			BindOutcome = new BindOutcomeComposer(_context, VanillaCrestType.Hunter);
			_composers.Add(this);
			CrestCompositionPatches.EnsureApplied(logger);
		}

		internal static bool IsComposed(CrestData crestData)
		{
			return _composers.Exists((CrestMovesetComposer composer) => composer.CrestData == crestData);
		}

		public void SetNeutralAttack(VanillaCrestType crestType)
		{
			SetNeutralAttack(crestType.ToString());
		}

		public void SetNeutralAttack(string sourceId)
		{
			NeutralAttacks.ApplyNeutralAttack(sourceId);
		}

		public void SetUpAttack(VanillaCrestType crestType)
		{
			SetUpAttack(crestType.ToString());
		}

		public void SetUpAttack(string sourceId)
		{
			UpAttacks.ApplyUpAttack(sourceId);
		}

		public void SetDownAttack(VanillaCrestType crestType)
		{
			DownAttacks.ApplyDownAttack(crestType);
		}

		public void SetDashAttack(VanillaCrestType crestType)
		{
			SetDashAttack(crestType.ToString());
		}

		public void SetDashAttack(string sourceId)
		{
			DashAttacks.ApplyDashAttack(sourceId);
		}

		public void SetBindOutcome(VanillaCrestType crestType)
		{
			BindOutcome.ApplyBindOutcome(crestType);
		}

		public void SetBindOutcome(string outcomeId)
		{
			BindOutcome.ApplyBindOutcome(outcomeId);
		}

		public void SetBaseOverrideClips(IEnumerable<tk2dSpriteAnimationClip>? baseClips)
		{
			_context.SetBaseOverrideClips(baseClips);
		}

		internal static void InitializeAllOnHeroAwake()
		{
			foreach (CrestMovesetComposer composer in _composers)
			{
				composer.RunGuarded("hero awake", composer.InitializeOnHeroAwake);
			}
		}

		internal static void InitializeAllOnHeroStart(HeroController hc)
		{
			foreach (CrestMovesetComposer composer in _composers)
			{
				composer.RunGuarded("hero start", delegate
				{
					composer.BindOutcome.InitializeOnHeroStart(hc);
				});
			}
		}

		internal static void ApplyAttackTiming(HeroController hc, AttackDirection direction)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			foreach (CrestMovesetComposer composer in _composers)
			{
				if ((object)hc.crestConfig == composer.CrestData.Moveset.HeroConfig)
				{
					composer.RunGuarded("attack timing", delegate
					{
						//IL_0017: Unknown result type (might be due to invalid IL or missing references)
						composer.ApplyDirectionTiming(hc, direction);
					});
				}
			}
		}

		internal static void ApplyRageAttacks(HeroController hc)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			if (!hc.WarriorState.IsInRageMode)
			{
				return;
			}
			foreach (CrestMovesetComposer composer in _composers)
			{
				ConfigGroup configGroup = composer.CrestData.Moveset.ConfigGroup;
				ConfigGroup rageAttacks = composer._context.RageAttacks;
				if (rageAttacks != null && configGroup != null && hc.CurrentConfigGroup == configGroup)
				{
					hc.SetConfigGroup(configGroup, rageAttacks);
				}
			}
		}

		internal static bool HasWandererLuck(HeroController hc)
		{
			if (!hc.cState.isMaggoted && hc.playerData.silk >= 9)
			{
				return _composers.Exists((CrestMovesetComposer composer) => composer.CrestData.IsEquipped && composer.BindOutcome.ActiveOutcome == VanillaCrestType.Wanderer);
			}
			return false;
		}

		internal static bool IsVoidBinding(HeroController? hc)
		{
			if ((Object)(object)hc != (Object)null && hc.cState.isBinding)
			{
				return _composers.Exists((CrestMovesetComposer composer) => composer.BindOutcome.IsVoidActive && composer.CrestData.IsEquipped);
			}
			return false;
		}

		internal static bool TryStartWandererCombo(HeroController hc)
		{
			foreach (CrestMovesetComposer composer in _composers)
			{
				if (composer.DashAttacks.TryStartWandererCombo(hc))
				{
					return true;
				}
			}
			return false;
		}

		internal static void NotifyEnemyDamaged(HealthManager enemy, HitInstance hit)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			foreach (CrestMovesetComposer composer in _composers)
			{
				composer.RunGuarded("enemy hit", delegate
				{
					//IL_001c: Unknown result type (might be due to invalid IL or missing references)
					composer.BindOutcome.HandleEnemyDamaged(enemy, hit);
				});
			}
		}

		private void ApplyDirectionTiming(HeroController hc, AttackDirection direction)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			HeroConfigNeedleforge heroConfig = CrestData.Moveset.HeroConfig;
			HeroControllerConfig val = (((int)direction == 1) ? _context.FindSource(UpAttacks.ActiveUpAttack)?.FindConfigGroup(hc)?.Config : (((int)direction != 2) ? _context.FindSource(NeutralAttacks.ActiveNeutralAttack)?.FindConfigGroup(hc)?.Config : VanillaCrestCatalog.FindVanillaConfigGroup(hc, DownAttacks.ActiveDownAttack)?.Config));
			if ((Object)(object)heroConfig != (Object)null && (Object)(object)val != (Object)null)
			{
				CrestComposerContext.ApplyAttackTiming(heroConfig, val);
			}
		}

		private void InitializeOnHeroAwake()
		{
			this.OnMovesetInitialized?.Invoke();
			_context.BeginHeroAwake();
			NeutralAttacks.InitializeOnHeroAwake();
			UpAttacks.InitializeOnHeroAwake();
			DownAttacks.InitializeOnHeroAwake();
			DashAttacks.InitializeOnHeroAwake();
			BindOutcome.InitializeOnHeroAwake();
			ConfigGroup configGroup = CrestData.Moveset.ConfigGroup;
			if (configGroup != null)
			{
				configGroup.Setup();
			}
		}

		private void RunGuarded(string stage, Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				ManualLogSource? logger = _context.Logger;
				if (logger != null)
				{
					logger.LogError((object)$"[CrestComposition] Composing '{CrestData.name}' failed at {stage}: {arg}");
				}
			}
		}
	}
	public sealed class DashAttackComposer
	{
		private sealed class DashClones
		{
			public GameObject? Stab;

			public GameObject? StabAlt;

			public int Steps;

			public readonly List<GameObject> RouteObjects = new List<GameObject>();
		}

		private const string WandererComboEntryState = "To Wanderer Combo";

		private static readonly string[] _stopStates = new string[4] { "Regain Control Normal", "Regain Control To Idle", "Continue Sprint?", "Continue Sprint? 2" };

		private readonly CrestComposerContext _context;

		private readonly Dictionary<string, DashClones> _clonesBySource = new Dictionary<string, DashClones>(StringComparer.Ordinal);

		private readonly List<GameObject> _slotClones = new List<GameObject>();

		private string _activeDashAttack;

		private bool _wandererComboReady;

		public string ActiveDashAttack => _activeDashAttack;

		public bool LastSelfCheckPassed { get; private set; }

		private string WandererComboEvent => _context.CrestData.name + " WANDERER COMBO";

		internal DashAttackComposer(CrestComposerContext context, string initialDashAttack)
		{
			_context = context;
			_activeDashAttack = initialDashAttack;
		}

		internal void InitializeOnHeroAwake()
		{
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			HeroController instance = HeroController.instance;
			ConfigGroup configGroup = _context.CrestData.Moveset.ConfigGroup;
			HeroConfigNeedleforge heroConfig = _context.CrestData.Moveset.HeroConfig;
			if ((Object)(object)instance == (Object)null || configGroup == null || (Object)(object)configGroup.ActiveRoot == (Object)null || (Object)(object)heroConfig == (Object)null)
			{
				ManualLogSource? logger = _context.Logger;
				if (logger != null)
				{
					logger.LogError((object)("[CrestComposition] Cannot initialize dash clones for '" + _context.CrestData.name + "': HeroController, ConfigGroup, ActiveRoot, or HeroConfig is null."));
				}
				return;
			}
			_clonesBySource.Clear();
			_slotClones.Clear();
			_wandererComboReady = false;
			CrestComposerContext.DestroyDefaultAttack(configGroup.DashStab);
			CrestComposerContext.DestroyDefaultAttack(configGroup.DashStabAlt);
			configGroup.DashStab = null;
			configGroup.DashStabAlt = null;
			foreach (AttackSource source in _context.Sources)
			{
				CloneSourceAttacks(instance, source);
			}
			if (!_clonesBySource.ContainsKey(_activeDashAttack))
			{
				ManualLogSource? logger2 = _context.Logger;
				if (logger2 != null)
				{
					logger2.LogWarning((object)("[CrestComposition] Dash source '" + _activeDashAttack + "' is not available; using Hunter."));
				}
				_activeDashAttack = VanillaCrestType.Hunter.ToString();
			}
			ApplyDashAttack(_activeDashAttack);
			heroConfig.DashSlashFsmEdit = _context.GuardFsmEdit("dash", new FsmEdit(BuildDashSlashFsm));
		}

		public void ApplyDashAttack(string sourceId)
		{
			if (_clonesBySource.Count > 0 && !_clonesBySource.ContainsKey(sourceId))
			{
				ManualLogSource? logger = _context.Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("[CrestComposition] Dash source '" + sourceId + "' is not available; keeping '" + _activeDashAttack + "'."));
				}
				return;
			}
			_activeDashAttack = sourceId;
			HeroController instance = HeroController.instance;
			ConfigGroup configGroup = _context.CrestData.Moveset.ConfigGroup;
			HeroConfigNeedleforge heroConfig = _context.CrestData.Moveset.HeroConfig;
			if ((Object)(object)instance == (Object)null || configGroup == null || (Object)(object)heroConfig == (Object)null || !_clonesBySource.TryGetValue(sourceId, out DashClones value))
			{
				return;
			}
			AttackSource attackSource = _context.FindSource(sourceId);
			if (attackSource == null)
			{
				return;
			}
			configGroup.DashStab = value.Stab;
			configGroup.DashStabAlt = value.StabAlt;
			List<GameObject> list = new List<GameObject> { value.Stab, value.StabAlt };
			list.AddRange(value.RouteObjects);
			_context.ActivateSelection(_slotClones, list.ToArray());
			HeroControllerConfig val = attackSource.FindConfigGroup(instance)?.Config;
			if ((Object)(object)val != (Object)null)
			{
				heroConfig.SetDashStabFields((float?)val.DashStabTime, (float?)val.DashStabSpeed, (float?)val.DashStabBounceJumpSpeed, (bool?)val.ForceShortDashStabBounce);
			}
			((HeroControllerConfig)heroConfig).dashStabSteps = value.Steps;
			_context.SetSlotClips(AttackSlot.Dash, CrestComposerContext.CollectClips(instance, attackSource, GetRoute(attackSource).ClipFilter));
			if (((MonoBehaviour)instance).didStart)
			{
				_context.RefreshConfigGroup(instance);
				ManualLogSource? logger2 = _context.Logger;
				if (logger2 != null)
				{
					logger2.LogInfo((object)("[CrestComposition] Applied dash attack '" + sourceId + "' to '" + _context.CrestData.name + "'."));
				}
			}
			else
			{
				_context.RebuildAnimations();
			}
		}

		internal bool TryStartWandererCombo(HeroController hc)
		{
			if (!_wandererComboReady || !string.Equals(_activeDashAttack, VanillaCrestType.Wanderer.ToString(), StringComparison.Ordinal) || hc.wandererDashComboWindowTimer <= 0f || !_context.CrestData.IsEquipped)
			{
				return false;
			}
			hc.sprintFSM.SendEvent(WandererComboEvent);
			return true;
		}

		private void CloneSourceAttacks(HeroController hc, AttackSource source)
		{
			if (!source.HasPlayableDashAttack)
			{
				ManualLogSource? logger = _context.Logger;
				if (logger != null)
				{
					logger.LogInfo((object)("[CrestComposition] '" + source.Id + "' has no playable dash attack to borrow."));
				}
				return;
			}
			ConfigGroup val = source.FindConfigGroup(hc);
			if (val == null)
			{
				ManualLogSource? logger2 = _context.Logger;
				if (logger2 != null)
				{
					logger2.LogWarning((object)("[CrestComposition] Could not find a ConfigGroup for dash source '" + source.Id + "'."));
				}
				return;
			}
			DashClones dashClones = new DashClones
			{
				Stab = CloneSlot(hc, source, val.DashStab, "DashStab"),
				StabAlt = CloneSlot(hc, source, val.DashStabAlt, "DashStabAlt")
			};
			dashClones.Steps = (source.IsVanilla ? val.Config.DashStabSteps : Mathf.Max(1, (!((Object)(object)val.DashStab != (Object)null)) ? 1 : val.DashStab.transform.childCount));
			foreach (FsmAttackObjectBinding binding in GetRoute(source).Bindings)
			{
				GameObject val2 = _context.CloneBinding(hc, source.Id, binding);
				if ((Object)(object)val2 != (Object)null)
				{
					dashClones.RouteObjects.Add(val2);
					AddSlotClone(val2);
				}
			}
			_clonesBySource[source.Id] = dashClones;
		}

		private GameObject? CloneSlot(HeroController hc, AttackSource source, GameObject? original, string slotName)
		{
			if ((Object)(object)original == (Object)null)
			{
				return null;
			}
			GameObject val = _context.CloneOnce(hc, original, source.Id + "_" + slotName);
			AddSlotClone(val);
			return val;
		}

		private void AddSlotClone(GameObject clone)
		{
			if (!_slotClones.Contains(clone))
			{
				_slotClones.Add(clone);
			}
		}

		private void BuildDashSlashFsm(PlayMakerFSM fsm, FsmState startState, out FsmState[] endStates)
		{
			endStates = (FsmState[])(object)new FsmState[1] { startState };
			HeroController instance = HeroController.instance;
			string name = _context.CrestData.name;
			List<FsmState> list = new List<FsmState>();
			foreach (AttackSource source in _context.Sources)
			{
				if (!_clonesBySource.TryGetValue(source.Id, out DashClones value))
				{
					continue;
				}
				DashAttackRoute route = GetRoute(source);
				Dictionary<string, FsmGameObject> dictionary = _context.BuildVariableRemap(fsm, instance, source.Id, route.Bindings);
				dictionary["Dash Stab"] = _context.CreateBranchVariable(fsm, source.Id, "Dash Stab", value.Stab);
				dictionary["Dash Stab Alt"] = _context.CreateBranchVariable(fsm, source.Id, "Dash Stab Alt", value.StabAlt);
				CopiedFsmBranch copiedFsmBranch = FsmBranchCopier.CopyBranch(fsm, route.EntryState, name + "_" + source.Id, (IReadOnlyCollection<string>)(object)_stopStates, dictionary, _context.CrestData.ToolCrest, (ToolCrest crest) => IsSourceCrest(source, crest));
				if (copiedFsmBranch == null)
				{
					ManualLogSource? logger = _context.Logger;
					if (logger != null)
					{
						logger.LogError((object)("[CrestComposition] Failed to copy Sprint branch '" + route.EntryState + "' for '" + source.Id + "'."));
					}
				}
				else
				{
					if (!source.IsVanilla)
					{
						AddNeedleforgeStepLookups(fsm, copiedFsmBranch, value);
					}
					list.AddRange(copiedFsmBranch.CopiedStates);
					FsmUtil.AddTransition(startState, GetDispatchEventName(source.Id), copiedFsmBranch.EntryState.Name);
					if (source.VanillaType == VanillaCrestType.Wanderer)
					{
						AddWandererCombo(fsm, source, dictionary, list);
					}
				}
			}
			FsmInt attackStep = FsmUtil.GetIntVariable(fsm, "Attack Step");
			FsmInt attackSteps = FsmUtil.GetIntVariable(fsm, "Attack Steps");
			FsmFloat attackSpeed = FsmUtil.GetFloatVariable(fsm, "Attack Speed");
			FsmFloat attackTime = FsmUtil.GetFloatVariable(fsm, "Attack Time");
			HeroConfigNeedleforge heroConfig = _context.CrestData.Moveset.HeroConfig;
			FsmUtil.AddMethod(startState, (Action)delegate
			{
				attackStep.Value = 1;
				attackSteps.Value = ((HeroControllerConfig)heroConfig).dashStabSteps;
				attackSpeed.Value = ((HeroControllerConfig)heroConfig).DashStabSpeed;
				attackTime.Value = ((HeroControllerConfig)heroConfig).DashStabTime;
				fsm.Fsm.Event(GetDispatchEventName(_activeDashAttack));
			}, false);
			LastSelfCheckPassed = FsmBranchSelfCheck.Verify(name, list, _context.AllClones, _context.GetSourceAttackRoots(instance), _context.CrestData.ToolCrest, _context.Logger);
		}

		private void AddWandererCombo(PlayMakerFSM fsm, AttackSource source, Dictionary<string, FsmGameObject> variableRemap, List<FsmState> allCopiedStates)
		{
			CopiedFsmBranch copiedFsmBranch = FsmBranchCopier.CopyBranch(fsm, "To Wanderer Combo", _context.CrestData.name + "_" + source.Id + "_Combo", (IReadOnlyCollection<string>)(object)_stopStates, variableRemap, _context.CrestData.ToolCrest, (ToolCrest crest) => IsSourceCrest(source, crest));
			if (copiedFsmBranch == null)
			{
				ManualLogSource? logger = _context.Logger;
				if (logger != null)
				{
					logger.LogError((object)"[CrestComposition] Failed to copy Sprint branch 'To Wanderer Combo'.");
				}
			}
			else
			{
				allCopiedStates.AddRange(copiedFsmBranch.CopiedStates);
				FsmUtil.AddGlobalTransition(fsm, WandererComboEvent, copiedFsmBranch.EntryState.Name);
				_wandererComboReady = true;
			}
		}

		private static void AddNeedleforgeStepLookups(PlayMakerFSM fsm, CopiedFsmBranch branch, DashClones clones)
		{
			FsmInt attackStep = FsmUtil.GetIntVariable(fsm, "Attack Step");
			FsmString attackChildName = FsmUtil.GetStringVariable(fsm, "Attack Child Name");
			FsmGameObject currentStab = FsmUtil.GetGameObjectVariable(fsm, "Dash Stab Crt");
			FsmObject clip = fsm.FsmVariables.FindFsmObject("Clip");
			if (branch.StateMap.TryGetValue("Set Attack Multiple", out FsmState value))
			{
				FsmUtil.InsertMethod(value, (Action)delegate
				{
					Transform val = (((Object)(object)clones.Stab != (Object)null) ? clones.Stab.transform : null);
					int num = attackStep.Value - 1;
					if ((Object)(object)val != (Object)null && num >= 0 && num < val.childCount)
					{
						attackChildName.Value = ((Object)val.GetChild(num)).name;
					}
				}, IndexOfAction<FindChild>(value), false);
			}
			if (!branch.StateMap.TryGetValue("Attack Dash Start", out FsmState value2))
			{
				return;
			}
			FsmUtil.InsertMethod(value2, (Action)delegate
			{
				AudioSource val = (((Object)(object)currentStab.Value != (Object)null) ? currentStab.Value.GetComponent<AudioSource>() : null);
				if ((Object)(object)val != (Object)null && (Object)(object)val.clip != (Object)null)
				{
					clip.Value = (Object)(object)val.clip;
				}
			}, IndexOfAction<PlayAudioEvent>(value2), false);
		}

		private static int IndexOfAction<TAction>(FsmState state) where TAction : FsmStateAction
		{
			int num = Array.FindIndex(state.Actions, (FsmStateAction action) => action is TAction);
			if (num < 0)
			{
				return state.Actions.Length;
			}
			return num;
		}

		private static bool IsSourceCrest(AttackSource source, ToolCrest crest)
		{
			if (!source.VanillaType.HasValue)
			{
				return false;
			}
			foreach (string alternateToolCrestName in VanillaCrestCatalog.Get(source.VanillaType.Value).AlternateToolCrestNames)
			{
				if (string.Equals(crest.name, alternateToolCrestName, StringComparison.Ordinal))
				{
					return true;
				}
			}
			return false;
		}

		private static DashAttackRoute GetRoute(AttackSource source)
		{
			if (!source.VanillaType.HasValue)
			{
				return VanillaCrestCatalog.CrossModDashAttackRoute;
			}
			return VanillaCrestCatalog.GetDashAttackRoute(source.VanillaType.Value);
		}

		private static string GetDispatchEventName(string sourceId)
		{
			return "TO_" + sourceId;
		}
	}
	public sealed class DownAttackComposer
	{
		private static readonly string[] _stopStates = new string[2] { "End", "Idle" };

		private static readonly string[] _downAttackClipKeywords = new string[8] { "down", "spike", "spinball", "drill", "grind", "pogo", "bounce", "rebound" };

		private readonly CrestComposerContext _context;

		private readonly CrestData _crestData;

		private readonly ManualLogSource? _logger;

		private readonly Dictionary<VanillaCrestType, Dictionary<string, GameObject>> _clonedObjectsByCrest = new Dictionary<VanillaCrestType, Dictionary<string, GameObject>>();

		private readonly Dictionary<VanillaCrestType, GameObject?> _primaryDownSlashByCrest = new Dictionary<VanillaCrestType, GameObject>();

		private readonly Dictionary<VanillaCrestType, GameObject?> _altDownSlashByCrest = new Dictionary<VanillaCrestType, GameObject>();

		private readonly List<GameObject> _allClonedObjects = new List<GameObject>();

		private VanillaCrestType _activeDownAttack;

		private bool _fsmInitialized;

		public VanillaCrestType ActiveDownAttack => _activeDownAttack;

		public bool LastSelfCheckPassed { get; private set; }

		internal DownAttackComposer(CrestComposerContext context, VanillaCrestType initialDownAttack)
		{
			_context = context;
			_crestData = context.CrestData;
			_logger = context.Logger;
			_activeDownAttack = initialDownAttack;
		}

		internal void InitializeOnHeroAwake()
		{
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Expected O, but got Unknown
			HeroController instance = HeroController.instance;
			ConfigGroup configGroup = _crestData.Moveset.ConfigGroup;
			HeroConfigNeedleforge heroConfig = _crestData.Moveset.HeroConfig;
			if ((Object)(object)instance == (Object)null || configGroup == null || (Object)(object)configGroup.ActiveRoot == (Object)null || (Object)(object)heroConfig == (Object)null)
			{
				ManualLogSource? logger = _logger;
				if (logger != null)
				{
					logger.LogError((object)("[CrestComposition] Cannot initialize down-attack clones for '" + _crestData.name + "': HeroController, ConfigGroup, ActiveRoot, or HeroConfig is null."));
				}
				return;
			}
			_fsmInitialized = false;
			_clonedObjectsByCrest.Clear();
			_primaryDownSlashByCrest.Clear();
			_altDownSlashByCrest.Clear();
			_allClonedObjects.Clear();
			CrestComposerContext.DestroyDefaultAttack(configGroup.DownSlashObject);
			CrestComposerContext.DestroyDefaultAttack(configGroup.AltDownSlashObject);
			configGroup.DownSlashObject = null;
			configGroup.AltDownSlashObject = null;
			configGroup.Downspike = null;
			configGroup.AltDownspike = null;
			configGroup.DownSlash = null;
			configGroup.AltDownSlash = null;
			configGroup.DownSlashDamager = null;
			configGroup.AltDownSlashDamager = null;
			foreach (VanillaCrestInfo value3 in VanillaCrestCatalog.All.Values)
			{
				CloneCrestDownAttackChildren(instance, configGroup.ActiveRoot.transform, value3);
			}
			RebindShamanSlashEffect();
			if (_primaryDownSlashByCrest.TryGetValue(_activeDownAttack, out GameObject value))
			{
				configGroup.DownSlashObject = value;
			}
			if (_altDownSlashByCrest.TryGetValue(_activeDownAttack, out GameObject value2))
			{
				configGroup.AltDownSlashObject = value2;
			}
			heroConfig.SetCustomDownslash(GetCustomDownSlashEventName(), _context.GuardFsmEdit("down", new FsmEdit(BuildDownSlashFsm)));
		}

		public void ApplyDownAttack(VanillaCrestType crestType)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Invalid comparison between Unknown and I4
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			_activeDownAttack = crestType;
			HeroController instance = HeroController.instance;
			ConfigGroup configGroup = _crestData.Moveset.ConfigGroup;
			HeroConfigNeedleforge heroConfig = _crestData.Moveset.HeroConfig;
			if (!_fsmInitialized || (Object)(object)instance == (Object)null || configGroup == null || (Object)(object)heroConfig == (Object)null)
			{
				return;
			}
			VanillaCrestInfo vanillaCrestInfo = VanillaCrestCatalog.Get(crestType);
			ConfigGroup val = VanillaCrestCatalog.FindVanillaConfigGroup(instance, crestType);
			DownSlashTypes downSlashType = vanillaCrestInfo.DownSlashType;
			if ((int)downSlashType != 0)
			{
				if ((int)downSlashType == 1)
				{
					((HeroControllerConfig)heroConfig).downSlashType = (DownSlashTypes)1;
					((HeroControllerConfig)heroConfig).downSlashEvent = string.Empty;
				}
				else
				{
					((HeroControllerConfig)heroConfig).downSlashType = (DownSlashTypes)2;
					((HeroControllerConfig)heroConfig).downSlashEvent = GetCustomDownSlashEventName();
				}
			}
			else
			{
				((HeroControllerConfig)heroConfig).downSlashType = (DownSlashTypes)0;
				((HeroControllerConfig)heroConfig).downSlashEvent = string.Empty;
				ApplyHunterDownspikeParameters(heroConfig, val?.Config);
			}
			_primaryDownSlashByCrest.TryGetValue(crestType, out GameObject value);
			_altDownSlashByCrest.TryGetValue(crestType, out GameObject value2);
			configGroup.DownSlashObject = value;
			configGroup.AltDownSlashObject = value2;
			configGroup.Downspike = null;
			configGroup.AltDownspike = null;
			configGroup.DownSlash = null;
			configGroup.AltDownSlash = null;
			configGroup.DownSlashDamager = null;
			configGroup.AltDownSlashDamager = null;
			_context.SetSlotClips(AttackSlot.Down, CollectDownAttackClips(instance, crestType));
			_context.RefreshConfigGroup(instance);
			ManualLogSource? logger = _logger;
			if (logger != null)
			{
				logger.LogInfo((object)$"[CrestComposition] Applied down attack '{crestType}' ({vanillaCrestInfo.DownSlashType}) to '{_crestData.name}'.");
			}
		}

		private void CloneCrestDownAttackChildren(HeroController hc, Transform customActiveRoot, VanillaCrestInfo info)
		{
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			ConfigGroup val = VanillaCrestCatalog.FindVanillaConfigGroup(hc, info.CrestType);
			if (val == null || (Object)(object)val.ActiveRoot == (Object)null)
			{
				ManualLogSource? logger = _logger;
				if (logger != null)
				{
					logger.LogWarning((object)($"[CrestComposition] Could not find vanilla ConfigGroup for '{info.CrestType}' " + "(expected ActiveRoot '" + info.ActiveRootName + "')."));
				}
				return;
			}
			Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>(StringComparer.Ordinal);
			_clonedObjectsByCrest[info.CrestType] = dictionary;
			_primaryDownSlashByCrest[info.CrestType] = null;
			_altDownSlashByCrest[info.CrestType] = null;
			foreach (DownAttackChildBinding downAttackChild in info.DownAttackChildren)
			{
				Transform val2 = val.ActiveRoot.transform.Find(downAttackChild.ChildName);
				if ((Object)(object)val2 == (Object)null)
				{
					ManualLogSource? logger2 = _logger;
					if (logger2 != null)
					{
						logger2.LogWarning((object)("[CrestComposition] Child '" + downAttackChild.ChildName + "' not found under vanilla root '" + ((Object)val.ActiveRoot).name + "'."));
					}
					continue;
				}
				GameObject val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject, customActiveRoot);
				((Object)val3).name = $"{info.CrestType}_{downAttackChild.ChildName}";
				val3.transform.SetLocalPositionAndRotation(val2.localPosition, val2.localRotation);
				val3.transform.localScale = val2.localScale;
				val3.SetActive(((Component)val2).gameObject.activeSelf);
				CrestComposerContext.RewireChildFsmsToHero(val3, ((Component)hc).gameObject);
				if (downAttackChild.IsPrimaryDownSlash)
				{
					EnsureHeroDownAttackComponent(val3);
					_primaryDownSlashByCrest[info.CrestType] = val3;
				}
				if (downAttackChild.IsAltDownSlash)
				{
					EnsureHeroDownAttackComponent(val3);
					_altDownSlashByCrest[info.CrestType] = val3;
				}
				dictionary[downAttackChild.ChildName] = val3;
				_allClonedObjects.Add(val3);
			}
		}

		private void RebindShamanSlashEffect()
		{
			if (!(CrestComposerContext.ActivateOnSlashField == null) && _clonedObjectsByCrest.TryGetValue(VanillaCrestType.Spell, out Dictionary<string, GameObject> value) && value.TryGetValue("DownSlash", out var value2) && value.TryGetValue("Shaman_blade_cast_effect DownSlash", out var value3))
			{
				NailAttackBase component = value2.GetComponent<NailAttackBase>();
				if (!((Object)(object)component == (Object)null))
				{
					CrestComposerContext.ActivateOnSlashField.SetValue(component, new GameObject[1] { value3 });
				}
			}
		}

		private void BuildDownSlashFsm(PlayMakerFSM fsm, FsmState startState, out FsmState[] endStates)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Invalid comparison between Unknown and I4
			endStates = Array.Empty<FsmState>();
			List<FsmState> list = new List<FsmState>();
			foreach (VanillaCrestInfo value3 in VanillaCrestCatalog.All.Values)
			{
				if ((int)value3.DownSlashType != 2 || string.IsNullOrEmpty(value3.CrestAttacksEntryState) || !_clonedObjectsByCrest.TryGetValue(value3.CrestType, out Dictionary<string, GameObject> value))
				{
					continue;
				}
				Dictionary<string, FsmGameObject> dictionary = new Dictionary<string, FsmGameObject>(StringComparer.Ordinal);
				foreach (DownAttackChildBinding downAttackChild in value3.DownAttackChildren)
				{
					if (!string.IsNullOrEmpty(downAttackChild.FsmVariableName) && value.TryGetValue(downAttackChild.ChildName, out var value2))
					{
						string text = $"{_crestData.name}_{value3.CrestType}_{downAttackChild.FsmVariableName}";
						FsmGameObject gameObjectVariable = FsmUtil.GetGameObjectVariable(fsm, text);
						gameObjectVariable.Value = value2;
						dictionary[downAttackChild.FsmVariableName] = gameObjectVariable;
					}
				}
				string statePrefix = $"{_crestData.name}_{value3.CrestType}";
				CopiedFsmBranch copiedFsmBranch = FsmBranchCopier.CopyBranch(fsm, value3.CrestAttacksEntryState, statePrefix, (IReadOnlyCollection<string>)(object)_stopStates, dictionary, _crestData.ToolCrest);
				if (copiedFsmBranch == null)
				{
					ManualLogSource? logger = _logger;
					if (logger != null)
					{
						logger.LogError((object)$"[CrestComposition] Failed to copy Crest Attacks branch '{value3.CrestAttacksEntryState}' for '{value3.CrestType}'.");
					}
				}
				else
				{
					list.AddRange(copiedFsmBranch.CopiedStates);
					string dispatchEventName = GetDispatchEventName(value3.CrestType);
					FsmUtil.AddTransition(startState, dispatchEventName, copiedFsmBranch.EntryState.Name);
				}
			}
			FsmUtil.AddTransition(startState, "FINISHED", "End");
			FsmUtil.AddMethod(startState, (Action)delegate
			{
				string dispatchEventName2 = GetDispatchEventName(_activeDownAttack);
				fsm.Fsm.Event(dispatchEventName2);
			}, false);
			RegisterWitchCancelCleanup(fsm);
			HeroController instance = HeroController.instance;
			List<Transform> vanillaActiveRoots = (List<Transform>)(((Object)(object)instance != (Object)null) ? ((IList)VanillaCrestCatalog.GetAllVanillaActiveRoots(instance)) : ((IList)new List<Transform>()));
			LastSelfCheckPassed = FsmBranchSelfCheck.Verify(_crestData.name, list, _allClonedObjects, vanillaActiveRoots, _crestData.ToolCrest, _logger);
			_fsmInitialized = true;
			ApplyDownAttack(_activeDownAttack);
		}

		private void RegisterWitchCancelCleanup(PlayMakerFSM fsm)
		{
			if (!_clonedObjectsByCrest.TryGetValue(VanillaCrestType.Witch, out Dictionary<string, GameObject> value) || !value.TryGetValue("Followup Slash", out var clonedFollowup) || (Object)(object)clonedFollowup == (Object)null)
			{
				return;
			}
			FsmState state = FsmUtil.GetState(fsm, "Cancel");
			if (state == null)
			{
				return;
			}
			FsmUtil.AddMethod(state, (Action)delegate
			{
				if ((Object)(object)clonedFollowup != (Object)null && clonedFollowup.activeSelf)
				{
					clonedFollowup.SetActive(false);
				}
			}, false);
		}

		private static void ApplyHunterDownspikeParameters(HeroConfigNeedleforge targetConfig, HeroControllerConfig? hunterConfig)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)hunterConfig == (Object)null))
			{
				float downspikeSpeed = hunterConfig.downspikeSpeed;
				targetConfig.SetDownspikeFields((float?)hunterConfig.downspikeAnticTime, (float?)hunterConfig.downspikeTime, (float?)hunterConfig.downspikeRecoveryTime, (bool?)hunterConfig.downspikeThrusts, (float?)downspikeSpeed, (Vector2?)new Vector2(0f - downspikeSpeed, 0f - downspikeSpeed), (Vector2?)Vector2.zero, (bool?)hunterConfig.downspikeBurstEffect);
			}
		}

		private static List<tk2dSpriteAnimationClip> CollectDownAttackClips(HeroController hc, VanillaCrestType crestType)
		{
			HashSet<string> explicitClipNames = new HashSet<string>(VanillaCrestCatalog.Get(crestType).DownAttackAnimationClips, StringComparer.OrdinalIgnoreCase);
			return CrestComposerContext.CollectClips(hc, new AttackSource(crestType), (string clipName) => explicitClipNames.Contains(clipName) || MatchesAnyKeyword(clipName, _downAttackClipKeywords));
		}

		private static bool MatchesAnyKeyword(string clipName, string[] keywords)
		{
			foreach (string value in keywords)
			{
				if (clipName.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
			return false;
		}

		private static void EnsureHeroDownAttackComponent(GameObject attackObject)
		{
			if (!((Object)(object)attackObject == (Object)null) && (Object)(object)attackObject.GetComponent<NailAttackBase>() != (Object)null && (Object)(object)attackObject.GetComponent<HeroDownAttack>() == (Object)null)
			{
				attackObject.AddComponent<HeroDownAttack>();
			}
		}

		private string GetCustomDownSlashEventName()
		{
			return _crestData.name + " DOWNSLASH";
		}

		private static string GetDispatchEventName(VanillaCrestType crestType)
		{
			return $"TO_{crestType}";
		}
	}
	public sealed class CopiedFsmBranch
	{
		public FsmState EntryState { get; }

		public IReadOnlyList<FsmState> CopiedStates { get; }

		public IReadOnlyDictionary<string, FsmState> StateMap { get; }

		public CopiedFsmBranch(FsmState entryState, List<FsmState> copiedStates, Dictionary<string, FsmState> stateMap)
		{
			EntryState = entryState;
			CopiedStates = copiedStates;
			StateMap = stateMap;
		}
	}
	public static class FsmBranchCopier
	{
		private const BindingFlags InstanceFieldFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		public static CopiedFsmBranch? CopyBranch(PlayMakerFSM fsm, string entryStateName, string statePrefix, IReadOnlyCollection<string> stopStates, IReadOnlyDictionary<string, FsmGameObject> variableRemap, ToolCrest? customToolCrest, Predicate<ToolCrest>? isSourceCrest = null)
		{
			if ((Object)(object)fsm == (Object)null || string.IsNullOrEmpty(entryStateName))
			{
				return null;
			}
			if (fsm.Fsm != null && !fsm.Fsm.preprocessed)
			{
				fsm.Preprocess();
			}
			if (FsmUtil.GetState(fsm, entryStateName) == null)
			{
				return null;
			}
			List<string> list = DiscoverReachableStateNames(fsm, entryStateName, stopStates);
			Dictionary<string, FsmState> dictionary = new Dictionary<string, FsmState>(StringComparer.Ordinal);
			List<FsmState> list2 = new List<FsmState>(list.Count);
			foreach (string item2 in list)
			{
				string text = statePrefix + " " + item2;
				FsmState item = (dictionary[item2] = FsmUtil.GetState(fsm, text) ?? FsmUtil.CopyState(fsm, item2, text));
				list2.Add(item);
			}
			foreach (FsmState item3 in list2)
			{
				RemapStateTransitions(fsm, item3, dictionary);
				RemoveCopiedLambdas(item3);
				RebindStateActions(item3, variableRemap, customToolCrest, isSourceCrest);
			}
			return new CopiedFsmBranch(dictionary[entryStateName], list2, dictionary);
		}

		private static List<string> DiscoverReachableStateNames(PlayMakerFSM fsm, string entryStateName, IReadOnlyCollection<string> stopStates)
		{
			HashSet<string> hashSet = new HashSet<string>(stopStates, StringComparer.Ordinal);
			HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
			Queue<string> queue = new Queue<string>();
			List<string> list = new List<string>();
			hashSet2.Add(entryStateName);
			queue.Enqueue(entryStateName);
			while (queue.Count > 0)
			{
				string text = queue.Dequeue();
				FsmState state = FsmUtil.GetState(fsm, text);
				if (state == null)
				{
					continue;
				}
				list.Add(text);
				if (state.Transitions == null)
				{
					continue;
				}
				FsmTransition[] transitions = state.Transitions;
				foreach (FsmTransition val in transitions)
				{
					if (val != null && !string.IsNullOrEmpty(val.ToState))
					{
						string toState = val.ToState;
						if (!hashSet.Contains(toState) && hashSet2.Add(toState))
						{
							queue.Enqueue(toState);
						}
					}
				}
			}
			return list;
		}

		private static void RemapStateTransitions(PlayMakerFSM fsm, FsmState copiedState, IReadOnlyDictionary<string, FsmState> copiedByOriginalName)
		{
			if (copiedState.Transitions == null)
			{
				return;
			}
			FsmTransition[] transitions = copiedState.Transitions;
			foreach (FsmTransition val in transitions)
			{
				if (val == null || string.IsNullOrEmpty(val.ToState))
				{
					continue;
				}
				if (copiedByOriginalName.TryGetValue(val.ToState, out FsmState value))
				{
					val.ToState = value.Name;
					val.ToFsmState = value;
					continue;
				}
				FsmState state = FsmUtil.GetState(fsm, val.ToState);
				if (state != null)
				{
					val.ToFsmState = state;
				}
			}
		}

		private static void RemoveCopiedLambdas(FsmState copiedState)
		{
			FsmStateAction[] actions = copiedState.Actions;
			if (actions != null && Array.Exists(actions, (FsmStateAction action) => action is LambdaAction))
			{
				copiedState.Actions = Array.FindAll(actions, (FsmStateAction action) => !(action is LambdaAction));
				copiedState.SaveActions();
			}
		}

		private static void RebindStateActions(FsmState copiedState, IReadOnlyDictionary<string, FsmGameObject> variableRemap, ToolCrest? customToolCrest, Predicate<ToolCrest>? isSourceCrest)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			if (copiedState.Actions == null)
			{
				return;
			}
			FsmStateAction[] actions = copiedState.Actions;
			foreach (FsmStateAction val in actions)
			{
				if (val == null)
				{
					continue;
				}
				CheckIfCrestEquipped val2 = (CheckIfCrestEquipped)(object)((val is CheckIfCrestEquipped) ? val : null);
				if (val2 != null && (Object)(object)customToolCrest != (Object)null)
				{
					int num;
					if (isSourceCrest != null)
					{
						FsmObject crest = val2.Crest;
						Object obj = ((crest != null) ? crest.Value : null);
						ToolCrest val3 = (ToolCrest)(object)((obj is ToolCrest) ? obj : null);
						num = ((val3 != null && isSourceCrest(val3)) ? 1 : 0);
					}
					else
					{
						num = 1;
					}
					bool flag = (byte)num != 0;
					val2.Crest = new FsmObject
					{
						Value = (Object)(object)(flag ? customToolCrest : null)
					};
				}
				RebindObjectFields(val, variableRemap);
			}
		}

		private static void RebindObjectFields(object target, IReadOnlyDictionary<string, FsmGameObject> variableRemap)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Invalid comparison between Unknown and I4
			//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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			Type type = target.GetType();
			while (type != null && type != typeof(object) && type != typeof(FsmStateAction))
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					object value = fieldInfo.GetValue(target);
					if (value == null)
					{
						continue;
					}
					FsmGameObject val = (FsmGameObject)((value is FsmGameObject) ? value : null);
					if (val != null)
					{
						if (!string.IsNullOrEmpty(((NamedVariable)val).Name) && variableRemap.TryGetValue(((NamedVariable)val).Name, out FsmGameObject value2))
						{
							fieldInfo.SetValue(target, value2);
						}
						continue;
					}
					FsmOwnerDefault val2 = (FsmOwnerDefault)((value is FsmOwnerDefault) ? value : null);
					if (val2 != null)
					{
						if ((int)val2.OwnerOption == 1 && val2.GameObject != null && !string.IsNullOrEmpty(((NamedVariable)val2.GameObject).Name) && variableRemap.TryGetValue(((NamedVariable)val2.GameObject).Name, out FsmGameObject value3))
						{
							FsmOwnerDefault value4 = new FsmOwnerDefault
							{
								OwnerOption = (OwnerDefaultOption)1,
								GameObject = value3
							};
							fieldInfo.SetValue(target, value4);
						}
					}
					else
					{
						if (!(value is FsmGameObject[] array))
						{
							continue;
						}
						for (int j = 0; j < array.Length; j++)
						{
							FsmGameObject val3 = array[j];
							if (val3 != null && !string.IsNullOrEmpty(((NamedVariable)val3).Name) && variableRemap.TryGetValue(((NamedVariable)val3).Name, out FsmGameObject value5))
							{
								array[j] = value5;
							}
						}
					}
				}
				type = type.BaseType;
			}
		}
	}
	public static class FsmBranchSelfCheck
	{
		private const BindingFlags InstanceFieldFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly FieldInfo? _activateOnSlashField = CrestComposerContext.ActivateOnSlashField;

		public static bool Verify(string crestName, IReadOnlyList<FsmState> copiedStates, IReadOnlyList<GameObject> clonedAttackObjects, IReadOnlyList<Transform> vanillaActiveRoots, ToolCrest? customToolCrest, ManualLogSource? logger)
		{
			List<string> list = new List<string>();
			HashSet<string> forbiddenVarSet = new HashSet<string>(VanillaCrestCatalog.AllVanillaCrestAttackVariables, StringComparer.Ordinal);
			foreach (FsmState copiedState in copiedStates)
			{
				if (copiedState == null || copiedState.Actions == null)
				{
					continue;
				}
				for (int i = 0; i < copiedState.Actions.Length; i++)
				{
					FsmStateAction val = copiedState.Actions[i];
					if (val != null && val.Enabled)
					{
						AuditAction(copiedState.Name, i, val, forbiddenVarSet, vanillaActiveRoots, customToolCrest, list);
					}
				}
			}
			foreach (GameObject clonedAttackObject in clonedAttackObjects)
			{
				if (!((Object)(object)clonedAttackObject == (Object)null))
				{
					AuditClonedAttackObject(clonedAttackObject, vanillaActiveRoots, list);
				}
			}
			if (list.Count == 0)
			{
				if (logger != null)
				{
					logger.LogInfo((object)("[CrestComposition] Self-check passed for '" + crestName + "': " + $"{copiedStates.Count} copied FSM states and {clonedAttackObjects.Count} " + "cloned attack objects verified with 0 vanilla references."));
				}
				return true;
			}
			if (logger != null)
			{
				logger.LogError((object)$"[CrestComposition] Self-check FAILED for '{crestName}' with {list.Count} violation(s):");
			}
			foreach (string item in list)
			{
				if (logger != null)
				{
					logger.LogError((object)("  - " + item));
				}
			}
			return false;
		}

		private static void AuditAction(string stateName, int actionIndex, FsmStateAction action, HashSet<string> forbiddenVarSet, IReadOnlyList<Transform> vanillaActiveRoots, ToolCrest? customToolCrest, List<string> violations)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Invalid comparison between Unknown and I4
			Type type = ((object)action).GetType();
			string text = $"State '{stateName}' action[{actionIndex}] ({type.Name})";
			CheckIfCrestEquipped val = (CheckIfCrestEquipped)(object)((action is CheckIfCrestEquipped) ? action : null);
			if (val != null)
			{
				FsmObject crest = val.Crest;
				Object obj = ((crest != null) ? crest.Value : null);
				ToolCrest val2 = (ToolCrest)(object)((obj is ToolCrest) ? obj : null);
				if ((Object)(object)val2 != (Object)null && val2 != customToolCrest)
				{
					violations.Add(text + " checks vanilla ToolCrest '" + val2.name + "' instead of '" + ((customToolCrest != null) ? customToolCrest.name : null) + "'.");
				}
			}
			Type type2 = type;
			while (type2 != null && type2 != typeof(object) && type2 != typeof(FsmStateAction))
			{
				FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					object value = fieldInfo.GetValue(action);
					if (value == null)
					{
						continue;
					}
					FsmGameObject val3 = (FsmGameObject)((value is FsmGameObject) ? value : null);
					if (val3 != null)
					{
						AuditFsmGameObject(text, fieldInfo.Name, val3, forbiddenVarSet, vanillaActiveRoots, violations);
						continue;
					}
					FsmOwnerDefault val4 = (FsmOwnerDefault)((value is FsmOwnerDefault) ? value : null);
					if (val4 != null && (int)val4.OwnerOption == 1 && val4.GameObject != null)
					{
						AuditFsmGameObject(text, fieldInfo.Name + ".GameObject", val4.GameObject, forbiddenVarSet, vanillaActiveRoots, violations);
						continue;
					}
					GameObject val5 = (GameObject)((value is GameObject) ? value : null);
					if (val5 != null)
					{
						if ((Object)(object)val5 != (Object)null && IsUnderAnyVanillaRoot(val5.transform, vanillaActiveRoots, out string matchedRootName))
						{
							violations.Add(text + " field '" + fieldInfo.Name + "' points directly to GameObject '" + ((Object)val5).name + "' under vanilla root '" + matchedRootName + "'.");
						}
						continue;
					}
					Component val6 = (Component)((value is Component) ? value : null);
					if (val6 != null && (Object)(object)val6 != (Object)null && IsUnderAnyVanillaRoot(val6.transform, vanillaActiveRoots, out string matchedRootName2))
					{
						violations.Add(text + " field '" + fieldInfo.Name + "' points directly to Component '" + ((object)val6).GetType().Name + "' under vanilla root '" + matchedRootName2 + "'.");
					}
				}
				type2 = type2.BaseType;
			}
		}

		private static void AuditFsmGameObject(string context, string fieldName, FsmGameObject fsmGo, HashSet<string> forbiddenVarSet, IReadOnlyList<Transform> vanillaActiveRoots, List<string> violations)
		{
			if (!string.IsNullOrEmpty(((NamedVariable)fsmGo).Name) && forbiddenVarSet.Contains(((NamedVariable)fsmGo).Name))
			{
				violations.Add(context + " field '" + fieldName + "' still references vanilla FSM variable '" + ((NamedVariable)fsmGo).Name + "'.");
			}
			if ((Object)(object)fsmGo.Value != (Object)null && IsUnderAnyVanillaRoot(fsmGo.Value.transform, vanillaActiveRoots, out string matchedRootName))
			{
				violations.Add(context + " field '" + fieldName + "' (var '" + ((NamedVariable)fsmGo).Name + "') points to GameObject '" + ((Object)fsmGo.Value).name + "' under vanilla root '" + matchedRootName + "'.");
			}
		}

		private static void AuditClonedAttackObject(GameObject clone, IReadOnlyList<Transform> vanillaActiveRoots, List<string> violations)
		{
			if (_activateOnSlashField == null)
			{
				return;
			}
			NailAttackBase[] componentsInChildren = clone.GetComponentsInChildren<NailAttackBase>(true);
			foreach (NailAttackBase val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null || !(_activateOnSlashField.GetValue(val) is GameObject[] array))
				{
					continue;
				}
				for (int j = 0; j < array.Length; j++)
				{
					GameObject val2 = array[j];
					if ((Object)(object)val2 != (Object)null && IsUnderAnyVanillaRoot(val2.transform, vanillaActiveRoots, out string matchedRootName))
					{
						violations.Add($"Cloned attack '{((Object)clone).name}' has activateOnSlash[{j}] pointing to '{((Object)val2).name}' under vanilla root '{matchedRootName}'.");
					}
				}
			}
		}

		private static bool IsUnderAnyVanillaRoot(Transform? candidate, IReadOnlyList<Transform> vanillaActiveRoots, out string matchedRootName)
		{
			matchedRootName = string.Empty;
			if ((Object)(object)candidate == (Object)null)
			{
				return false;
			}
			foreach (Transform vanillaActiveRoot in vanillaActiveRoots)
			{
				if ((Object)(object)vanillaActiveRoot != (Object)null && candidate.IsChildOf(vanillaActiveRoot))
				{
					matchedRootName = ((Object)vanillaActiveRoot).name;
					return true;
				}
			}
			return false;
		}
	}
	public sealed class NeutralAttackComposer
	{
		private sealed class CrestClones
		{
			public GameObject? Normal;

			public GameObject? Alternate;

			public GameObject? Wall;

			public GameObject? Taunt;

			public GameObject? Charge;

			public GameObject? RageNormal;

			public GameObject? RageAlternate;

			public GameObject? RageWall;
		}

		private static readonly string[] _stopStates = new string[2] { "Set Finished", "Regain Partial Control" };

		private static readonly HashSet<string> _clipNames = new HashSet<string>(VanillaCrestCatalog.NeutralAttackAnimationClips, StringComparer.Ordinal);

		private readonly CrestComposerContext _context;

		private readonly Dictionary<string, CrestClones> _clonesBySource = new Dictionary<string, CrestClones>(StringComparer.Ordinal);

		private readonly List<GameObject> _slotClones = new List<GameObject>();

		private string _activeNeutralAttack;

		public string ActiveNeutralAttack => _activeNeutralAttack;

		public bool LastSelfCheckPassed { get; private set; }

		internal NeutralAttackComposer(CrestComposerContext context, string initialNeutralAttack)
		{
			_context = context;
			_activeNeutralAttack = initialNeutralAttack;
		}

plugins/CustomCrest.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CrestComposition;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Needleforge;
using Needleforge.Data;
using TeamCherry.Localization;
using UnityEngine;

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

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

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CustomCrestMod
{
	public class AcceptableEnumList<T> : AcceptableValueBase where T : Enum
	{
		public virtual T[] AcceptableEnums { get; }

		public AcceptableEnumList(params T[] acceptableEnums)
			: base(typeof(T))
		{
			if (acceptableEnums == null)
			{
				throw new ArgumentNullException("acceptableEnums");
			}
			if (acceptableEnums.Length == 0)
			{
				throw new ArgumentException("At least one acceptable value is needed", "acceptableEnums");
			}
			AcceptableEnums = acceptableEnums;
		}

		public override object Clamp(object value)
		{
			if (!((AcceptableValueBase)this).IsValid(value))
			{
				return AcceptableEnums[0];
			}
			return value;
		}

		public override bool IsValid(object value)
		{
			if (value is T)
			{
				T obj = (T)value;
				return AcceptableEnums.Any((T x) => x.Equals(obj));
			}
			return false;
		}

		public override string ToDescriptionString()
		{
			return "# Acceptable values: " + string.Join(", ", AcceptableEnums.Select((T x) => x.ToString()).ToArray());
		}
	}
	public static class AnimationLibraryHelper
	{
		public static void RefreshAnimationLookup(tk2dSpriteAnimation? animLib)
		{
			if (!((Object)(object)animLib == (Object)null))
			{
				AnimationLibraryLookup.Refresh(animLib);
				ManualLogSource? modLogger = Plugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogInfo((object)"Refreshed animation library lookup table");
				}
			}
		}
	}
	internal sealed class ConfigurationManagerAttributes
	{
		public bool? ShowRangeAsPercent;

		public Action<ConfigEntryBase> CustomDrawer;

		public bool? Browsable;

		public string Category;

		public object DefaultValue;

		public bool? HideDefaultButton;

		public bool? HideSettingName;

		public string Description;

		public string DispName;

		public int? Order;

		public bool? ReadOnly;

		public bool? IsAdvanced;

		public Func<object, string> ObjToStr;

		public Func<string, object> StrToObj;
	}
	public enum CrestType
	{
		Hunter,
		Reaper,
		Wanderer,
		Warrior,
		Witch,
		Toolmaster,
		Spell
	}
	public static class CrestTypeExtensions
	{
		public static string GetInternalName(this CrestType crestType)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return VanillaCrestCatalog.Get(crestType.ToVanillaCrestType()).ActiveRootName;
		}

		public static VanillaCrestType ToVanillaCrestType(this CrestType crestType)
		{
			return (VanillaCrestType)(crestType switch
			{
				CrestType.Hunter => 0, 
				CrestType.Reaper => 1, 
				CrestType.Wanderer => 2, 
				CrestType.Warrior => 3, 
				CrestType.Witch => 4, 
				CrestType.Toolmaster => 5, 
				CrestType.Spell => 6, 
				_ => 0, 
			});
		}
	}
	public static class CustomCrestBuilder
	{
		public const string CustomCrestName = "CustomCrest";

		public const string LocalizationSheet = "Tools";

		public const string NameKey = "CREST_CUSTOM_NAME";

		public const string DescriptionKey = "CREST_CUSTOM_DESC";

		public const string PrefixKey = "CREST_CUSTOM_PREFIX";

		private static CrestData? _crestData;

		private static CrestMovesetComposer? _composer;

		public static CrestData? CrestData => _crestData;

		public static CrestMovesetComposer? Composer => _composer;

		public static bool IsInitialized
		{
			get
			{
				if (_crestData != null)
				{
					return _composer != null;
				}
				return false;
			}
		}

		public static void RegisterWithNeedleforge()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			if (_crestData == null)
			{
				LocalisedString val = new LocalisedString
				{
					Sheet = "Tools",
					Key = "CREST_CUSTOM_NAME"
				};
				LocalisedString val2 = new LocalisedString
				{
					Sheet = "Tools",
					Key = "CREST_CUSTOM_DESC"
				};
				_crestData = NeedleforgePlugin.AddCrest("CustomCrest", val, val2, Plugin.CustomCrestSprite, Plugin.CustomCrestSilhouetteSprite);
				_crestData.UnlockedAtStart = true;
				RebuildSlots(_crestData);
				_composer = new CrestMovesetComposer(_crestData, (VanillaCrestType)0, (VanillaCrestType)0, Plugin.DownAttackCrest.Value.ToVanillaCrestType(), Plugin.ModLogger);
				_composer.OnMovesetInitialized += OnMovesetInitialized;
				ManualLogSource? modLogger = Plugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogInfo((object)"Registered 'CustomCrest' with Needleforge.");
				}
			}
		}

		public static void ApplyNeutralAttackSelection(string sourceId)
		{
			CrestMovesetComposer? composer = _composer;
			if (composer != null)
			{
				composer.SetNeutralAttack(sourceId);
			}
		}

		public static void ApplyUpAttackSelection(string sourceId)
		{
			CrestMovesetComposer? composer = _composer;
			if (composer != null)
			{
				composer.SetUpAttack(sourceId);
			}
		}

		public static void ApplyDashAttackSelection(string sourceId)
		{
			CrestMovesetComposer? composer = _composer;
			if (composer != null)
			{
				composer.SetDashAttack(sourceId);
			}
		}

		public static void ApplyBindOutcomeSelection(string outcomeId)
		{
			CrestMovesetComposer? composer = _composer;
			if (composer != null)
			{
				composer.SetBindOutcome(outcomeId);
			}
		}

		public static void ApplyDownAttackSelection(CrestType crestType)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (_composer != null)
			{
				_composer.SetDownAttack(crestType.ToVanillaCrestType());
			}
		}

		public static void RebuildSlots(CrestData crestData)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (crestData != null)
			{
				crestData.slots.Clear();
				SlotInfo[] array = BuildCustomSlots();
				foreach (SlotInfo item in array)
				{
					crestData.slots.Add(item);
				}
			}
		}

		public static void ApplySlotLayoutChange()
		{
			if (_crestData == null)
			{
				return;
			}
			ToolCrest toolCrest = _crestData.ToolCrest;
			SlotInfo[] array = (((Object)(object)toolCrest != (Object)null) ? toolCrest.slots : null);
			RebuildSlots(_crestData);
			if (!((Object)(object)toolCrest == (Object)null))
			{
				toolCrest.slots = _crestData.slots.ToArray();
				if (array != null && (Object)(object)HeroController.instance != (Object)null && PlayerData.instance != null)
				{
					RemapEquippedTools(array, toolCrest.slots);
				}
			}
		}

		public static void ReconcileSavedTools()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			CrestData? crestData = _crestData;
			if ((Object)(object)((crestData != null) ? crestData.ToolCrest : null) == (Object)null || PlayerData.instance == null || (Object)(object)ManagerSingleton<ToolItemManager>.Instance == (Object)null)
			{
				return;
			}
			Data data = ((SerializableNamedList<Data, NamedData>)(object)PlayerData.instance.ToolEquips).GetData("CustomCrest");
			if (data.Slots == null)
			{
				return;
			}
			SlotInfo[] array = _crestData.slots.ToArray();
			List<string> list = new List<string>(array.Length);
			for (int i = 0; i < array.Length; i++)
			{
				list.Add(string.Empty);
			}
			List<ToolItem> list2 = new List<ToolItem>();
			bool flag = data.Slots.Count > array.Length;
			for (int j = 0; j < data.Slots.Count; j++)
			{
				string equippedTool = data.Slots[j].EquippedTool;
				if (string.IsNullOrEmpty(equippedTool))
				{
					continue;
				}
				ToolItem toolByName = ToolItemManager.GetToolByName(equippedTool);
				if ((Object)(object)toolByName == (Object)null)
				{
					if (j < array.Length)
					{
						list[j] = equippedTool;
					}
				}
				else if (j < array.Length && toolByName.Type == array[j].Type)
				{
					list[j] = equippedTool;
				}
				else
				{
					list2.Add(toolByName);
					flag = true;
				}
			}
			if (!flag)
			{
				return;
			}
			foreach (ToolItem tool in list2)
			{
				int num = FindFreeSlot(array, list, (SlotInfo slot) => slot.Type == tool.Type);
				if (num >= 0)
				{
					list[num] = tool.name;
				}
			}
			WriteEquippedTools(list, array.Length);
			ManualLogSource? modLogger = Plugin.ModLogger;
			if (modLogger != null)
			{
				modLogger.LogInfo((object)$"Moved or unequipped {list2.Count} saved tool(s) to match the current slot layout.");
			}
		}

		private static void RemapEquippedTools(SlotInfo[] oldSlots, SlotInfo[] newSlots)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			Data data = ((SerializableNamedList<Data, NamedData>)(object)PlayerData.instance.ToolEquips).GetData("CustomCrest");
			if (data.Slots == null)
			{
				return;
			}
			List<string> list = new List<string>(newSlots.Length);
			for (int i = 0; i < newSlots.Length; i++)
			{
				list.Add(string.Empty);
			}
			for (int j = 0; j < oldSlots.Length && j < data.Slots.Count; j++)
			{
				string equippedTool = data.Slots[j].EquippedTool;
				if (string.IsNullOrEmpty(equippedTool))
				{
					continue;
				}
				SlotInfo oldSlot = oldSlots[j];
				Predicate<SlotInfo> predicate = (SlotInfo slot) => slot.Type == oldSlot.Type && slot.AttackBinding == oldSlot.AttackBinding;
				int num = ((j < newSlots.Length && list[j].Length == 0 && predicate(newSlots[j])) ? j : FindFreeSlot(newSlots, list, predicate));
				if (num < 0)
				{
					num = FindFreeSlot(newSlots, list, (SlotInfo slot) => slot.Type == oldSlot.Type);
				}
				if (num >= 0)
				{
					list[num] = equippedTool;
				}
			}
			WriteEquippedTools(list, newSlots.Length);
			ToolItemManager.SendEquippedChangedEvent(true);
		}

		private static void WriteEquippedTools(List<string> equippedTools, int slotCount)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			ToolItemManager.SetEquippedTools("CustomCrest", equippedTools);
			Data data = ((SerializableNamedList<Data, NamedData>)(object)PlayerData.instance.ToolEquips).GetData("CustomCrest");
			if (data.Slots != null && data.Slots.Count > slotCount)
			{
				data.Slots.RemoveRange(slotCount, data.Slots.Count - slotCount);
				((SerializableNamedList<Data, NamedData>)(object)PlayerData.instance.ToolEquips).SetData("CustomCrest", data);
			}
		}

		private static int FindFreeSlot(SlotInfo[] slots, List<string> equippedTools, Predicate<SlotInfo> matches)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < slots.Length; i++)
			{
				if (equippedTools[i].Length == 0 && matches(slots[i]))
				{
					return i;
				}
			}
			return -1;
		}

		public static void InjectLocalizedStrings()
		{
			try
			{
				if (typeof(Language).GetField("_currentEntrySheets", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null) is IDictionary dictionary && dictionary.Contains("Tools") && dictionary["Tools"] is IDictionary dictionary2)
				{
					dictionary2["CREST_CUSTOM_NAME"] = "Custom Crest";
					dictionary2["CREST_CUSTOM_DESC"] = "Behold, the power of customization!";
					dictionary2["CREST_CUSTOM_PREFIX"] = "Bound the Custom Crest of";
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? modLogger = Plugin.ModLogger;
				if (modLogger != null)
				{
					modLogger.LogWarning((object)("Could not inject localized strings: " + ex.Message));
				}
			}
		}

		private static void OnMovesetInitialized()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			InjectLocalizedStrings();
			CrestData? crestData = _crestData;
			if ((Object)(object)((crestData != null) ? crestData.ToolCrest : null) != (Object)null)
			{
				_crestData.ToolCrest.itemNamePrefix = new LocalisedString
				{
					Sheet = "Tools",
					Key = "CREST_CUSTOM_PREFIX"
				};
			}
		}

		private static SlotInfo[] BuildCustomSlots()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			List<SlotInfo> list = new List<SlotInfo>();
			float num = (0f - (float)(Plugin.BlueSlots.Value - 1) * 1.8f) / 2f;
			for (int i = 0; i < Plugin.BlueSlots.Value; i++)
			{
				list.Add(CreateSlot(num + (float)i * 1.8f, 3.2f, (ToolItemType)1));
			}
			ToolItemType type = (ToolItemType)(Plugin.UpUseSkillSlots.Value ? 3 : 0);
			for (int j = 0; j < Plugin.UpAttackSlots.Value; j++)
			{
				list.Add(CreateSlot(0f, 1.6f, type, (AttackToolBinding)1));
			}
			ToolItemType type2 = (ToolItemType)(Plugin.NeutralUseSkillSlots.Value ? 3 : 0);
			for (int k = 0; k < Plugin.NeutralAttackSlots.Value; k++)
			{
				list.Add(CreateSlot(0f, 0f, type2, (AttackToolBinding)0));
			}
			ToolItemType type3 = (ToolItemType)(Plugin.DownUseSkillSlots.Value ? 3 : 0);
			for (int l = 0; l < Plugin.DownAttackSlots.Value; l++)
			{
				list.Add(CreateSlot(0f, -1.6f, type3, (AttackToolBinding)2));
			}
			float num2 = (0f - (float)(Plugin.YellowSlots.Value - 1) * 1.8f) / 2f;
			for (int m = 0; m < Plugin.YellowSlots.Value; m++)
			{
				list.Add(CreateSlot(num2 + (float)m * 1.8f, -3.2f, (ToolItemType)2));
			}
			return ToolSlotNavigationHelper.ToFixedNavigation(list.ToArray());
		}

		private static SlotInfo CreateSlot(float x, float y, ToolItemType type, AttackToolBinding? binding = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			SlotInfo result = new SlotInfo
			{
				Position = new Vector2(x, y),
				Type = type,
				IsLocked = !Plugin.UnlockAllSlots.Value,
				NavUpIndex = -1,
				NavDownIndex = -1,
				NavLeftIndex = -1,
				NavRightIndex = -1,
				NavUpFallbackIndex = -1,
				NavDownFallbackIndex = -1,
				NavLeftFallbackIndex = -1,
				NavRightFallbackIndex = -1
			};
			if (binding.HasValue)
			{
				result.AttackBinding = binding.Value;
			}
			return result;
		}
	}
	[BepInPlugin("com.zorkats.silksong.customcrest", "Custom Crest Builder", "4.0.0")]
	[BepInDependency("io.github.needleforge", "0.9.0")]
	[BepInDependency("org.silksong-modding.fsmutil", "0.3.16")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(HeroController), "Start")]
		public static class HeroController_Start_ReconcileTools_Patch
		{
			private static void Prefix()
			{
				try
				{
					CustomCrestBuilder.ReconcileSavedTools();
				}
				catch (Exception arg)
				{
					ManualLogSource? modLogger = ModLogger;
					if (modLogger != null)
					{
						modLogger.LogError((object)$"Could not match saved tools to the slot layout: {arg}");
					}
				}
			}
		}

		[HarmonyPatch(typeof(Language), "Get", new Type[]
		{
			typeof(string),
			typeof(string)
		})]
		public static class Language_Get_Localization_Patch
		{
			private static void Postfix(string key, string sheetTitle, ref string __result)
			{
				if (string.Equals(sheetTitle, "Tools", StringComparison.Ordinal))
				{
					switch (key)
					{
					case "CREST_CUSTOM_NAME":
						__result = "Custom Crest";
						break;
					case "CREST_CUSTOM_DESC":
						__result = "Behold, the power of customization!";
						break;
					case "CREST_CUSTOM_PREFIX":
						__result = "Bound the Custom Crest of";
						break;
					}
				}
			}
		}

		private const string PluginGuid = "com.zorkats.silksong.customcrest";

		private const string PluginName = "Custom Crest Builder";

		private const string PluginVersion = "4.0.0";

		public static Sprite? CustomCrestSprite;

		public static Sprite? CustomCrestSilhouetteSprite;

		public static ConfigEntry<string> NeutralAttackCrest;

		public static ConfigEntry<string> UpAttackCrest;

		public static ConfigEntry<string> DashAttackCrest;

		public static ConfigEntry<string> BindingActionCrest;

		public static ConfigEntry<CrestType> DownAttackCrest;

		public static ConfigEntry<int> NeutralAttackSlots;

		public static ConfigEntry<int> UpAttackSlots;

		public static ConfigEntry<int> DownAttackSlots;

		public static ConfigEntry<int> BlueSlots;

		public static ConfigEntry<int> YellowSlots;

		public static ConfigEntry<bool> UnlockAllSlots;

		public static ConfigEntry<bool> UpUseSkillSlots;

		public static ConfigEntry<bool> NeutralUseSkillSlots;

		public static ConfigEntry<bool> DownUseSkillSlots;

		public static ManualLogSource? ModLogger;

		private readonly HashSet<ConfigEntryBase> _slotLayoutEntries = new HashSet<ConfigEntryBase>();

		private Harmony? _harmony;

		private void Awake()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			ModLogger = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Custom Crest Builder v4.0.0 loaded");
			LoadEmbeddedSprites();
			SetupConfig();
			DownAttackCrest.SettingChanged += OnDownAttackSettingChanged;
			((BaseUnityPlugin)this).Config.SettingChanged += OnConfigSettingChanged;
			CustomCrestBuilder.RegisterWithNeedleforge();
			_harmony = new Harmony("com.zorkats.silksong.customcrest");
			try
			{
				_harmony.PatchAll(typeof(Language_Get_Localization_Patch));
				_harmony.PatchAll(typeof(HeroController_Start_ReconcileTools_Patch));
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Patches applied");
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Failed to apply patches: {arg}");
			}
		}

		private void Start()
		{
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			List<AttackSource> available = AttackSourceCatalog.GetAvailable(((BaseUnityPlugin)this).Logger);
			string[] array = available.Select((AttackSource source) => source.Id).ToArray();
			string[] array2 = (from source in available
				where source.HasPlayableDashAttack
				select source.Id).ToArray();
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Attack sources available: " + string.Join(", ", array)));
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Dash attack sources available: " + string.Join(", ", array2)));
			NeutralAttackCrest = BindAttackSource("NeutralAttack", "Crest to copy Neutral Attack moveset from", array);
			UpAttackCrest = BindAttackSource("UpAttack", "Crest to copy Up Attack moveset from", array);
			DashAttackCrest = BindAttackSource("DashAttack", "Crest to copy Dash Attack moveset from", array2);
			NeutralAttackCrest.SettingChanged += OnNeutralAttackSettingChanged;
			UpAttackCrest.SettingChanged += OnUpAttackSettingChanged;
			DashAttackCrest.SettingChanged += OnDashAttackSettingChanged;
			CustomCrestBuilder.ApplyNeutralAttackSelection(NeutralAttackCrest.Value);
			CustomCrestBuilder.ApplyUpAttackSelection(UpAttackCrest.Value);
			CustomCrestBuilder.ApplyDashAttackSelection(DashAttackCrest.Value);
			string[] array3 = ((CustomCrestBuilder.Composer != null) ? CustomCrestBuilder.Composer.BindOutcome.GetAvailableOutcomes().ToArray() : new string[1] { ((object)(VanillaCrestType)0/*cast due to .constrained prefix*/).ToString() });
			BindingActionCrest = ((BaseUnityPlugin)this).Config.Bind<string>("1. Attack Movesets", "BindingAction", ((object)(VanillaCrestType)0/*cast due to .constrained prefix*/).ToString(), new ConfigDescription("Crest whose bind outcome to use: Warrior enters rage, Witch binds with tentacles, Reaper enters reaper mode, Spell charges, Toolmaster quick crafts when binding with Up held, Wanderer heals normally and gives lucky hits while silk is at 9 or more, Hunter heals normally, and Void, when Void Crest is installed, focuses and uses its sphere when binding with Up held", (AcceptableValueBase)(object)new AcceptableValueList<string>(array3), Array.Empty<object>()));
			BindingActionCrest.SettingChanged += OnBindingActionSettingChanged;
			CustomCrestBuilder.ApplyBindOutcomeSelection(BindingActionCrest.Value);
		}

		private ConfigEntry<string> BindAttackSource(string key, string description, string[] attackSources)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			return ((BaseUnityPlugin)this).Config.Bind<string>("1. Attack Movesets", key, ((object)(VanillaCrestType)0/*cast due to .constrained prefix*/).ToString(), new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueList<string>(attackSources), Array.Empty<object>()));
		}

		private void OnDestroy()
		{
			if (NeutralAttackCrest != null)
			{
				NeutralAttackCrest.SettingChanged -= OnNeutralAttackSettingChanged;
			}
			if (UpAttackCrest != null)
			{
				UpAttackCrest.SettingChanged -= OnUpAttackSettingChanged;
			}
			if (DownAttackCrest != null)
			{
				DownAttackCrest.SettingChanged -= OnDownAttackSettingChanged;
			}
			if (DashAttackCrest != null)
			{
				DashAttackCrest.SettingChanged -= OnDashAttackSettingChanged;
			}
			if (BindingActionCrest != null)
			{
				BindingActionCrest.SettingChanged -= OnBindingActionSettingChanged;
			}
			((BaseUnityPlugin)this).Config.SettingChanged -= OnConfigSettingChanged;
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private static void OnNeutralAttackSettingChanged(object sender, EventArgs args)
		{
			CustomCrestBuilder.ApplyNeutralAttackSelection(NeutralAttackCrest.Value);
		}

		private static void OnUpAttackSettingChanged(object sender, EventArgs args)
		{
			CustomCrestBuilder.ApplyUpAttackSelection(UpAttackCrest.Value);
		}

		private static void OnDownAttackSettingChanged(object sender, EventArgs args)
		{
			CustomCrestBuilder.ApplyDownAttackSelection(DownAttackCrest.Value);
		}

		private static void OnDashAttackSettingChanged(object sender, EventArgs args)
		{
			CustomCrestBuilder.ApplyDashAttackSelection(DashAttackCrest.Value);
		}

		private static void OnBindingActionSettingChanged(object sender, EventArgs args)
		{
			CustomCrestBuilder.ApplyBindOutcomeSelection(BindingActionCrest.Value);
		}

		private void OnConfigSettingChanged(object sender, SettingChangedEventArgs args)
		{
			if (_slotLayoutEntries.Contains(args.ChangedSetting))
			{
				CustomCrestBuilder.ApplySlotLayoutChange();
			}
		}

		private void SetupConfig()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Expected O, but got Unknown
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			DownAttackCrest = ((BaseUnityPlugin)this).Config.Bind<CrestType>("1. Attack Movesets", "DownAttack", CrestType.Hunter, new ConfigDescription("Crest to copy Down Attack moveset from", (AcceptableValueBase)(object)new AcceptableEnumList<CrestType>(CrestType.Hunter, CrestType.Reaper, CrestType.Wanderer, CrestType.Warrior, CrestType.Witch, CrestType.Toolmaster, CrestType.Spell), Array.Empty<object>()));
			NeutralAttackSlots = ((BaseUnityPlugin)this).Config.Bind<int>("2. Attack Slot Distribution", "NeutralSlots", 1, new ConfigDescription("Number of Neutral Attack slots", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1), Array.Empty<object>()));
			NeutralUseSkillSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Attack Slot Distribution", "NeutralUseSkillSlots", false, "If true, Neutral attack slots will be white/Skill type instead of red");
			UpAttackSlots = ((BaseUnityPlugin)this).Config.Bind<int>("2. Attack Slot Distribution", "UpSlots", 1, new ConfigDescription("Number of Up Attack slots", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1), Array.Empty<object>()));
			UpUseSkillSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Attack Slot Distribution", "UpUseSkillSlots", false, "If true, Up attack slots will be white/Skill type instead of red");
			DownAttackSlots = ((BaseUnityPlugin)this).Config.Bind<int>("2. Attack Slot Distribution", "DownSlots", 1, new ConfigDescription("Number of Down Attack slots", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1), Array.Empty<object>()));
			DownUseSkillSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Attack Slot Distribution", "DownUseSkillSlots", false, "If true, Down attack slots will be white/Skill type instead of red");
			BlueSlots = ((BaseUnityPlugin)this).Config.Bind<int>("3. Passive & Utility Slots", "BlueSlots", 3, new ConfigDescription("Number of Blue (passive) tool slots", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			YellowSlots = ((BaseUnityPlugin)this).Config.Bind<int>("3. Passive & Utility Slots", "YellowSlots", 3, new ConfigDescription("Number of Yellow (utility) tool slots", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			UnlockAllSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("4. General Options", "UnlockAllSlots", true, "If true, all slots are unlocked by default");
			_slotLayoutEntries.UnionWith((IEnumerable<ConfigEntryBase>)(object)new ConfigEntryBase[9]
			{
				(ConfigEntryBase)NeutralAttackSlots,
				(ConfigEntryBase)NeutralUseSkillSlots,
				(ConfigEntryBase)UpAttackSlots,
				(ConfigEntryBase)UpUseSkillSlots,
				(ConfigEntryBase)DownAttackSlots,
				(ConfigEntryBase)DownUseSkillSlots,
				(ConfigEntryBase)BlueSlots,
				(ConfigEntryBase)YellowSlots,
				(ConfigEntryBase)UnlockAllSlots
			});
		}

		private Sprite? LoadSprite(string resourceName)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			try
			{
				using Stream stream = executingAssembly.GetManifestResourceStream(resourceName);
				if (stream == null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Embedded resource not found: " + resourceName));
					return null;
				}
				byte[] array = new byte[stream.Length];
				int num;
				for (int i = 0; i < array.Length; i += num)
				{
					num = stream.Read(array, i, array.Length - i);
					if (num <= 0)
					{
						break;
					}
				}
				Texture2D val = new Texture2D(256, 256, (TextureFormat)4, false);
				ImageConversion.LoadImage(val, array);
				val.Apply();
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Failed to load sprite from resource {resourceName}: {arg}");
				return null;
			}
		}

		private void LoadEmbeddedSprites()
		{
			CustomCrestSprite = LoadSprite("CustomCrest.Custom_Crest.png");
			CustomCrestSilhouetteSprite = LoadSprite("CustomCrest.CustomCrestSilhouette.png");
			if ((Object)(object)CustomCrestSprite != (Object)null)
			{
				((Object)CustomCrestSprite).name = "CustomCrestIcon";
			}
		}
	}
	public static class ToolSlotNavigationHelper
	{
		private enum Direction
		{
			None,
			Left,
			Right,
			Up,
			Down
		}

		public static SlotInfo[] ToFixedNavigation(SlotInfo[] slots)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if (slots == null)
			{
				return Array.Empty<SlotInfo>();
			}
			for (int i = 0; i < slots.Length; i++)
			{
				Vector2 position = slots[i].Position;
				foreach (Direction value in Enum.GetValues(typeof(Direction)))
				{
					if (value == Direction.None)
					{
						continue;
					}
					int num = -1;
					float num2 = float.MaxValue;
					for (int j = 0; j < slots.Length; j++)
					{
						if (i == j)
						{
							continue;
						}
						Vector2 position2 = slots[j].Position;
						if (IsInDirection(position, position2, value))
						{
							float num3 = Vector2.Distance(position, position2);
							if (num3 < num2)
							{
								num2 = num3;
								num = j;
							}
						}
					}
					switch (value)
					{
					case Direction.Left:
						slots[i].NavLeftIndex = num;
						break;
					case Direction.Right:
						slots[i].NavRightIndex = num;
						break;
					case Direction.Up:
						slots[i].NavUpIndex = num;
						break;
					case Direction.Down:
						slots[i].NavDownIndex = num;
						break;
					}
				}
			}
			return slots;
		}

		private static bool IsInDirection(Vector2 from, Vector2 to, Direction dir)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = to - from;
			switch (dir)
			{
			case Direction.Left:
				if (val.x < 0f)
				{
					return Math.Abs(val.x) >= Math.Abs(val.y);
				}
				return false;
			case Direction.Right:
				if (val.x > 0f)
				{
					return Math.Abs(val.x) >= Math.Abs(val.y);
				}
				return false;
			case Direction.Up:
				if (val.y > 0f)
				{
					return Math.Abs(val.y) >= Math.Abs(val.x);
				}
				return false;
			case Direction.Down:
				if (val.y < 0f)
				{
					return Math.Abs(val.y) >= Math.Abs(val.x);
				}
				return false;
			default:
				return false;
			}
		}
	}
}