Decompiled source of PoVPlus NorseDemigods v1.0.0

PoVPlus.NorseDemigods.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("PoVPlus.NorseDemigods")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9efae1c53938a3515f5106ece0b6e7a8857b826c")]
[assembly: AssemblyProduct("PoVPlus.NorseDemigods")]
[assembly: AssemblyTitle("PoVPlus.NorseDemigods")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace PoVPlus.NorseDemigods;

[BepInPlugin("avesatanas.povplus.norsedemigods", "PoVPlus.NorseDemigods", "1.0.0")]
public sealed class Plugin : BaseUnityPlugin
{
	internal sealed class ConduitMark
	{
		public ItemData Item;

		public bool Weapon;

		public float Share = 1f;
	}

	internal enum BuildKind
	{
		Gem,
		Conduit,
		Weapon
	}

	internal struct ConduitRule
	{
		public SkillType Skill;

		public bool TwoHandedOnly;
	}

	private sealed class ConfigurationManagerAttributes
	{
		public int? Order;
	}

	[Flags]
	internal enum Shape
	{
		None = 0,
		Area = 1,
		Projectile = 2
	}

	internal sealed class MorphState
	{
		public bool Built;

		public string Ability;

		public float Before;

		public string Line;

		public Shape Shape;

		public BuildState Build;

		public float Chop;

		public float Pickaxe;

		public bool TreeHeld;

		public ItemData Conduit;

		public SharedData Shared;

		public float Add;

		public object Profile;
	}

	internal sealed class BuildState
	{
		public bool Saved;

		public object Profile;

		public object Weapon;

		public object Tags;

		public bool RangedSet;

		public bool Ranged;

		public bool BuiltRanged;
	}

	private static readonly string[] ExecuteDecided = new string[15]
	{
		"Blast", "Bomb", "Cleave", "Whirlwind", "Stagger", "FrostNova", "Crush", "LightningTorpedo", "HolySun", "SharpMist",
		"Tornado", "Vortex", "WaterSphere", "NanoCube", "Sacrifice"
	};

	private static readonly Dictionary<string, float> Shares = new Dictionary<string, float>
	{
		{
			"HolySun",
			1f / 7f
		},
		{ "SharpMist", 0.125f },
		{
			"Tornado",
			1f / 15f
		},
		{ "NanoCube", 0.1f },
		{ "DecayAura", 0.1f },
		{ "EnergyWisp", 0.2f }
	};

	private static FieldInfo _stormRateField;

	private static FieldInfo _burnDurationField;

	private static FieldInfo _sphereCountField;

	private static FieldInfo _infusedSphereField;

	private static ConfigEntry<int> _stormRate;

	private static ConfigEntry<int> _burnDuration;

	private static ConfigEntry<int> _sphereCount;

	private static ConfigEntry<int> _infusedSphere;

	private static Func<Player, bool> _infused;

	private static MethodInfo _minionsOf;

	private static MethodInfo _skeletons;

	private static bool _shareFailed;

	private static readonly HashSet<string> WeaponDerived = new HashSet<string> { "Slash", "Whirlwind", "Cleave", "Stagger", "InfusedArrow" };

	private static readonly Dictionary<string, ConduitMark> Decided = new Dictionary<string, ConduitMark>();

	private static readonly ConditionalWeakTable<Component, ConduitMark> ConduitOf = new ConditionalWeakTable<Component, ConduitMark>();

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

	private static Dictionary<string, SharedData> _originalShared;

	private static PropertyInfo _conduitOwner;

	private static bool _conduitsOn;

	private static bool _conduitFailed;

	[ThreadStatic]
	private static ConduitMark _objectConduit;

	private static ConfigFile _config;

	private static PropertyInfo _godList;

	private static PropertyInfo _godListName;

	private static PropertyInfo _godListAbilities;

	private static object _godsBoundFrom;

	private static readonly Dictionary<string, bool> MinionDefaults = new Dictionary<string, bool>
	{
		{ "ElementalGolem", true },
		{ "Minions", true },
		{ "Surtling", true },
		{ "Wolf", false }
	};

	private static readonly Dictionary<string, ConfigEntry<bool>> Minions = new Dictionary<string, ConfigEntry<bool>>();

	private static readonly Dictionary<string, ConfigEntry<bool>> Companion = new Dictionary<string, ConfigEntry<bool>>();

	private static readonly Dictionary<string, string[]> ConduitConfigDefaults = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
	{
		{
			"Thor",
			new string[2] { "Clubs, Unarmed, Axes", "Mjölnir and Járngreipr; Static Body rewards clubs and axes" }
		},
		{
			"Brokkr",
			new string[2] { "Clubs, Axes", "the smith of Mjölnir; Thunder Forger rewards axes and clubs" }
		},
		{
			"Eir",
			new string[2] { "Spears, Swords", "Holy Body rewards spears and swords" }
		},
		{
			"Freyja",
			new string[2] { "Spears, Swords, ElementalMagic", "Thorn Body rewards spears and swords; a seiðr staff" }
		},
		{
			"Surtr",
			new string[2] { "Swords, Axes, Polearms", "his fiery sword; Flame Body rewards axes, swords and polearms" }
		},
		{
			"Njord",
			new string[2] { "Polearms, Axes, Swords, Clubs (two-handed)", "Aquatic Body rewards axes, swords and polearms; Raider two-handed clubs" }
		},
		{
			"Hel",
			new string[2] { "Knives, Polearms, Axes (two-handed), Swords (two-handed)", "her knife Sultr; Celestial Body rewards polearms, daggers and two-handed axes and swords" }
		},
		{
			"Kvasir",
			new string[2] { "Knives, Bows, Crossbows, Unarmed, BloodMagic", "Piercing Instincts and Bloody Archer reward knives, claws, bows and crossbows; his blood" }
		},
		{
			"Ullr",
			new string[2] { "Bows, Crossbows, Spears", "the bow-god; Hunter rewards bows, crossbows and spears" }
		},
		{
			"Hraesvelgr",
			new string[2] { "Swords, Polearms", "Eagle Precision rewards swords and polearms" }
		},
		{
			"Fenrir",
			new string[2] { "Unarmed, ElementalMagic", "Titan Arms fights bare-handed; frost shards are fired with a staff" }
		},
		{
			"Saiyan",
			new string[2] { "Unarmed", "Titan Arms fights bare-handed" }
		}
	};

	private static readonly Dictionary<string, SkillType> ConduitSkillNames = new Dictionary<string, SkillType>(StringComparer.OrdinalIgnoreCase)
	{
		{
			"Swords",
			(SkillType)1
		},
		{
			"Knives",
			(SkillType)2
		},
		{
			"Clubs",
			(SkillType)3
		},
		{
			"Polearms",
			(SkillType)4
		},
		{
			"Spears",
			(SkillType)5
		},
		{
			"Axes",
			(SkillType)7
		},
		{
			"Bows",
			(SkillType)8
		},
		{
			"Crossbows",
			(SkillType)14
		},
		{
			"Unarmed",
			(SkillType)11
		},
		{
			"ElementalMagic",
			(SkillType)9
		},
		{
			"BloodMagic",
			(SkillType)10
		}
	};

	private const string TwoHandedMark = "(two-handed)";

	private static readonly Dictionary<string, ConfigEntry<string>> _conduitEntries = new Dictionary<string, ConfigEntry<string>>(StringComparer.OrdinalIgnoreCase);

	private static readonly Dictionary<string, ConduitRule[]> _conduitRules = new Dictionary<string, ConduitRule[]>(StringComparer.OrdinalIgnoreCase);

	private static ConfigEntry<bool> _useConduits;

	private static ConfigEntry<bool> _holdKey;

	private static bool _keyHeld;

	private static int _holdEdits;

	private static bool _holdInstalled;

	private static bool _jumpInstalled;

	private static bool _jumpCast;

	private static bool _jumpFailed;

	private static bool _typeFailed;

	private static Func<object, int> _abilityType;

	private static int _airType;

	private static Func<object, bool> _isChanneled;

	private static Func<object, bool> _isActive;

	private static Action<object, bool> _stopAbility;

	private static Func<string, bool> _button;

	private static Func<Character, bool> _takeInput;

	private static MethodInfo _tryGetAbility;

	private static readonly object[] ProbeArgs = new object[3];

	private static readonly object NoSkill = (object)(SkillType)0;

	private static object _jumpChannel;

	private static bool _airJumpHooked;

	private static int _inJump;

	private static float _airJumpAt = float.NegativeInfinity;

	private static bool _pending;

	private static int _pendingFrame;

	private static float _pendingAt;

	private static float _pendingReal;

	private static readonly MethodInfo HeldMainMethod = AccessTools.Method(typeof(Plugin), "HeldMain", (Type[])null, (Type[])null);

	private static readonly MethodInfo HeldShortcutMethod = AccessTools.Method(typeof(Plugin), "HeldShortcut", (Type[])null, (Type[])null);

	private static readonly MethodInfo KeepMethod = AccessTools.Method(typeof(Plugin), "KeepAbility", (Type[])null, (Type[])null);

	private static readonly MethodInfo ShortcutPressed = AccessTools.Method(typeof(KeyboardShortcut), "IsPressed", (Type[])null, (Type[])null);

	private const int NoAirJump = 0;

	private const int DoubleJumpOnly = 1;

	private const int WallJumpOrUnknown = 2;

	private static object _spellCategory;

	private static readonly FieldRef<Attack, Humanoid> AttackOwner = AccessTools.FieldRefAccess<Attack, Humanoid>("m_character");

	[ThreadStatic]
	private static int _delivering;

	private static readonly ConditionalWeakTable<SharedData, string> Morphs = new ConditionalWeakTable<SharedData, string>();

	private static FieldInfo _profileOverride;

	private static FieldInfo _weaponOverride;

	private static MethodInfo _tagsReplace;

	private static MethodInfo _tagsPop;

	private static object _noTags;

	private static bool _stateFailed;

	private static MethodInfo _tagsPush;

	private static object _areaTag;

	private static object _gemTag;

	private static object _gemAreaTag;

	private static object _gemProfile;

	private static FieldInfo _budgetMult;

	private static bool _treeFailed;

	private static MethodInfo _conduitFor;

	private static Func<ItemData, SkillType> _treeSkillOf;

	private static FieldInfo _tooltipItem;

	[ThreadStatic]
	private static ItemData _tooltipSaved;

	private static bool _conduitBuildFailed;

	private static readonly ConditionalWeakTable<HitData, object> MorphProfiles = new ConditionalWeakTable<HitData, object>();

	private static object _shots;

	private static MethodInfo _shotFind;

	private static FieldInfo _shotWeapon;

	private static bool _landingFailed;

	[ThreadStatic]
	private static HitData _marked;

	[ThreadStatic]
	private static object _markedProfile;

	[ThreadStatic]
	private static int _semanDepth;

	[ThreadStatic]
	private static int _markedDepth;

	private static readonly Dictionary<string, Shape> Shapes = new Dictionary<string, Shape>
	{
		{
			"FrostNova",
			Shape.Area
		},
		{
			"PoisonCloud",
			Shape.Area
		},
		{
			"HolySun",
			Shape.Area
		},
		{
			"Tornado",
			Shape.Area
		},
		{
			"Vortex",
			Shape.Area
		},
		{
			"SharpMist",
			Shape.Area
		},
		{
			"WaterSphere",
			Shape.Area
		},
		{
			"DecayAura",
			Shape.Area
		},
		{
			"Blast",
			Shape.Area
		},
		{
			"BurningGround",
			Shape.Area
		},
		{
			"Fireball",
			Shape.Projectile
		},
		{
			"Iceshards",
			Shape.Projectile
		},
		{
			"PoisonJavelin",
			Shape.Projectile
		},
		{
			"AcidBolt",
			Shape.Projectile
		},
		{
			"ArcaneBolt",
			Shape.Projectile
		},
		{
			"LightningBolt",
			Shape.Projectile
		},
		{
			"LightningTorpedo",
			Shape.Projectile
		},
		{
			"Bomb",
			Shape.Projectile
		},
		{
			"Meteor",
			Shape.Projectile
		}
	};

	[ThreadStatic]
	private static int _building;

	private static ManualLogSource _log;

	private static ConfigEntry<bool> _hitLog;

	private static MethodInfo _tryGetDemigod;

	private static PropertyInfo _demigodName;

	private static MethodInfo _treeSkill;

	private static bool _logFailed;

	private static readonly Dictionary<string, float> SkipLogged = new Dictionary<string, float>();

	public const string PluginGuid = "avesatanas.povplus.norsedemigods";

	public const string PluginName = "PoVPlus.NorseDemigods";

	public const string PluginVersion = "1.0.0";

	private const SkillType None = (SkillType)0;

	private static Assembly _norse;

	private static Type _povEffect;

	private static readonly FieldRef<Humanoid, Attack> CurrentAttack = AccessTools.FieldRefAccess<Humanoid, Attack>("m_currentAttack");

	private static MethodInfo _copyBudget;

	private static MethodInfo _addTags;

	private static object _budgets;

	private static MethodInfo _budgetFind;

	private static MethodInfo _critOf;

	private static MethodInfo _trimFind;

	private static object _trimBudgets;

	private static FieldInfo _budgetCharge;

	private static FieldInfo _budgetTags;

	private static long _strikeTags;

	private static bool _inheritFailed;

	private static readonly string[] KnownDamageAbilities = new string[41]
	{
		"AcidBolt", "ArcaneBolt", "Blast", "Blink", "BloodSlash", "Bomb", "BurningGround", "Cleave", "Crush", "Dash",
		"DecayAura", "ElementalGolem", "ElementalShield", "EnergyWisp", "Enraged", "Fireball", "FrostNova", "HolyStrike", "HolySun", "Iceshards",
		"InfusedArrow", "LightningBolt", "LightningStorm", "LightningStrike", "LightningTorpedo", "Meteor", "Minions", "NanoCube", "PoisonCloud", "PoisonJavelin",
		"Restoration", "Sacrifice", "SharpMist", "Slash", "Stagger", "Surtling", "Tornado", "Vortex", "WaterSphere", "Whirlwind",
		"Wolf"
	};

	[ThreadStatic]
	private static int _inNorseObject;

	[ThreadStatic]
	private static string _objectAbility;

	[ThreadStatic]
	private static float _objectShare;

	private static readonly ConditionalWeakTable<Aoe, object> BurnAoes = new ConditionalWeakTable<Aoe, object>();

	[ThreadStatic]
	private static int _inVictimDamage;

	[ThreadStatic]
	private static HitData _victimHit;

	[ThreadStatic]
	private static int _inAreaDamage;

	[ThreadStatic]
	private static HitData _areaHit;

	private static readonly HitData NoHit = new HitData();

	private static readonly HashSet<string> DerivedProcs = new HashSet<string> { "@AquaticBody", "@CelestialBody", "@EaglePrecision", "@FlameBody", "@HolyBody", "@SaiyanBody", "@StaticBody", "@ThornBody", "@ThunderForger", "Enraged" };

	private static readonly ConditionalWeakTable<Component, string> Launched = new ConditionalWeakTable<Component, string>();

	[ThreadStatic]
	private static Projectile _arrowSplash;

	[ThreadStatic]
	private static int _arrowArea;

	[ThreadStatic]
	private static int _arrowVictim;

	private static Action<Projectile, HitData> _arrowInherit;

	private static bool _arrowFailed;

	private static readonly Dictionary<Type, string> NorseIds = new Dictionary<Type, string>();

	private static readonly ConditionalWeakTable<Projectile, object> Grown = new ConditionalWeakTable<Projectile, object>();

	private static readonly object GrownMark = new object();

	private static FieldRef<Projectile, Character> _projectileOwner;

	private static MethodInfo _fighting;

	private static MethodInfo _subjectAdd;

	private static object _areaSubject;

	private static object _projectileSubject;

	private static PropertyInfo _progressCurrent;

	private static FieldInfo _progressStats;

	private static MethodInfo _areaFactor;

	private static bool _growFailed;

	private static Func<string, bool> _statHas;

	private static Type _minionMark;

	private static MethodInfo _cooldownOf;

	private static object _skillCooldown;

	private static MethodInfo _companionSend;

	private static FieldInfo _wolfField;

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

	private static readonly Dictionary<string, SharedData> MorphSeen = new Dictionary<string, SharedData>();

	private static ConfigEntry<bool> _measuredBonus;

	private static Type _abilityBase;

	private static PropertyInfo _abilityOwner;

	private static readonly Dictionary<Type, Type> TooltipDeclarer = new Dictionary<Type, Type>();

	private static bool _measureFailed;

	private static bool _tooltipFailed;

	private const string TooltipSeparator = "\n";

	private static readonly HashSet<string> NoDamage = new HashSet<string> { "DrainBlood", "DarkAura", "Wolf", "Minions", "ElementalGolem", "Surtling" };

	private static bool HitLogOn
	{
		get
		{
			if (_log != null && _hitLog != null)
			{
				return _hitLog.Value;
			}
			return false;
		}
	}

	private static void InstallConduits(Harmony h)
	{
		if (_tryGetDemigod == null || _demigodName == null)
		{
			throw new MissingMethodException("needs Helper.TryGetDemigod (CurrentGod)");
		}
		Type type = _norse.GetType("NorseDemigods.Cache", throwOnError: true);
		FieldInfo field = type.GetField("OriginalItemSharedDataDictionary", BindingFlags.Static | BindingFlags.Public);
		if (field == null || field.FieldType != typeof(Dictionary<string, SharedData>))
		{
			throw new MissingFieldException(type.FullName, "OriginalItemSharedDataDictionary");
		}
		if (!(field.GetValue(null) is Dictionary<string, SharedData> originalShared))
		{
			throw new MissingFieldException(type.FullName, "OriginalItemSharedDataDictionary (null)");
		}
		Type type2 = _norse.GetType("NorseDemigods.DemigodAbility", throwOnError: true);
		PropertyInfo property = type2.GetProperty("Owner", BindingFlags.Instance | BindingFlags.Public);
		if (property == null || property.PropertyType != typeof(Player) || property.GetGetMethod() == null)
		{
			throw new MissingMemberException(type2.FullName, "Owner");
		}
		List<MethodInfo> list = new List<MethodInfo>();
		string[] executeDecided = ExecuteDecided;
		foreach (string text in executeDecided)
		{
			Type type3 = _norse.GetType("NorseDemigods.Abilities.Ability" + text, throwOnError: true);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type3, "Execute", Type.EmptyTypes, (Type[])null);
			if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(void))
			{
				throw new MissingMethodException(type3.FullName, "Execute()");
			}
			list.Add(methodInfo);
		}
		HarmonyMethod val = Hook("ConduitExecute");
		ResolveShares();
		_originalShared = originalShared;
		_conduitOwner = property;
		foreach (MethodInfo item in list)
		{
			h.Patch((MethodBase)item, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		_conduitsOn = true;
	}

	private static void ConduitExecute(object __instance, MethodBase __originalMethod)
	{
		if (!_conduitsOn || __instance == null || __originalMethod == null)
		{
			return;
		}
		string text = null;
		try
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && _conduitOwner.GetValue(__instance, null) == localPlayer)
			{
				text = NorseId(__originalMethod.DeclaringType);
				if (text != null)
				{
					bool weapon;
					ItemData item = DecideNow(localPlayer, GodIfUsed(localPlayer), text, out weapon);
					Decided[text] = new ConduitMark
					{
						Item = item,
						Weapon = weapon,
						Share = CastShare(text, localPlayer)
					};
				}
			}
		}
		catch (Exception e)
		{
			if (text != null)
			{
				Decided.Remove(text);
			}
			ConduitFailed(e);
		}
	}

	private static string GodIfUsed(Player player)
	{
		if ((_useConduits == null || !_useConduits.Value) && !HitLogOn)
		{
			return null;
		}
		return CurrentGod(player);
	}

	private static SharedData SharedOf(ItemData item)
	{
		if (item == null)
		{
			return null;
		}
		SharedData shared = item.m_shared;
		if (shared == null || shared.m_name == null || _originalShared == null)
		{
			return shared;
		}
		try
		{
			if (!Morphs.TryGetValue(shared, out var _))
			{
				return shared;
			}
			SharedData value2;
			return (_originalShared.TryGetValue(shared.m_name, out value2) && value2 != null) ? value2 : shared;
		}
		catch (Exception e)
		{
			ConduitFailed(e);
			return shared;
		}
	}

	private static ItemData ConduitFor(Player p, string god)
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		if (!_conduitsOn || (Object)(object)p == (Object)null || god == null)
		{
			return null;
		}
		try
		{
			if (!TryConduits(god, out var rules) || rules == null || rules.Count == 0)
			{
				return null;
			}
			ItemData currentWeapon = ((Humanoid)p).GetCurrentWeapon();
			SharedData val = SharedOf(currentWeapon);
			return (val != null && ConduitMatch(val.m_skillType, val.m_itemType, rules)) ? currentWeapon : null;
		}
		catch (Exception e)
		{
			ConduitFailed(e);
			return null;
		}
	}

	private static bool ConduitMatch(SkillType skill, ItemType type, IReadOnlyList<ConduitRule> rules)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		if (rules == null)
		{
			return false;
		}
		for (int i = 0; i < rules.Count; i++)
		{
			ConduitRule conduitRule = rules[i];
			if (conduitRule.Skill == skill && (!conduitRule.TwoHandedOnly || IsTwoHandedType(type)))
			{
				return true;
			}
		}
		return false;
	}

	private static bool IsTwoHandedType(ItemType type)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Invalid comparison between Unknown and I4
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		if ((int)type != 14)
		{
			return (int)type == 22;
		}
		return true;
	}

	private static SharedData SwapInOriginal(ItemData x)
	{
		if (x == null)
		{
			return null;
		}
		SharedData shared = x.m_shared;
		SharedData val = SharedOf(x);
		if (val != null)
		{
			x.m_shared = val;
		}
		return shared;
	}

	private static void RestoreShared(ItemData x, SharedData saved)
	{
		if (x != null && saved != null)
		{
			x.m_shared = saved;
		}
	}

	private static float AddHalfBase(ItemData x, ref HitData hit, float share)
	{
		//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_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		if (x == null || hit == null)
		{
			return 0f;
		}
		try
		{
			DamageTypes damage = x.GetDamage();
			float num = 0.5f * share * (((DamageTypes)(ref damage)).GetTotalDamage() - damage.m_chop - damage.m_pickaxe);
			if (!(num > 0f) || float.IsInfinity(num))
			{
				return 0f;
			}
			float num2 = ((DamageTypes)(ref hit.m_damage)).GetTotalDamage() - hit.m_damage.m_chop - hit.m_damage.m_pickaxe;
			if (!(num2 > 0f))
			{
				string text = ((_inNorseObject > 0) ? _objectAbility : NorseAbility());
				if (NoAddTypes.Add(text ?? "?") && _log != null)
				{
					_log.LogInfo((object)("Conduit +50% base damage not added to " + (text ?? "?") + ": its hit has no damage type to add it in (reported once per ability)."));
				}
				return 0f;
			}
			float chop = hit.m_damage.m_chop;
			float pickaxe = hit.m_damage.m_pickaxe;
			((DamageTypes)(ref hit.m_damage)).Modify(1f + num / num2);
			hit.m_damage.m_chop = chop;
			hit.m_damage.m_pickaxe = pickaxe;
			return num;
		}
		catch (Exception e)
		{
			ConduitFailed(e);
			return 0f;
		}
	}

	private static void ResolveShares()
	{
		try
		{
			_stormRateField = IntEntry("AbilityLightningStorm", "LightningStrikesPerSecond");
			_burnDurationField = IntEntry("AbilityBurningGround", "AbilityDuration");
			_sphereCountField = IntEntry("AbilityWaterSphere", "SphereCount");
			_infusedSphereField = IntEntry("AbilityWaterSphere", "InfusedSphereCount");
			Type type = _norse.GetType("NorseDemigods.Helper", throwOnError: true);
			MethodInfo method = type.GetMethod("AreAbilitiesInfused", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(Player) }, null);
			if (method != null && method.ReturnType == typeof(bool))
			{
				_infused = (Func<Player, bool>)Delegate.CreateDelegate(typeof(Func<Player, bool>), method);
			}
			Type type2 = _norse.GetType("NorseDemigods.Abilities.AbilityMinions", throwOnError: false);
			MethodInfo methodInfo = ((type2 != null) ? type2.GetMethod("GetActiveSkeletons", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null) : null);
			MethodInfo methodInfo2 = null;
			foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(type))
			{
				if (declaredMethod.Name == "TryGetDemigodAbility" && declaredMethod.IsGenericMethodDefinition && declaredMethod.GetParameters().Length == 2)
				{
					methodInfo2 = declaredMethod;
					break;
				}
			}
			if (methodInfo2 != null && methodInfo != null && methodInfo.ReturnType == typeof(int))
			{
				_minionsOf = methodInfo2.MakeGenericMethod(type2);
				_skeletons = methodInfo;
			}
		}
		catch (Exception e)
		{
			ShareFailed(e);
		}
		string text = ((_stormRateField == null) ? " LightningStrikesPerSecond (4 used)" : "") + ((_burnDurationField == null) ? " BurningGround AbilityDuration" : "") + ((_sphereCountField == null || _infusedSphereField == null || _infused == null) ? " WaterSphere counts" : "") + ((_minionsOf == null) ? " Sacrifice skeletons" : "");
		if (text.Length > 0 && _log != null)
		{
			_log.LogWarning((object)("Skipped (conduit +50% share; these hits take the whole +50%, Lightning Storm its default rate):" + text));
		}
	}

	private static FieldInfo IntEntry(string ability, string name)
	{
		Type type = _norse.GetType("NorseDemigods.Abilities." + ability, throwOnError: false);
		FieldInfo fieldInfo = ((type != null) ? type.GetField(name, BindingFlags.Static | BindingFlags.NonPublic) : null);
		if (!(fieldInfo != null) || !(fieldInfo.FieldType == typeof(ConfigEntry<int>)))
		{
			return null;
		}
		return fieldInfo;
	}

	private static int NorseInt(ref ConfigEntry<int> entry, FieldInfo field, int fallback)
	{
		if (entry == null && field != null)
		{
			entry = field.GetValue(null) as ConfigEntry<int>;
		}
		if (entry == null)
		{
			return fallback;
		}
		return entry.Value;
	}

	private static float TickShare(string ability)
	{
		if (ability == null)
		{
			return 1f;
		}
		if (ability == "LightningStorm")
		{
			int num = 4;
			try
			{
				num = NorseInt(ref _stormRate, _stormRateField, 4);
			}
			catch (Exception e)
			{
				ShareFailed(e);
			}
			if (num <= 0)
			{
				return 1f;
			}
			return 1f / (float)num / 5f;
		}
		if (!Shares.TryGetValue(ability, out var value))
		{
			return 1f;
		}
		return value;
	}

	private static float CastShare(string ability, Player p)
	{
		try
		{
			if (ability == "WaterSphere")
			{
				if (_infused == null)
				{
					return 1f;
				}
				int num = (_infused(p) ? NorseInt(ref _infusedSphere, _infusedSphereField, 0) : NorseInt(ref _sphereCount, _sphereCountField, 0));
				return (num > 1) ? (1f / (float)num) : 1f;
			}
			if (ability == "Sacrifice")
			{
				if (_minionsOf == null)
				{
					return 1f;
				}
				object[] array = new object[2] { p, null };
				int num2 = (((bool)_minionsOf.Invoke(null, array) && array[1] != null) ? ((int)_skeletons.Invoke(array[1], null)) : 0);
				return (num2 > 1) ? (1f / (float)num2) : 1f;
			}
			return TickShare(ability);
		}
		catch (Exception e)
		{
			ShareFailed(e);
			return 1f;
		}
	}

	private static float BurnShare(Aoe aoe)
	{
		try
		{
			if (aoe.m_hitAfterTtl)
			{
				return 1f;
			}
			float hitInterval = aoe.m_hitInterval;
			float num = NorseInt(ref _burnDuration, _burnDurationField, 0);
			if (!(hitInterval > 0f) || !(num > 0f))
			{
				return 1f;
			}
			int num2 = AoeHits(num, hitInterval);
			return (num2 > 1) ? (1f / (float)num2) : 1f;
		}
		catch (Exception e)
		{
			ShareFailed(e);
			return 1f;
		}
	}

	private static int AoeHits(float ttl, float interval)
	{
		return Mathf.CeilToInt(ttl / interval - 0.001f);
	}

	private static void ShareFailed(Exception e)
	{
		if (!_shareFailed && _log != null)
		{
			_shareFailed = true;
			_log.LogWarning((object)("Conduit +50% share not read, that hit used its fallback share (reported once): " + (e.InnerException ?? e).Message));
		}
	}

	private static bool IsWeaponDerived(string ability)
	{
		if (ability != null)
		{
			if (!WeaponDerived.Contains(ability))
			{
				return DerivedProcs.Contains(ability);
			}
			return true;
		}
		return false;
	}

	private static BuildKind BuildMode(bool resolved, bool conduit, bool weaponDerived)
	{
		if (resolved)
		{
			if (!conduit)
			{
				if (!weaponDerived)
				{
					return BuildKind.Gem;
				}
				return BuildKind.Weapon;
			}
			return BuildKind.Conduit;
		}
		return BuildKind.Gem;
	}

	private static ItemData DecideNow(Player p, string god, string ability, out bool weapon)
	{
		weapon = false;
		int num;
		object obj;
		if (_conduitsOn && _conduitFor != null)
		{
			num = (((Object)(object)p != (Object)null) ? 1 : 0);
			if (num != 0)
			{
				obj = ConduitFor(p, god);
				goto IL_002e;
			}
		}
		else
		{
			num = 0;
		}
		obj = null;
		goto IL_002e;
		IL_002e:
		ItemData val = (ItemData)obj;
		switch (BuildMode((byte)num != 0, val != null, ability != null && WeaponDerived.Contains(ability)))
		{
		case BuildKind.Conduit:
			return val;
		default:
			return null;
		case BuildKind.Weapon:
			try
			{
				ItemData currentWeapon = ((Humanoid)p).GetCurrentWeapon();
				weapon = currentWeapon != null;
				return currentWeapon;
			}
			catch (Exception e)
			{
				ConduitFailed(e);
				return null;
			}
		}
	}

	private static bool TryDecided(string ability, out ConduitMark mark)
	{
		mark = null;
		if (ability != null && Decided.TryGetValue(ability, out mark))
		{
			return mark != null;
		}
		return false;
	}

	private static void MarkConduit(Component projectile, Component aoe, string ability)
	{
		try
		{
			if (!((Object)(object)projectile == (Object)null) || !((Object)(object)aoe == (Object)null))
			{
				if (!TryDecided(ability, out var mark))
				{
					Player localPlayer = Player.m_localPlayer;
					bool weapon;
					ItemData item = DecideNow(localPlayer, GodIfUsed(localPlayer), ability, out weapon);
					mark = new ConduitMark
					{
						Item = item,
						Weapon = weapon
					};
				}
				SetConduit(projectile, mark);
				SetConduit(aoe, mark);
			}
		}
		catch (Exception e)
		{
			ConduitFailed(e);
		}
	}

	private static void SetConduit(Component target, ConduitMark mark)
	{
		if (target == null || mark == null)
		{
			return;
		}
		try
		{
			ConduitOf.Remove(target);
			ConduitOf.Add(target, mark);
		}
		catch (Exception e)
		{
			ConduitFailed(e);
		}
	}

	private static ConduitMark ConduitMarkOf(Component target)
	{
		if (target == null || !ConduitOf.TryGetValue(target, out var value))
		{
			return null;
		}
		return value;
	}

	private static string ConduitText(ItemData x)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		SharedData val = SharedOf(x);
		if (val == null)
		{
			return "";
		}
		return ((object)Unsafe.As<SkillType, SkillType>(ref val.m_skillType)/*cast due to .constrained prefix*/).ToString() + (IsTwoHandedType(val.m_itemType) ? ",2H" : "");
	}

	private static void ConduitFailed(Exception e)
	{
		if (!_conduitFailed && _log != null)
		{
			_conduitFailed = true;
			_log.LogWarning((object)("Conduit decision failed, the hit builds as a gem (reported once): " + (e.InnerException ?? e).Message));
		}
	}

	private static void GodListLoaded()
	{
		try
		{
			BindGods();
		}
		catch (Exception ex)
		{
			if (_log != null)
			{
				_log.LogWarning((object)("Per-god settings not bound from NorseDemigods' god list: " + ex.Message));
			}
		}
	}

	private static void BindGods()
	{
		if (_godList == null || _config == null || !(_godList.GetValue(null, null) is IEnumerable enumerable) || enumerable == _godsBoundFrom)
		{
			return;
		}
		_godsBoundFrom = enumerable;
		bool saveOnConfigSet = _config.SaveOnConfigSet;
		_config.SaveOnConfigSet = false;
		try
		{
			try
			{
				BindUseConduits();
			}
			catch (Exception ex)
			{
				if (_log != null)
				{
					_log.LogWarning((object)("[Conduits] Use conduits not bound, conduits stay off: " + ex.Message));
				}
			}
			foreach (object item in enumerable)
			{
				string text = ((item != null) ? (_godListName.GetValue(item, null) as string) : null);
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				try
				{
					BindConduitConfig(text);
				}
				catch (Exception ex2)
				{
					if (_log != null)
					{
						_log.LogWarning((object)("[Conduits] " + text + " not bound: " + ex2.Message));
					}
				}
			}
			int num = RemoveOldSkillSettings();
			if (num > 0 && _log != null)
			{
				_log.LogInfo((object)("removed " + num + " old skill settings; abilities now build as gems, or through [Conduits]"));
			}
			_config.Save();
		}
		finally
		{
			_config.SaveOnConfigSet = saveOnConfigSet;
		}
	}

	private static void BindControls(ConfigFile config)
	{
		_holdKey = config.Bind<bool>("Controls", "Hold key for god special attacks", false, "On: on the ground and while blocking, a god ability on the alternate attack only fires while you hold NorseDemigods' own \"Hotkey Ignore Special Attack\" key (Left Alt by default); without the key you get the item's own alternate attack, if it has one. Bare hands and fist weapons follow the same rule, so bare-hand spells such as Fireball also need the key. In the air, press jump again for the god's air ability (Soar, Combustion, Crush); the alternate attack in the air never starts a god's air ability. A god with no air ability follows the ground rule in the air too. Hraesvelgr's double jump comes first when NorseDemigods offers it, and a press it does not use for the double jump fires Soar; hold jump to charge Soar and let go to launch. Path of Valheiman's double jump and wall jump also come first: the god's air ability fires on the next press they do not use (except beside a ledge you could climb, where the god's air ability wins). Another mod's air jump (EpicLoot's double jump, for one) is no longer waited for unless you have Path of Valheiman's wall jump, so one press can start both. Pressing the alternate attack while Soar is charging does nothing, as in NorseDemigods. A jump press starts no air ability while building, during an attack, or with a bow in hand (in NorseDemigods a bow cannot start one either). Off (the default): NorseDemigods works as shipped, where holding that key skips the ability. A change applies from the next press, no restart needed.");
	}

	private static void BindUseConduits()
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected O, but got Unknown
		_useConduits = _config.Bind<bool>("Conduits", "Use conduits", false, new ConfigDescription("On: holding one of a god's listed weapons builds the ability's hit as an attack with that weapon, plus half its base damage. Off (the default): every hit a Norse ability makes itself builds as a Path of Valheiman gem spell, whatever is in hand. Either way, hits whose damage already comes from the weapon (Slash, Cleave, Whirlwind, Stagger, Infused Arrow's splash) build as an attack with the item in hand and never get the extra half. A change applies from the next cast, no restart needed.", (AcceptableValueBase)null, new object[1]
		{
			new ConfigurationManagerAttributes
			{
				Order = 1
			}
		}));
	}

	private static void BindConduitConfig(string god)
	{
		ConduitConfigDefaults.TryGetValue(god, out var value);
		ConfigEntry<string> entry = _config.Bind<string>("Conduits", god, (value != null) ? value[0] : "", "Weapon skills that act as " + god + "'s conduits" + ((value != null) ? (" (" + value[1] + ")") : "") + ": separated by commas, each optionally followed by (two-handed); skills are Swords, Knives, Clubs, Polearms, Spears, Axes, Bows, Crossbows, Unarmed, ElementalMagic, BloodMagic; empty means none.");
		_conduitRules[god] = ParseConduitConfig(god, entry.Value, out var _);
		if (_conduitEntries.ContainsKey(god))
		{
			return;
		}
		_conduitEntries[god] = entry;
		entry.SettingChanged += delegate
		{
			try
			{
				_conduitRules[god] = ParseConduitConfig(god, entry.Value, out var _);
			}
			catch (Exception)
			{
			}
		};
	}

	private static ConduitRule[] ParseConduitConfig(string god, string value, out int invalid)
	{
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		invalid = 0;
		List<ConduitRule> list = new List<ConduitRule>();
		if (string.IsNullOrEmpty(value))
		{
			return list.ToArray();
		}
		string[] array = value.Split(new char[1] { ',' });
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length == 0)
			{
				continue;
			}
			string text2 = text;
			bool flag = text2.EndsWith("(two-handed)", StringComparison.OrdinalIgnoreCase);
			if (flag)
			{
				text2 = text2.Substring(0, text2.Length - "(two-handed)".Length).Trim();
			}
			if (ConduitSkillNames.TryGetValue(text2, out var value2))
			{
				list.Add(new ConduitRule
				{
					Skill = value2,
					TwoHandedOnly = flag
				});
				continue;
			}
			invalid++;
			if (_log != null)
			{
				_log.LogWarning((object)("[Conduits] " + god + ": \"" + text + "\" is not a conduit skill; ignored."));
			}
		}
		return list.ToArray();
	}

	private static bool TryConduits(string god, out IReadOnlyList<ConduitRule> rules)
	{
		rules = null;
		ConfigEntry<bool> useConduits = _useConduits;
		if (useConduits == null || !useConduits.Value || string.IsNullOrEmpty(god))
		{
			return false;
		}
		if (!_conduitRules.TryGetValue(god, out var value) || value.Length == 0)
		{
			return false;
		}
		rules = value;
		return true;
	}

	private static int RemoveOldSkillSettings()
	{
		try
		{
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ConfigFile), "OrphanedEntries");
			Dictionary<ConfigDefinition, string> dictionary = ((propertyInfo != null) ? (propertyInfo.GetValue(_config, null) as Dictionary<ConfigDefinition, string>) : null);
			if (dictionary == null)
			{
				return 0;
			}
			List<ConfigDefinition> list = new List<ConfigDefinition>();
			foreach (ConfigDefinition key in dictionary.Keys)
			{
				if (key.Section == "Skill" || key.Section.StartsWith("Skill - ", StringComparison.Ordinal))
				{
					list.Add(key);
				}
			}
			foreach (ConfigDefinition item in list)
			{
				dictionary.Remove(item);
			}
			return list.Count;
		}
		catch (Exception ex)
		{
			if (_log != null)
			{
				_log.LogWarning((object)("Old [Skill] settings not removed: " + ex.Message));
			}
			return 0;
		}
	}

	private static void InstallControls(Harmony h)
	{
		Type type = _norse.GetType("NorseDemigods.Helper", throwOnError: true);
		Type type2 = _norse.GetType("NorseDemigods.DemigodAbility", throwOnError: true);
		MethodInfo method = type.GetMethod("TryGetSecondaryAttackAbility", BindingFlags.Static | BindingFlags.Public, null, new Type[3]
		{
			typeof(Player),
			typeof(SkillType),
			type2.MakeByRefType()
		}, null);
		if (method == null || method.ReturnType != typeof(bool))
		{
			throw new MissingMethodException(type.FullName, "TryGetSecondaryAttackAbility(Player, SkillType, out DemigodAbility)");
		}
		if (ShortcutPressed == null || HeldMainMethod == null || HeldShortcutMethod == null || KeepMethod == null)
		{
			throw new MissingMethodException("KeyboardShortcut.IsPressed or a Controls filter");
		}
		CountHoldEdits(PatchProcessor.GetOriginalInstructions((MethodBase)method, (ILGenerator)null));
		try
		{
			h.Patch((MethodBase)method, (HarmonyMethod)null, (HarmonyMethod)null, Hook("HoldKeyTranspiler"), (HarmonyMethod)null, (HarmonyMethod)null);
			_holdInstalled = true;
		}
		catch
		{
			try
			{
				h.Unpatch((MethodBase)method, (HarmonyPatchType)0, "avesatanas.povplus.norsedemigods");
			}
			catch (Exception)
			{
			}
			_holdInstalled = false;
			throw;
		}
	}

	private static bool IsGetKey(CodeInstruction c)
	{
		MethodInfo methodInfo = c.operand as MethodInfo;
		if (c.opcode == OpCodes.Call && methodInfo != null && methodInfo.Name == "GetKey" && methodInfo.DeclaringType != null && methodInfo.DeclaringType.FullName == "UnityEngine.Input" && methodInfo.ReturnType == typeof(bool) && methodInfo.GetParameters().Length == 1)
		{
			return methodInfo.GetParameters()[0].ParameterType == typeof(KeyCode);
		}
		return false;
	}

	private static bool IsShortcutPressed(CodeInstruction c)
	{
		if (c.opcode == OpCodes.Call)
		{
			return object.Equals(c.operand, ShortcutPressed);
		}
		return false;
	}

	private static void CountHoldEdits(IEnumerable<CodeInstruction> code)
	{
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		bool flag = true;
		foreach (CodeInstruction item in code)
		{
			FieldInfo fieldInfo = item.operand as FieldInfo;
			if (IsGetKey(item))
			{
				num++;
				flag = flag && num2 == 0;
			}
			else if (IsShortcutPressed(item))
			{
				num2++;
			}
			else if (item.opcode == OpCodes.Ret)
			{
				num3++;
			}
			else if (item.opcode == OpCodes.Ldsfld && fieldInfo != null && fieldInfo.Name == "HotkeyIgnoreSpecialAttack" && fieldInfo.DeclaringType != null && fieldInfo.DeclaringType.FullName == "NorseDemigods.Configs")
			{
				num4++;
			}
		}
		if (num != 1 || num2 != 1 || num3 != 1 || num4 != 2 || !flag)
		{
			throw new InvalidOperationException("TryGetSecondaryAttackAbility has an unexpected shape (GetKey " + num + ", IsPressed " + num2 + ", ret " + num3 + ", HotkeyIgnoreSpecialAttack " + num4 + (flag ? "" : ", IsPressed first") + "; expected 1, 1, 1, 2)");
		}
	}

	private static IEnumerable<CodeInstruction> HoldKeyTranspiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
	{
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Expected O, but got Unknown
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Expected O, but got Unknown
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Expected O, but got Unknown
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Expected O, but got Unknown
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Expected O, but got Unknown
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Expected O, but got Unknown
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Expected O, but got Unknown
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0185: Expected O, but got Unknown
		//IL_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Expected O, but got Unknown
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Expected O, but got Unknown
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		try
		{
			CountHoldEdits(list);
		}
		catch (Exception ex)
		{
			if (!_holdInstalled)
			{
				throw;
			}
			if (_log != null)
			{
				_log.LogWarning((object)("[Controls] Hold key for god special attacks stepped aside, another mod changed Norse's method; Norse decides as shipped: " + ex.Message));
			}
			return list;
		}
		int num = 0;
		int num2 = 0;
		for (int i = 0; i < list.Count; i++)
		{
			CodeInstruction val = list[i];
			if (IsGetKey(val) || IsShortcutPressed(val))
			{
				list.Insert(i + 1, new CodeInstruction(OpCodes.Ldarg_0, (object)null));
				list.Insert(i + 2, new CodeInstruction(OpCodes.Ldarg_1, (object)null));
				list.Insert(i + 3, new CodeInstruction(OpCodes.Call, (object)(IsGetKey(val) ? HeldMainMethod : HeldShortcutMethod)));
				i += 3;
				num++;
				num2++;
			}
			else if (val.opcode == OpCodes.Ret)
			{
				Label label = generator.DefineLabel();
				List<CodeInstruction> list2 = new List<CodeInstruction>
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null),
					new CodeInstruction(OpCodes.Ldarg_1, (object)null),
					new CodeInstruction(OpCodes.Ldarg_2, (object)null),
					new CodeInstruction(OpCodes.Ldind_Ref, (object)null),
					new CodeInstruction(OpCodes.Call, (object)KeepMethod),
					new CodeInstruction(OpCodes.Dup, (object)null),
					new CodeInstruction(OpCodes.Brtrue, (object)label),
					new CodeInstruction(OpCodes.Ldarg_2, (object)null),
					new CodeInstruction(OpCodes.Ldnull, (object)null),
					new CodeInstruction(OpCodes.Stind_Ref, (object)null)
				};
				list2[0].labels.AddRange(val.labels);
				val.labels.Clear();
				val.labels.Add(label);
				list.InsertRange(i, list2);
				i += list2.Count;
				num++;
			}
		}
		if (num != 3 || num2 != 2)
		{
			throw new InvalidOperationException("TryGetSecondaryAttackAbility: " + num2 + " key reads and " + (num - num2) + " returns edited, expected 2 and 1");
		}
		_holdEdits = num2;
		return list;
	}

	private static bool Reversed(Player player, SkillType skill)
	{
		ConfigEntry<bool> holdKey = _holdKey;
		if (holdKey != null && holdKey.Value && player != null)
		{
			return player == Player.m_localPlayer;
		}
		return false;
	}

	private static bool HeldMain(bool held, Player player, SkillType skill)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		_keyHeld = held;
		if (held)
		{
			return !Reversed(player, skill);
		}
		return false;
	}

	private static bool HeldShortcut(bool held, Player player, SkillType skill)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		_keyHeld |= held;
		if (held)
		{
			return !Reversed(player, skill);
		}
		return false;
	}

	private static bool KeepAbility(bool found, Player player, SkillType skill, object ability)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		if (!found || !Reversed(player, skill))
		{
			return found;
		}
		if (!_jumpInstalled)
		{
			return _keyHeld;
		}
		if (_typeFailed)
		{
			if (!_jumpCast)
			{
				return _keyHeld;
			}
			return false;
		}
		bool flag;
		bool result;
		try
		{
			flag = _abilityType(ability) == _airType;
			result = flag && !_jumpCast && _isChanneled(ability) && _isActive(ability);
		}
		catch (Exception ex)
		{
			if (_log != null)
			{
				_log.LogWarning((object)("[Controls] could not read a god ability's type; from now on every god ability on the alternate attack needs the held key, and a jump press starts none: " + ex.Message));
			}
			_typeFailed = true;
			return !_jumpCast && _keyHeld;
		}
		if (_jumpCast)
		{
			return flag;
		}
		if (!flag)
		{
			return _keyHeld;
		}
		return result;
	}

	private static void JumpBegin(Character __instance, out bool __state)
	{
		__state = false;
		if ((object)__instance != Player.m_localPlayer || _jumpCast || _jumpFailed || !_jumpInstalled)
		{
			return;
		}
		ConfigEntry<bool> holdKey = _holdKey;
		if (holdKey == null || !holdKey.Value)
		{
			return;
		}
		_inJump++;
		try
		{
			__state = !__instance.IsOnGround();
		}
		catch (Exception e)
		{
			JumpFailed(e);
		}
	}

	private static void JumpEnd(Character __instance, bool __state, bool __runOriginal)
	{
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Expected O, but got Unknown
		if (_inJump > 0 && (object)__instance == Player.m_localPlayer)
		{
			_inJump--;
		}
		if (!__state || !__runOriginal)
		{
			return;
		}
		int num = (_airJumpHooked ? AirJumpKind() : 0);
		if (num == 1 && AirJumpTookPress(_airJumpAt, Time.fixedTime, Time.fixedDeltaTime))
		{
			return;
		}
		if (num != 2)
		{
			try
			{
				CastFromJump((Player)__instance);
				return;
			}
			catch (Exception e)
			{
				JumpFailed(e);
				return;
			}
		}
		_pending = true;
		_pendingFrame = Time.frameCount;
		_pendingAt = Time.fixedTime;
		_pendingReal = Time.realtimeSinceStartup;
	}

	private static int AirJumpKind()
	{
		Func<string, bool> statHas = _statHas;
		if (statHas == null)
		{
			return 2;
		}
		try
		{
			return statHas("WallJump") ? 2 : (statHas("DoubleJump") ? 1 : 0);
		}
		catch (Exception ex)
		{
			_statHas = null;
			if (_log != null)
			{
				_log.LogWarning((object)("[Controls] could not read Path of Valheiman's double jump and wall jump; from now on a jump press in the air waits for them as before: " + ex.Message));
			}
			return 2;
		}
	}

	private static void AirJumped(Character __instance, bool effects)
	{
		if ((object)__instance == Player.m_localPlayer && effects && _inJump <= 0 && !_jumpCast && _jumpInstalled)
		{
			ConfigEntry<bool> holdKey = _holdKey;
			if (holdKey != null && holdKey.Value)
			{
				_airJumpAt = Time.fixedTime;
			}
		}
	}

	private void FixedUpdate()
	{
		_inJump = 0;
		if (!_pending || Time.frameCount < _pendingFrame + 2)
		{
			return;
		}
		_pending = false;
		if (AirJumpTookPress(_airJumpAt, _pendingAt, Time.fixedDeltaTime) || Time.realtimeSinceStartup - _pendingReal > 0.5f)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		ConfigEntry<bool> holdKey = _holdKey;
		if ((Object)(object)localPlayer == (Object)null || holdKey == null || !holdKey.Value || !_jumpInstalled)
		{
			return;
		}
		try
		{
			if (_takeInput((Character)(object)localPlayer))
			{
				CastFromJump(localPlayer);
			}
		}
		catch (Exception e)
		{
			JumpFailed(e);
		}
	}

	private static void CastFromJump(Player player)
	{
		if (((Character)player).InAttack() || ((Character)player).InPlaceMode())
		{
			return;
		}
		SharedData val = SharedOf(((Humanoid)player).GetCurrentWeapon());
		if (val != null && val.m_attack != null && val.m_attack.m_bowDraw)
		{
			return;
		}
		_jumpCast = true;
		try
		{
			ProbeArgs[0] = player;
			ProbeArgs[1] = NoSkill;
			ProbeArgs[2] = null;
			if ((bool)_tryGetAbility.Invoke(null, ProbeArgs))
			{
				object obj = ProbeArgs[2];
				if (_abilityType(obj) == _airType && ((Character)player).StartAttack((Character)null, true) && _isChanneled(obj) && _isActive(obj))
				{
					_jumpChannel = obj;
				}
			}
		}
		finally
		{
			_jumpCast = false;
			ProbeArgs[0] = null;
			ProbeArgs[2] = null;
		}
	}

	private void Update()
	{
		if (_jumpChannel == null)
		{
			return;
		}
		object jumpChannel = _jumpChannel;
		try
		{
			if (!_isActive(jumpChannel))
			{
				_jumpChannel = null;
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && _takeInput((Character)(object)localPlayer) && !_button("Jump") && !_button("JoyJump"))
			{
				_jumpChannel = null;
				if (_isChanneled(jumpChannel))
				{
					_stopAbility(jumpChannel, arg2: true);
				}
			}
		}
		catch (Exception e)
		{
			_jumpChannel = null;
			JumpFailed(e);
		}
	}

	private static bool AirJumpTookPress(float airJumpAt, float pressAt, float step)
	{
		return airJumpAt >= pressAt - 2.5f * step;
	}

	private static void JumpFailed(Exception e)
	{
		if (!_jumpFailed)
		{
			_jumpFailed = true;
			_jumpInstalled = false;
			if (_log != null)
			{
				_log.LogWarning((object)("[Controls] the jump press for god air abilities stopped after an error; in the air the held key starts them again: " + e));
			}
		}
	}

	private static void InstallJumpCast(Harmony h)
	{
		if (!_holdInstalled)
		{
			throw new InvalidOperationException("needs the hold-key part (see its Skipped line)");
		}
		Type type = _norse.GetType("NorseDemigods.DemigodAbility", throwOnError: true);
		Type type2 = _norse.GetType("NorseDemigods.Helper", throwOnError: true);
		MethodInfo method = type2.GetMethod("TryGetSecondaryAttackAbility", BindingFlags.Static | BindingFlags.Public, null, new Type[3]
		{
			typeof(Player),
			typeof(SkillType),
			type.MakeByRefType()
		}, null);
		if (method == null || method.ReturnType != typeof(bool))
		{
			throw new MissingMethodException(type2.FullName, "TryGetSecondaryAttackAbility(Player, SkillType, out DemigodAbility)");
		}
		PropertyInfo propertyInfo = AccessTools.Property(type, "AbilityParameters");
		MethodInfo methodInfo = ((propertyInfo != null) ? propertyInfo.GetGetMethod(nonPublic: true) : null);
		FieldInfo fieldInfo = ((methodInfo != null && methodInfo.ReturnType.IsValueType) ? AccessTools.Field(methodInfo.ReturnType, "AbilityType") : null);
		if (fieldInfo == null || !fieldInfo.FieldType.IsEnum || Enum.GetUnderlyingType(fieldInfo.FieldType) != typeof(int))
		{
			throw new MissingFieldException(type.FullName, "AbilityParameters.AbilityType");
		}
		int airType = Convert.ToInt32(Enum.Parse(fieldInfo.FieldType, "SPECIAL_ATTACK_AIR"));
		Func<object, bool> isChanneled = Getter(type, "IsChanneled");
		Func<object, bool> isActive = Getter(type, "IsActive");
		MethodInfo methodInfo2 = AccessTools.Method(type, "Stop", new Type[1] { typeof(bool) }, (Type[])null);
		if (methodInfo2 == null || methodInfo2.IsStatic)
		{
			throw new MissingMethodException(type.FullName, "Stop(bool)");
		}
		Type type3 = Type.GetType("ZInput, assembly_utils", throwOnError: false) ?? typeof(Player).Assembly.GetType("ZInput", throwOnError: false);
		MethodInfo methodInfo3 = ((type3 != null) ? type3.GetMethod("GetButton", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null) : null);
		if (methodInfo3 == null || methodInfo3.ReturnType != typeof(bool))
		{
			throw new MissingMethodException("ZInput", "GetButton(string)");
		}
		MethodInfo methodInfo4 = AccessTools.Method(typeof(Character), "Jump", new Type[1] { typeof(bool) }, (Type[])null);
		if (methodInfo4 == null)
		{
			throw new MissingMethodException(typeof(Character).FullName, "Jump(bool)");
		}
		MethodInfo methodInfo5 = AccessTools.Method(typeof(Character), "TakeInput", Type.EmptyTypes, (Type[])null);
		if (methodInfo5 == null || methodInfo5.IsStatic || methodInfo5.ReturnType != typeof(bool))
		{
			throw new MissingMethodException(typeof(Character).FullName, "TakeInput()");
		}
		Func<Character, bool> takeInput = AccessTools.MethodDelegate<Func<Character, bool>>(methodInfo5, (object)null, true);
		MethodInfo method2 = typeof(Character).GetMethod("ForceJump", BindingFlags.Instance | BindingFlags.Public, null, new Type[2]
		{
			typeof(Vector3),
			typeof(bool)
		}, null);
		DynamicMethod dynamicMethod = new DynamicMethod("PoVPlusNorseAbilityType", typeof(int), new Type[1] { typeof(object) }, typeof(Plugin), skipVisibility: true);
		ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
		LocalBuilder local = iLGenerator.DeclareLocal(methodInfo.ReturnType);
		iLGenerator.Emit(OpCodes.Ldarg_0);
		iLGenerator.Emit(OpCodes.Castclass, type);
		iLGenerator.Emit(OpCodes.Callvirt, methodInfo);
		iLGenerator.Emit(OpCodes.Stloc, local);
		iLGenerator.Emit(OpCodes.Ldloca, local);
		iLGenerator.Emit(OpCodes.Ldfld, fieldInfo);
		iLGenerator.Emit(OpCodes.Ret);
		DynamicMethod dynamicMethod2 = new DynamicMethod("PoVPlusNorseAbilityStop", null, new Type[2]
		{
			typeof(object),
			typeof(bool)
		}, typeof(Plugin), skipVisibility: true);
		ILGenerator iLGenerator2 = dynamicMethod2.GetILGenerator();
		iLGenerator2.Emit(OpCodes.Ldarg_0);
		iLGenerator2.Emit(OpCodes.Castclass, type);
		iLGenerator2.Emit(OpCodes.Ldarg_1);
		iLGenerator2.Emit(OpCodes.Callvirt, methodInfo2);
		iLGenerator2.Emit(OpCodes.Ret);
		HarmonyMethod val = Hook("JumpBegin");
		val.priority = 800;
		HarmonyMethod val2 = Hook("JumpEnd");
		_abilityType = (Func<object, int>)dynamicMethod.CreateDelegate(typeof(Func<object, int>));
		_airType = airType;
		_isChanneled = isChanneled;
		_isActive = isActive;
		_stopAbility = (Action<object, bool>)dynamicMethod2.CreateDelegate(typeof(Action<object, bool>));
		_button = (Func<string, bool>)Delegate.CreateDelegate(typeof(Func<string, bool>), methodInfo3);
		_tryGetAbility = method;
		_takeInput = takeInput;
		try
		{
			h.Patch((MethodBase)methodInfo4, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch
		{
			try
			{
				h.Unpatch((MethodBase)methodInfo4, (HarmonyPatchType)0, "avesatanas.povplus.norsedemigods");
			}
			catch (Exception)
			{
			}
			throw;
		}
		if (method2 == null)
		{
			_log.LogWarning((object)"[Controls] Path of Valheiman's double jump and wall jump are not given the press first; a jump press in the air casts the god's air ability at once (Character.ForceJump(Vector3, bool) not found).");
		}
		else
		{
			try
			{
				h.Patch((MethodBase)method2, (HarmonyMethod)null, Hook("AirJumped"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_airJumpHooked = true;
			}
			catch (Exception ex2)
			{
				try
				{
					h.Unpatch((MethodBase)method2, (HarmonyPatchType)0, "avesatanas.povplus.norsedemigods");
				}
				catch (Exception)
				{
				}
				_log.LogWarning((object)("[Controls] Path of Valheiman's double jump and wall jump are not given the press first; a jump press in the air casts the god's air ability at once (" + ex2.Message + ")."));
			}
		}
		_jumpInstalled = true;
	}

	private static Func<object, bool> Getter(Type type, string name)
	{
		PropertyInfo propertyInfo = AccessTools.Property(type, name);
		MethodInfo methodInfo = ((propertyInfo != null && propertyInfo.PropertyType == typeof(bool)) ? propertyInfo.GetGetMethod(nonPublic: true) : null);
		if (methodInfo == null || methodInfo.IsStatic)
		{
			throw new MissingMemberException(type.FullName, name);
		}
		DynamicMethod dynamicMethod = new DynamicMethod("PoVPlusNorse" + name, typeof(bool), new Type[1] { typeof(object) }, typeof(Plugin), skipVisibility: true);
		ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
		iLGenerator.Emit(OpCodes.Ldarg_0);
		iLGenerator.Emit(OpCodes.Castclass, type);
		iLGenerator.Emit(OpCodes.Callvirt, methodInfo);
		iLGenerator.Emit(OpCodes.Ret);
		return (Func<object, bool>)dynamicMethod.CreateDelegate(typeof(Func<object, bool>));
	}

	private static void ResolveBuildState(Assembly pov, Type affixes)
	{
		Type type = pov.GetType("PassiveTree.WeaponProfile", throwOnError: true);
		Type type2 = pov.GetType("PassiveTree.WeaponKind", throwOnError: true);
		Type type3 = pov.GetType("PassiveTree.WeaponGroup", throwOnError: true);
		Type type4 = pov.GetType("PassiveTree.CombatCategory", throwOnError: true);
		Type type5 = pov.GetType("PassiveTree.HitContext", throwOnError: true);
		Type type6 = pov.GetType("PassiveTree.HitTag", throwOnError: true);
		FieldInfo fieldInfo = AccessTools.Field(affixes, "ProfileOverride");
		if (fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(Nullable<>).MakeGenericType(type))
		{
			throw new MissingFieldException(affixes.FullName, "ProfileOverride");
		}
		FieldInfo fieldInfo2 = AccessTools.Field(affixes, "Override");
		if (fieldInfo2 == null || !fieldInfo2.IsStatic || fieldInfo2.FieldType != typeof(ItemData))
		{
			throw new MissingFieldException(affixes.FullName, "Override");
		}
		ConstructorInfo constructorInfo = AccessTools.Constructor(type, new Type[3] { type2, type3, type4 }, false);
		if (constructorInfo == null)
		{
			throw new MissingMethodException(type.FullName, ".ctor(WeaponKind, WeaponGroup, CombatCategory)");
		}
		MethodInfo methodInfo = AccessTools.Method(type5, "Replace", new Type[1] { type6 }, (Type[])null);
		if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != type6)
		{
			throw new MissingMethodException(type5.FullName, "Replace");
		}
		MethodInfo methodInfo2 = AccessTools.Method(type5, "Pop", new Type[1] { type6 }, (Type[])null);
		if (methodInfo2 == null || !methodInfo2.IsStatic)
		{
			throw new MissingMethodException(type5.FullName, "Pop");
		}
		MethodInfo methodInfo3 = AccessTools.Method(type5, "Push", new Type[1] { type6 }, (Type[])null);
		if (methodInfo3 == null || !methodInfo3.IsStatic || methodInfo3.ReturnType != type6)
		{
			throw new MissingMethodException(type5.FullName, "Push");
		}
		object noTags = EnumValue(type6, "None");
		object obj = EnumValue(type6, "Area");
		object obj2 = EnumValue(type6, "Gem");
		object gemAreaTag = Enum.ToObject(type6, Convert.ToInt64(obj2) | Convert.ToInt64(obj));
		_gemProfile = constructorInfo.Invoke(new object[3]
		{
			EnumValue(type2, "None"),
			EnumValue(type3, "None"),
			EnumValue(type4, "Spell")
		});
		_gemTag = obj2;
		_gemAreaTag = gemAreaTag;
		_noTags = noTags;
		_areaTag = obj;
		_tagsPush = methodInfo3;
		_tagsReplace = methodInfo;
		_tagsPop = methodInfo2;
		_weaponOverride = fieldInfo2;
		_profileOverride = fieldInfo;
		ResolveConduitBuild(pov, affixes);
	}

	private static object EnumValue(Type type, string name)
	{
		if (!Enum.IsDefined(type, name))
		{
			throw new MissingMemberException(type.FullName, name);
		}
		return Enum.Parse(type, name);
	}

	private static void MorphIsSpell(Attack __0, ref object __result)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		if (__0 != null && !((Object)(object)AttackOwner.Invoke(__0) != (Object)(object)Player.m_localPlayer))
		{
			ItemData weapon = __0.GetWeapon();
			if (weapon != null && weapon.m_shared != null && (int)weapon.m_shared.m_skillType == 0 && Morphs.TryGetValue(weapon.m_shared, out var value) && value != "PoisonJavelin")
			{
				__result = _spellCategory;
			}
		}
	}

	private static void MorphBegin(StatusEffect __instance, ref SkillType __0, ref HitData __1, out MorphState __state)
	{
		//IL_002b: 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_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Expected I4, but got Unknown
		//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
		__state = null;
		Player localPlayer = Player.m_localPlayer;
		if (__1 == null || (Object)(object)localPlayer == (Object)null || (Object)(object)__instance.m_character != (Object)(object)localPlayer)
		{
			return;
		}
		if (__0 || (int)__1.m_skill != 0)
		{
			if (_building == 0)
			{
				__state = MeasureOnly(localPlayer, __0, __1);
			}
		}
		else
		{
			if (_building > 0 || BuildInProgress())
			{
				return;
			}
			ItemData currentWeapon = ((Humanoid)localPlayer).GetCurrentWeapon();
			if (currentWeapon == null || currentWeapon.m_shared == null || (int)currentWeapon.m_shared.m_skillType != 0 || !Morphs.TryGetValue(currentWeapon.m_shared, out var value))
			{
				return;
			}
			MorphState morphState = (__state = new MorphState
			{
				Built = true,
				Ability = value,
				Shape = ShapeOf(value),
				Build = new BuildState()
			});
			ResetMorphDamage(currentWeapon, __1);
			morphState.Before = __1.GetTotalDamage();
			string god = GodIfUsed(localPlayer);
			bool flag = (morphState.Shape & Shape.Area) != 0;
			object obj = null;
			ItemData val = ((_conduitsOn && _conduitFor != null) ? ConduitFor(localPlayer, god) : null);
			if (val != null)
			{
				morphState.Shared = SwapInOriginal(val);
				morphState.Conduit = val;
				obj = ConduitProfile(val, __1.m_ranged, localPlayer);
				if (obj == null)
				{
					RestoreShared(val, morphState.Shared);
					morphState.Conduit = null;
				}
			}
			morphState.Profile = ((morphState.Conduit != null) ? obj : _gemProfile);
			if (morphState.Conduit != null)
			{
				Enter(morphState.Build, obj, val, flag ? _areaTag : null);
				if (!morphState.Build.Saved)
				{
					RestoreShared(val, morphState.Shared);
					morphState.Conduit = null;
					morphState.Profile = _gemProfile;
				}
			}
			if (morphState.Conduit != null)
			{
				__0 = (SkillType)(int)ConduitSkill(val);
				__1.m_skill = __0;
				if (!IsWeaponDerived(value))
				{
					morphState.Add = AddHalfBase(val, ref __1, 1f);
				}
			}
			else
			{
				Enter(morphState.Build, _gemProfile, null, flag ? _gemAreaTag : _gemTag);
			}
			if (HitLogOn)
			{
				try
				{
					morphState.Line = HitHead("morph", value, god, localPlayer, TargetOf(__1), __0);
				}
				catch (Exception e)
				{
					LogFailed(e);
				}
			}
			if ((morphState.Shape & Shape.Projectile) != Shape.None && (__1.m_damage.m_chop > 0f || __1.m_damage.m_pickaxe > 0f))
			{
				morphState.Chop = __1.m_damage.m_chop;
				morphState.Pickaxe = __1.m_damage.m_pickaxe;
				__1.m_damage.m_chop = 0f;
				__1.m_damage.m_pickaxe = 0f;
				morphState.TreeHeld = true;
			}
		}
	}

	private static void MorphEnd(ref HitData __1, MorphState __state)
	{
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		if (__state == null)
		{
			return;
		}
		if (__state.Conduit != null)
		{
			RestoreShared(__state.Conduit, __state.Shared);
		}
		if (__state.Build != null)
		{
			Leave(__state.Build);
		}
		if (__1 == null)
		{
			return;
		}
		if (__state.TreeHeld)
		{
			RestoreTree(__state, __1);
		}
		if (__state.Built && __state.Build != null && __state.Build.Saved)
		{
			MarkLanding(__1, __state.Profile);
			if (_semanDepth > 0)
			{
				_marked = __1;
				_markedProfile = __state.Profile;
				_markedDepth = _semanDepth;
			}
		}
		if (__state.Built)
		{
			__1.m_skill = (SkillType)0;
		}
		Measure(__state.Ability, __state.Before, __1);
		if (__state.Line == null || !HitLogOn)
		{
			return;
		}
		bool area = (__state.Shape & Shape.Area) != Shape.None && __state.Build != null && __state.Build.Tags != null;
		try
		{
			_log.LogInfo((object)("[hit] " + __state.Line + HitTail(__1, __state.Before, __1.m_ranged, TagText(area, __state.Shape, __1.m_ranged), __state.Built ? ModeText(__state.Conduit, __state.Add) : "weapon", __state.TreeHeld)));
		}
		catch (Exception e)
		{
			LogFailed(e);
		}
	}

	private static bool BuildInProgress()
	{
		try
		{
			return _profileOverride.GetValue(null) != null;
		}
		catch (Exception e)
		{
			StateFailed(e);
			return false;
		}
	}

	private static void ResetMorphDamage(ItemData weapon, HitData hit)
	{
		//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_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: 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)
		try
		{
			DamageTypes damage = weapon.GetDamage();
			float totalDamage = ((DamageTypes)(ref damage)).GetTotalDamage();
			if (!(totalDamage <= 0f))
			{
				float num = hit.GetTotalDamage() / totalDamage;
				if (!float.IsNaN(num) && !float.IsInfinity(num))
				{
					DamageTypes damages = weapon.m_shared.m_damages;
					((DamageTypes)(ref damages)).Modify(num);
					hit.m_damage = damages;
				}
			}
		}
		catch (Exception e)
		{
			StateFailed(e);
		}
	}

	private static void RestoreTree(MorphState state, HitData hit)
	{
		float mult = 1f;
		try
		{
			if (!BudgetMult(hit, out mult))
			{
				float num = state.Before + state.Add - state.Chop - state.Pickaxe;
				mult = ((num > 0f) ? (hit.GetTotalDamage() / num) : 1f);
			}
			if (float.IsNaN(mult) || float.IsInfinity(mult) || mult < 0f)
			{
				mult = 1f;
			}
		}
		catch (Exception e)
		{
			mult = 1f;
			TreeFailed(e);
		}
		hit.m_damage.m_chop = state.Chop * mult;
		hit.m_damage.m_pickaxe = state.Pickaxe * mult;
	}

	private static bool BudgetMult(HitData hit, out float mult)
	{
		mult = 1f;
		if (_budgetFind == null || _budgets == null)
		{
			return false;
		}
		object[] array = new object[2] { hit, null };
		if (!(bool)_budgetFind.Invoke(_budgets, array) || array[1] == null)
		{
			return false;
		}
		if (_budgetMult == null)
		{
			_budgetMult = array[1].GetType().GetField("Mult");
		}
		if (_budgetMult == null || _budgetMult.FieldType != typeof(float))
		{
			return false;
		}
		mult = (float)_budgetMult.GetValue(array[1]);
		return true;
	}

	private static void TreeFailed(Exception e)
	{
		if (!_treeFailed && _log != null)
		{
			_treeFailed = true;
			_log.LogWarning((object)("Norse spell tree damage put back without Path of Valheiman's multiplier (reported once): " + (e.InnerException ?? e).Message));
		}
	}

	private static MorphState MeasureOnly(Player player, SkillType skill, HitData hit)
	{
		//IL_0018: 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_0026: 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)
		try
		{
			ItemData currentWeapon = ((Humanoid)player).GetCurrentWeapon();
			if (currentWeapon == null || currentWeapon.m_shared == null || (int)currentWeapon.m_shared.m_skillType == 0 || skill != currentWeapon.m_shared.m_skillType)
			{
				return null;
			}
			Attack val = CurrentAttack.Invoke((Humanoid)(object)player);
			if (val == null || val.GetWeapon() != currentWeapon)
			{
				return null;
			}
			if (!Morphs.TryGetValue(currentWeapon.m_shared, out var value) || string.IsNullOrEmpty(value) || value[0] == '@')
			{
				return null;
			}
			float totalDamage = hit.GetTotalDamage();
			if (totalDamage <= 0f)
			{
				return null;
			}
			MorphState morphState = new MorphState
			{
				Built = false,
				Ability = value,
				Before = totalDamage
			};
			if (HitLogOn)
			{
				try
				{
					morphState.Line = HitHead("morph measured-only", value, CurrentGod(player), player, TargetOf(hit), skill);
				}
				catch (Exception e)
				{
					LogFailed(e);
				}
			}
			return morphState;
		}
		catch (Exception e2)
		{
			MeasureFailed(e2);
			return null;
		}
	}

	private static void InstallLanding(Harmony h, Type crits)
	{
		if (crits == null)
		{
			throw new TypeLoadException("PassiveTree.CriticalHits");
		}
		FieldInfo field = crits.GetField("shots", BindingFlags.Static | BindingFlags.NonPublic);
		object obj = ((field != null) ? field.GetValue(null) : null);
		MethodInfo methodInfo = obj?.GetType().GetMethod("TryGetValue");
		if (methodInfo == null || methodInfo.GetParameters().Length != 2 || methodInfo.GetParameters()[0].ParameterType != typeof(Projectile))
		{
			throw new MissingFieldException(crits.FullName, "shots");
		}
		Type elementType = methodInfo.GetParameters()[1].ParameterType.GetElementType();
		FieldInfo fieldInfo = ((elementType != null && !elementType.IsValueType) ? elementType.GetField("Weapon") : null);
		if (fieldInfo == null || _gemProfile == null || fieldInfo.FieldType != _gemProfile.GetType())
		{
			throw new MissingFieldException("CriticalHits.Budget", "Weapon");
		}
		MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Projectile), "Setup", (Type[])null, (Type[])null);
		if (methodInfo2 == null)
		{
			throw new MissingMethodException(typeof(Projectile).FullName, "Setup");
		}
		MethodInfo methodInfo3 = AccessTools.Method(typeof(SEMan), "ModifyAttack", new Type[2]
		{
			typeof(SkillType),
			typeof(HitData).MakeByRefType()
		}, (Type[])null);
		if (methodInfo3 == null)
		{
			throw new MissingMethodException(typeof(SEMan).FullName, "ModifyAttack(SkillType, ref HitData)");
		}
		HarmonyMethod val = Hook("MorphLanding");
		val.priority = 0;
		_shots = obj;
		_shotWeapon = fieldInfo;
		h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)methodInfo3, Hook("ModifyAttackBegin"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("ModifyAttackEnd"), (HarmonyMethod)null);
		_shotFind = methodInfo;
	}

	private static void ModifyAttackBegin(out bool __state)
	{
		_semanDepth++;
		__state = true;
	}

	private static void ModifyAttackEnd(ref HitData __1, bool __state)
	{
		int semanDepth = _semanDepth;
		if (__state && _semanDepth > 0)
		{
			_semanDepth--;
		}
		if (!__state || _marked == null || semanDepth > _markedDepth)
		{
			return;
		}
		try
		{
			if (__1 != null && __1 != _marked)
			{
				if (_copyBudget != null)
				{
					_copyBudget.Invoke(null, new object[2] { _marked, __1 });
				}
				MarkLanding(__1, _markedProfile);
			}
		}
		catch (Exception e)
		{
			LandingFailed(e);
		}
		finally
		{
			_marked = null;
			_markedProfile = null;
			_markedDepth = 0;
		}
	}

	private static void MarkLanding(HitData hit, object profile)
	{
		if (_shotFind == null || hit == null || profile == null)
		{
			return;
		}
		try
		{
			MorphProfiles.Remove(hit);
			MorphProfiles.Add(hit, profile);
		}
		catch (Exception e)
		{
			LandingFailed(e);
		}
	}

	private static void MorphLanding(Projectile __instance, HitData ___m_originalHitData)
	{
		if (___m_originalHitData == null || _shotFind == null || !MorphProfiles.TryGetValue(___m_originalHitData, out var value))
		{
			return;
		}
		try
		{
			object[] array = new object[2] { __instance, null };
			if ((bool)_shotFind.Invoke(_shots, array) && array[1] != null)
			{
				_shotWeapon.SetValue(array[1], value);
			}
		}
		catch (Exception e)
		{
			LandingFailed(e);
		}
	}

	private static void LandingFailed(Exception e)
	{
		if (!_landingFailed && _log != null)
		{
			_landingFailed = true;
			_log.LogWarning((object)("A morph spell's landing crit kept Path of Valheiman's profile (reported once): " + (e.InnerException ?? e).Message));
		}
	}

	private static void MorphMapped(SharedData __result, Type __1)
	{
		string text = NorseId(__1);
		if (__result != null && text != null && !Morphs.TryGetValue(__result, out var _))
		{
			Morphs.Add(__result, text);
			if (!MorphSeen.ContainsKey(text))
			{
				MorphSeen[text] = __result;
			}
		}
	}

	private static void BuildAbilityHit(Character __instance, ref HitData hit, out int __state)
	{
		//IL_035a: Unknown result type (might be due to invalid IL or missing references)
		//IL_035c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0332: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02de: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
		__state = 0;
		if (hit == null)
		{
			return;
		}
		float totalDamage = hit.GetTotalDamage();
		if (totalDamage <= 0f)
		{
			return;
		}
		if (_delivering > 0)
		{
			if ((_inVictimDamage <= 0 || !SkipDerived(__instance, hit)) && HitLogOn)
			{
				LogSkip(__instance, hit, null, "in delivery");
			}
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || (Object)(object)__instance == (Object)(object)localPlayer || (Object)(object)hit.GetAttacker() != (Object)(object)localPlayer)
		{
			return;
		}
		if (!BaseAI.IsEnemy((Character)(object)localPlayer, __instance))
		{
			if (HitLogOn)
			{
				LogSkip(__instance, hit, null, "not enemy");
			}
			return;
		}
		string text = ((_inNorseObject > 0) ? _objectAbility : NorseAbility());
		if (_inNorseObject == 0 && text == null)
		{
			return;
		}
		StatusEffect val = null;
		foreach (StatusEffect statusEffect in ((Character)localPlayer).GetSEMan().GetStatusEffects())
		{
			if (_povEffect.IsInstanceOfType(statusEffect))
			{
				val = statusEffect;
				break;
			}
		}
		if ((Object)(object)val == (Object)null)
		{
			if (HitLogOn)
			{
				LogSkip(__instance, hit, text, "no PoV effect");
			}
		}
		else
		{
			if ((_inVictimDamage > 0 && SkipDerived(__instance, hit)) || SkipArrowSplash(hit))
			{
				return;
			}
			HitData hit2 = hit.Clone();
			SkillType skill = hit2.m_skill;
			if ((Object)(object)hit2.m_hitCollider == (Object)null)
			{
				Collider component = ((Component)__instance).GetComponent<Collider>();
				hit2.m_hitCollider = (((Object)(object)component != (Object)null) ? component : ((Component)__instance).GetComponentInChildren<Collider>());
			}
			string god = GodIfUsed(localPlayer);
			ItemData val2 = null;
			bool weapon = false;
			float num = 1f;
			if (_conduitsOn && _conduitFor != null)
			{
				ConduitMark mark = _objectConduit;
				if (mark != null || TryDecided(text, out mark))
				{
					val2 = mark.Item;
					weapon = mark.Weapon;
					num = mark.Share;
				}
				else
				{
					val2 = DecideNow(localPlayer, god, text, out weapon);
					num = TickShare(text);
				}
				if (_inNorseObject > 0)
				{
					num *= _objectShare;
				}
			}
			hit2.m_skill = (SkillType)0;
			BuildState buildState = new BuildState();
			Shape shape = ShapeOf(text);
			if (FromAreaDamage(hit) && (shape & Shape.Projectile) == 0)
			{
				shape |= Shape.Area;
			}
			bool flag = (shape & Shape.Area) != 0;
			string text2 = null;
			float add = 0f;
			try
			{
				ShapeBegin(buildState, shape, hit2);
				SharedData saved = null;
				object obj = null;
				if (val2 != null)
				{
					saved = SwapInOriginal(val2);
					obj = ConduitProfile(val2, hit2.m_ranged, localPlayer);
					if (obj == null)
					{
						RestoreShared(val2, saved);
						val2 = null;
					}
				}
				try
				{
					SkillType val3 = (SkillType)0;
					if (val2 != null)
					{
						Enter(buildState, obj, val2, flag ? _areaTag : null);
						if (buildState.Saved)
						{
							val3 = ConduitSkill(val2);
						}
						else
						{
							RestoreShared(val2, saved);
							val2 = null;
						}
					}
					if (val2 == null)
					{
						Enter(buildState, _gemProfile, null, flag ? _gemAreaTag : _gemTag);
					}
					hit2.m_skill = val3;
					if (HitLogOn)
					{
						try
						{
							text2 = HitHead("direct", text, god, localPlayer, __instance, val3);
						}
						catch (Exception e)
						{
							LogFailed(e);
						}
					}
					if (val2 != null && !weapon && !IsWeaponDerived(text))
					{
						add = AddHalfBase(val2, ref hit2, num);
					}
					_building++;
					try
					{
						val.ModifyAttack(val3, ref hit2);
					}
					finally
					{
						_building--;
					}
				}
				finally
				{
					if (val2 != null)
					{
						RestoreShared(val2, saved);
					}
				}
			}
			finally
			{
				hit2.m_skill = skill;
				ShapeEnd(buildState, hit2);
				Leave(buildState);
			}
			hit = hit2;
			__state = 1;
			_delivering++;
			Measure(text, totalDamage, hit2);
			if (text2 != null)
			{
				bool area = flag && buildState.Tags != null;
				try
				{
					_log.LogInfo((object)("[hit] " + text2 + HitTail(hit2, totalDamage, buildState.BuiltRanged, TagText(area, shape, buildState.BuiltRanged), ModeText(val2, add, weapon, num), treeHeld: false)));
				}
				catch (Exception e2)
				{
					LogFailed(e2);
				}
			}
			if (val2 != null && TooltipSet(val2))
			{
				__state = 3;
			}
		}
	}

	private static object ConduitProfile(ItemData x, bool ranged, Player player)
	{
		try
		{
			bool flag = (Object)(object)((Humanoid)player).m_unarmedWeapon != (Object)null && x == ((Humanoid)player).m_unarmedWeapon.m_itemData;
			return _conduitFor.Invoke(null, new object[4] { x, ranged, flag, player });
		}
		catch (Exception e)
		{
			ConduitBuildFailed(e);
			return null;
		}
	}

	private static SkillType ConduitSkill(ItemData x)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			return _treeSkillOf(x);
		}
		catch (Exception e)
		{
			ConduitBuildFailed(e);
			return (SkillType)((x.m_shared != null) ? ((int)x.m_shared.m_skillType) : 0);
		}
	}

	private static bool TooltipSet(ItemData x)
	{
		try
		{
			object? value = _tooltipItem.GetValue(null);
			_tooltipSaved = (ItemData)((value is ItemData) ? value : null);
			_tooltipItem.SetValue(null, x);
			return true;
		}
		catch (Exception e)
		{
			_tooltipSaved = null;
			ConduitBuildFailed(e);
			return false;
		}
	}

	private static void ConduitBuildFailed(Exception e)
	{
		if (!_conduitBuildFailed && _log != null)
		{
			_conduitBuildFailed = true;
			_log.LogWarning((object)("Conduit build step failed, that hit built as a gem or without its crit item (reported once): " + (e.InnerException ?? e).Message));
		}
	}

	private static void ResolveConduitBuild(Assembly pov, Type affixes)
	{
		try
		{
			Type type = pov.GetType("PassiveTree.WeaponProfile", throwOnError: true);
			BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public;
			MethodInfo method = affixes.GetMethod("For", bindingAttr, null, new Type[4]
			{
				typeof(ItemData),
				typeof(bool),
				typeof(bool),
				typeof(Humanoid)
			}, null);
			if (method == null || method.ReturnType != type)
			{
				throw new MissingMethodException(affixes.FullName, "For(ItemData, bool, bool, Humanoid)");
			}
			MethodInfo method2 = affixes.GetMethod("TreeSkill", bindingAttr, null, new Type[1] { typeof(ItemData) }, null);
			if (method2 == null || method2.ReturnType != typeof(SkillType))
			{
				throw new MissingMethodException(affixes.FullName, "TreeSkill(ItemData)");
			}
			Type type2 = pov.GetType("PassiveTree.Loot.GearEvaluator", throwOnError: true);
			FieldInfo field = type2.GetField("TooltipItem", bindingAttr);
			if (field == null || field.FieldType != typeof(ItemData) || !field.IsDefined(typeof(ThreadStaticAttribute), inherit: false))
			{
				throw new MissingFieldException(type2.FullName, "TooltipItem");
			}
			Func<ItemData, SkillType> treeSkillOf = (Func<ItemData, SkillType>)Delegate.CreateDelegate(typeof(Func<ItemData, SkillType>), method2);
			_tooltipItem = field;
			_treeSkillOf = treeSkillOf;
			_conduitFor = method;
		}
		catch (Exception ex)
		{
			if (_log != null)
			{
				_log.LogWarning((object)("Skipped (conduit hits; every hit builds as a gem): " + ex.Message));
			}
		}
	}

	private static Shape ShapeOf(string ability)
	{
		if (ability == null || !Shapes.TryGetValue(ability, out var value))
		{
			return Shape.None;
		}
		return value;
	}

	private static void ShapeBegin(BuildState state, Shape shape, HitData built)
	{
		state.BuiltRanged = built.m_ranged;
		if (shape != Shape.None)
		{
			state.Ranged = built.m_ranged;
			state.RangedSet = true;
			built.m_ranged = (shape & Shape.Projectile) != 0;
			state.BuiltRanged = built.m_ranged;
		}
	}

	private static void ShapeEnd(BuildState state, HitData built)
	{
		if (state.RangedSet)
		{
			built.m_ranged = state.Ranged;
		}
	}

	private static void Enter(BuildState state, object profile, ItemData item, object tags)
	{
		try
		{
			state.Profile = _profileOverride.GetValue(null);
			state.Weapon = _weaponOverride.GetValue(null);
			state.Saved = true;
			if (profile != null)
			{
				_profileOverride.SetValue(null, profile);
			}
			_weaponOverride.SetValue(null, item);
			state.Tags = _tagsReplace.Invoke(null, new object[1] { _noTags });
			if (tags != null)
			{
				_tagsPush.Invoke(null, new object[1] { tags });
			}
		}
		catch (Exception e)
		{
			Leave(state);
			state.Saved = false;
			state.Tags = null;
			StateFailed(e);
		}
	}

	private static void Leave(BuildState state)
	{
		if (state.Tags != null)
		{
			try
			{
				_tagsPop.Invoke(null, new object[1] { state.Tags });
			}
			catch (Exception e)
			{
				StateFailed(e);
			}
		}
		if (!state.Saved)
		{
			return;
		}
		try
		{
			_profileOverride.SetValue(null, state.Profile);
		}
		catch (Exception e2)
		{
			StateFailed(e2);
		}
		try
		{
			_weaponOverride.SetValue(null, state.Weapon);
		}
		catch (Exception e3)
		{
			StateFailed(e3);
		}
	}

	private static void StateFailed(Exception e)
	{
		if (!_stateFailed && _log != null)
		{
			_stateFailed = true;
			_log.LogWarning((object)("Path of Valheiman build state not set or not restored (reported once): " + e.Message));
		}
	}

	private static void DeliveryEnd(int __state)
	{
		if (__state == 3)
		{
			try
			{
				_tooltipItem.SetValue(null, _tooltipSaved);
			}
			catch (Exception e)
			{
				ConduitBuildFailed(e);
			}
			_tooltipSaved = null;
		}
		if (__state != 0 && _delivering > 0)
		{
			_delivering--;
		}
	}

	private static void HitLanded(Character __instance, HitData hit)
	{
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (HitLogOn && hit != null && !((Object)(object)__instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)hit.GetAttacker() != (Object)(object)Player.m_localPlayer))
			{
				object[] array = new object[2] { hit, 0f };
				bool flag = (bool)_critOf.Invoke(null, array);
				_log.LogInfo((object)("[hit] landed target=" + __instance.m_name + " " + ((object)__instance.GetZDOID()/*cast due to .constrained prefix*/).ToString() + " frame=" + Time.frameCount + " total=" + hit.GetTotalDamage().ToString("0.##", CultureInfo.InvariantCulture) + " crit=" + (flag ? ("yes x" + ((float)array[1]).ToString("0.##", CultureInfo.InvariantCulture)) : "no")));
			}
		}
		catch (Exception)
		{
		}
	}

	private static string ResolvedSkill(Player player, SkillType skill)
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		if (_treeSkill == null)
		{
			return "?";
		}
		try
		{
			return _treeSkill.Invoke(null, new object[2] { player, skill }).ToString();
		}
		catch (Exception)
		{
			return "?";
		}
	}

	private static Character TargetOf(HitData hit)
	{
		if (!((Object)(object)hit.m_hitCollider != (Object)null))
		{
			return null;
		}
		return ((Component)hit.m_hitCollider).GetComponentInParent<Character>();
	}

	private static string Named(string ability)
	{
		if (ability != null)
		{
			if (ability.Length != 0)
			{
				return ability;
			}
			return "norse";
		}
		return "?";
	}

	private static string HitHead(string site, string ability, string god, Player player, Character target, SkillType skill)
	{
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		SharedData val = SharedOf(((Humanoid)player).GetCurrentWeapon());
		return site + " ability=" + Named(ability) + " god=" + (god ?? "?") + " target=" + (((Object)(object)target != (Object)null) ? (target.m_name + " " + ((object)target.GetZDOID()/*cast due to .constrained prefix*/).ToString()) : "none") + " frame=" + Time.frameCount + " resolved=" + ResolvedSkill(player, skill) + " held=" + ((val != null) ? (val.m_name + " (" + ((object)Unsafe.As<SkillType, SkillType>(ref val.m_skillType)/*cast due to .constrained prefix*/).ToString() + ")") : "none");
	}

	private static string ModeText(ItemData conduit, float add, bool weapon = false, float share = 1f)
	{
		if (conduit == null)
		{
			return "gem";
		}
		if (weapon)
		{
			return "weapon(" + ConduitText(conduit) + ")";
		}
		return "conduit(" + ConduitText(conduit) + ") add=" + add.ToString("0.###", CultureInfo.InvariantCulture) + ((share < 1f) ? (" share=" + share.ToString("0.####", CultureInfo.InvariantCulture)) : "");
	}

	private static string HitTail(HitData built, float before, bool ranged, string tags, string mode, bool treeHeld)
	{
		return " mode=" + mode + " ranged=" + ranged + " tags=" + tags + " before=" + before.ToString("0.##") + " after=" + built.GetTotalDamage().ToString("0.##") + (treeHeld ? " treecrit=suppressed" : "");
	}

	private static string TagText(bool area, Shape shape, bool ranged)
	{
		bool flag = (shape & Shape.Projectile) != 0 && ranged;
		if (!area)
		{
			if (!flag)
			{
				return "";
			}
			return "Projectile";
		}
		if (!flag)
		{
			return "Area";
		}
		return "Area|Projectile";
	}

	private static void LogSkip(Character target, HitData hit, string ability, string reason)
	{
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)target == (Object)(object)localPlayer || (Object)(object)hit.GetAttacker() != (Object)(object)localPlayer)
			{
				return;
			}
			if (ability == null)
			{
				ability = ((_inNorseObject > 0) ? _objectAbility : NorseAbility());
				if (_inNorseObject == 0 && ability == null)
				{
					return;
				}
			}
			string key = ability ?? "";
			if (!SkipLogged.TryGetValue(key, out var value) || !(Time.time - value < 5f))
			{
				SkipLogged[key] = Time.time;
				_log.LogInfo((object)("[hit] skipped ability=" + Named(ability) + " target=" + (((Object)(object)target != (Object)null) ? (target.m_name + " " + ((object)target.GetZDOID()/*cast due to .constrained prefix*/).ToString()) : "none") + " frame=" + Time.frameCount + " reason=" + reason));
			}
		}
		catch (Exception e)
		{
			LogFailed(e);
		}
	}

	private static void LogFailed(Exception e)
	{
		if (!_logFailed && _log != null)
		{
			_logFailed = true;
			_log.LogWarning((object)("Hit log failed (reported once): " + e.Message));
		}
	}

	private void Start()
	{
		//IL_061b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0625: Expected O, but got Unknown
		if (!Find("NorseDemigods", new Version(1, 9, 3), out var info) || !Find("treextr.pathofvalheiman", new Version(6, 0, 6), out var info2))
		{
			return;
		}
		_config = ((BaseUnityPlugin)this).Config;
		foreach (KeyValuePair<string, bool> minionDefault in MinionDefaults)
		{
			Minions[minionDefault.Key] = ((BaseUnityPlugin)this).Config.Bind<bool>("Minion", minionDefault.Key, minionDefault.Value, "Whether the " + minionDefault.Key + " summon counts as a Path of Valheiman minion of its summoner.");
		}
		Companion["Wolf"] = ((BaseUnityPlugin)this).Config.Bind<bool>("Companion", "Wolf", true, "Summoning the wolf makes it your Path of Valheiman companion (only for a wolf not counted as a minion). It replaces any other companion you have.");
		_hitLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "HitLog", false, "One log line per Norse ability hit Path of Valheiman builds, for testing.");
		_measuredBonus = ((BaseUnityPlugin)this).Config.Bind<bool>("Tooltip", "MeasuredBonus", true, "Each damage ability's line in the god's status tooltip shows how much Path of Valheiman raised its last hit (until the first hit: hit something to measure).");
		BindControls(((BaseUnityPlugin)this).Config);
		_log = ((BaseUnityPlugin)this).Logger;
		Harmony harmony = null;
		string at = null;
		try
		{
			_norse = ((object)info.Instance).GetType().Assembly;
			_povEffect = ((object)info2.Instance).GetType().Assembly.GetType("PassiveTree.SE_PassiveTree", throwOnError: true);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(_povEffect, "ModifyAttack", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException(_povEffect.FullName, "ModifyAttack");
			}
			Assembly povAssembly = _povEffect.Assembly;
			Type affixes = povAssembly.GetType("PassiveTree.WeaponAffixes", throwOnError: true);
			ResolveBuildState(povAssembly, affixes);
			Type type = _norse.GetType("NorseDemigods.Demigod", throwOnError: true);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(type, "OnVictimDamage", new Type[2]
			{
				typeof(Character),
				typeof(HitData)
			}, (Type[])null);
			if (methodInfo2 == null)
			{
				throw new MissingMethodException(type.FullName, "OnVictimDamage");
			}
			PropertyInfo propertyInfo = AccessTools.Property(type, "DemigodDefaults");
			if (propertyInfo == null || propertyInfo.GetGetMethod() == null || !propertyInfo.GetGetMethod().IsStatic || !typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType))
			{
				throw new MissingMemberException(type.FullName, "DemigodDefaults");
			}
			Type type2 = _norse.GetType("NorseDemigods.DemigodDefaults", throwOnError: true);
			PropertyInfo propertyInfo2 = AccessTools.Property(type2, "Name");
			PropertyInfo propertyInfo3 = AccessTools.Property(type2, "DefaultAbilities");
			if (propertyInfo2 == null || propertyInfo2.PropertyType != typeof(string) || propertyInfo3 == null || !typeof(IEnumerable).IsAssignableFrom(propertyInfo3.PropertyType))
			{
				throw new MissingMemberException(type2.FullName, "Name/DefaultAbilities");
			}
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(type, "SetupDefaults", Type.EmptyTypes, (Type[])null);
			if (methodInfo3 == null || !methodInfo3.IsStatic)
			{
				throw new MissingMethodException(type.FullName, "SetupDefaults");
			}
			MethodInfo methodInfo4 = AccessTools.Method(typeof(Character), "Damage", (Type[])null, (Type[])null);
			if (methodInfo4 == null)
			{
				throw new MissingMethodException(typeof(Character).FullName, "Damage");
			}
			Type helper = _norse.GetType("NorseDemigods.Helper", throwOnError: true);
			List<MethodInfo> list = new List<MethodInfo>();
			foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(helper))
			{
				if (declaredMethod.Name == "SpawnGameObject" && declaredMethod.ReturnType == typeof(GameObject))
				{
					list.Add(declaredMethod);
				}
			}
			if (list.Count == 0)
			{
				throw new MissingMethodException("NorseDemigods.Helper", "SpawnGameObject");
			}
			MethodInfo methodInfo5 = AccessTools.Method(helper, "GetCachedModifiedItemSharedData", new Type[2]
			{
				typeof(ItemData),
				typeof(Type)
			}, (Type[])null);
			if (methodInfo5 == null)
			{
				throw new MissingMethodException(helper.FullName, "GetCachedModifiedItemSharedData");
			}
			List<MethodInfo> list2 = new List<MethodInfo>();
			List<MethodInfo> list3 = new List<MethodInfo>();
			Type[] array = new Type[2]
			{
				typeof(Projectile),
				typeof(Aoe)
			};
			foreach (Type type3 in array)
			{
				MethodInfo methodInfo6 = AccessTools.Method(type3, "Awake", (Type[])null, (Type[])null);
				MethodInfo methodInfo7 = AccessTools.Method(type3, "OnHit", (Type[])null, (Type[])null);
				if (methodInfo6 == null)
				{
					throw new MissingMethodException(type3.FullName, "Awake");
				}
				if (methodInfo7 == null)
				{
					throw new MissingMethodException(type3.FullName, "OnHit");
				}
				list2.Add(methodInfo6);
				list3.Add(methodInfo7);
			}
			_godListName = propertyInfo2;
			_godListAbilities = propertyInfo3;
			_godList = propertyInfo;
			HarmonyMethod postfix = Hook("GodListLoaded");
			HarmonyMethod prefix = Hook("VictimDamageBegin");
			HarmonyMethod finalizer = Hook("VictimDamageEnd");
			HarmonyMethod prefix2 = Hook("MorphBegin");
			HarmonyMethod finalizer2 = Hook("MorphEnd");
			HarmonyMethod val = Hook("BuildAbilityHit");
			val.priority = 800;
			HarmonyMethod finalizer3 = Hook("DeliveryEnd");
			HarmonyMethod postfix2 = Hook("NorseSpawned");
			HarmonyMethod postfix3 = Hook("MorphMapped");
			HarmonyMethod postfix4 = Hook("ChildSpawned");
			HarmonyMethod prefix3 = Hook("ObjectHitBegin");
			HarmonyMethod finalizer4 = Hook("ObjectHitEnd");
			harmony = new Harmony("avesatanas.povplus.norsedemigods");
			Apply(methodInfo3, null, postfix, null);
			Apply(methodInfo2, prefix, null, finalizer);
			Apply(methodInfo, prefix2, null, finalizer2);
			Apply(methodInfo4, val, null, finalizer3);
			foreach (MethodInfo item in list)
			{
				Apply(item, null, postfix2, null);
			}
			Apply(methodInfo5, null, postfix3, null);
			foreach (MethodInfo item2 in list2)
			{
				Apply(item2, null, postfix4, null);
			}
			foreach (MethodInfo item3 in list3)
			{
				Apply(item3, prefix3, null, finalizer4);
			}
			at = null;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Active: NorseDemigods ability damage is built by Path of Valheiman.");
			Optional("the startup log names the Path of Valheiman API", delegate
			{
				Type type4 = povAssembly.GetType("Valheiman.Api.Pov", throwOnError: true);
				FieldInfo fieldInfo = AccessTools.Field(type4, "ApiVersion");
				if (fieldInfo == null || !fieldInfo.IsStatic || fieldInfo.FieldType != typeof(Version))
				{
					throw new MissingFieldException(type4.FullName, "ApiVersion");
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Path of Valheiman API " + fieldInfo.GetValue(null)));
			});
			Optional("the hit log knows the current god", delegate
			{
				Type type4 = _norse.GetType("NorseDemigods.Demigod", throwOnError: true);
				MethodInfo methodInfo8 = null;
				foreach (MethodInfo declaredMethod2 in AccessTools.GetDeclaredMethods(helper))
				{
					if (declaredMethod2.Name == "TryGetDemigod" && declaredMethod2.IsGenericMethodDefinition && declaredMethod2.GetParameters().Length == 2)
					{
						methodInfo8 = declaredMethod2;
						break;
					}
				}
				PropertyInfo propertyInfo4 = AccessTools.Property(type4, "DemigodName");
				if (methodInfo8 == null || propertyInfo4 == null)
				{
					throw new MissingMethodException("NorseDemigods.Helper", "TryGetDemigod");
				}
				_tryGetDemigod = methodInfo8.MakeGenericMethod(type4);
				_demigodName = propertyInfo4;
			});
			Optional("Conduits: a god's weapons build the hit as an attack with that weapon", delegate
			{
				if (_conduitFor == null)
				{
					throw new MissingMethodException("needs WeaponAffixes.For, TreeSkill(ItemData) and GearEvaluator.TooltipItem (see the conduit hits Skipped line)");
				}
				InstallConduits(harmony);
			});
			Optional("the hit log reads the skill Path of Valheiman resolves", delegate
			{
				MethodInfo methodInfo8 = AccessTools.Method(affixes, "TreeSkill", new Type[2]
				{
					typeof(Character),
					typeof(SkillType)
				}, (Type[])null);
				if (methodInfo8 == null)
				{
					throw new MissingMethodException("PassiveTree.WeaponAffixes", "TreeSkill");
				}
				_treeSkill = methodInfo8;
			});
			Optional("summons count as Path of Valheiman minions", delegate
			{
				_minionMark = povAssembly.GetType("PassiveTree.Minions+Mark", throwOnError: true);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(MonsterAI), "SetFollowTarget", (Type[])null, (Type[])null), (HarmonyMethod)null, Hook("SummonFollows"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			});
			Optional("pets stay tamed pets, not summons", delegate
			{
				Type type4 = povAssembly.GetType("PassiveTree.CreatureTags", throwOnError: true);
				MethodInfo methodInfo8 = AccessTools.Method(type4, "Summoned", new Type[1] { typeof(Character) }, (Type[])null);
				if (methodInfo8 == null)
				{
					throw new MissingMethodException(type4.FullName, "Summoned");
				}
				harmony.Patch((MethodBase)methodInfo8, (HarmonyMethod)null, Hook("NotSummoned"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			});
			Optional("the summoned wolf becomes a Path of Valheiman companion", delegate
			{
				MethodInfo methodInfo8 = AccessTools.Method(povAssembly.GetType("PassiveTree.Companions", throwOnError: true), "Send", new Type[8]
				{
					typeof(ZDOID),
					typeof(string),
					typeof(long),
					typeof(string),
					typeof(int),
					typeof(Vector3),
					typeof(ZDOID),
					typeof(bool)
				}, (Type[])null);
				Type? type4 = _norse.GetType("NorseDemigods.Abilities.AbilityWolf", throwOnError: true);
				MethodInfo methodInfo9 = AccessTools.Method(type4, "Stop", (Type[])null, (Type[])null);
				_wolfField = AccessTools.Field(type4, "WolfCharacter");
				if (methodInfo8 == null || methodInfo9 == null || _wolfField == null)
				{
					throw new MissingMethodException("companion hook");
				}
				harmony.Patch((MethodBase)methodInfo9, Hook("WolfDismissed"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_companionSend = methodInfo8;
			});
			Optional("ability cooldowns use Path of Valheiman skill cooldown", delegate
			{
				_cooldownOf = AccessTools.Method(povAssembly.GetType("PassiveTree.Cooldowns", throwOnError: true), "Of", (Type[])null, (Type[])null);
				_skillCooldown = Enum.Parse(povAssembly.GetType("PassiveTree.Subject", throwOnError: true), "PassiveEffect");
				MethodInfo methodInfo8 = AccessTools.Method(_norse.GetType("NorseDemigods.StatusEffects.SE_Ability_Cooldown", throwOnError: true), "CreateAbilityCooldownStatusEffect", (Type[])null, (Type[])null);
				if (_cooldownOf == null || methodInfo8 == null)
				{
					throw new MissingMethodException("cooldown hook");
				}
				harmony.Patch((MethodBase)methodInfo8, (HarmonyMethod)null, Hook("CooldownCreated"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			});
			Optional("projectile abilities use cast speed", delegate
			{
				_spellCategory = Enum.Parse(povAssembly.GetType("PassiveTree.CombatCategory", throwOnError: true), "Spell");
				MethodInfo methodInfo8 = AccessTools.Method(povAssembly.GetType("PassiveTree.CombatCategories", throwOnError: true), "For", new Type[1] { typeof(Attack) }, (Type[])null);
				if (methodInfo8 == null)
				{
					throw new MissingMethodException("PassiveTree.CombatCategories", "For");
				}
				harmony.Patch((MethodBase)methodInfo8, (HarmonyMethod)null, Hook("MorphIsSpell"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			});
			Optional("Norse area follow-up hits (Helper.DoAreaDamage) are built as Area hits", delegate
			{
				int num = 0;
				MethodInfo[] methods = helper.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo8 in methods)
				{
					ParameterInfo[] array2 = ((methodInfo8.Name