Decompiled source of Even More Balanced Mortician v1.6.0

EvenMoreBalancedMortician.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AncientScepter;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using EntityStates;
using EvenMoreBalancedMortician.Networking;
using EvenMoreBalancedMortician.Patches;
using EvenMoreBalancedMortician.Presets;
using EvenMoreBalancedMortician.Scepter;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using Morris;
using Morris.Components;
using Morris.Content;
using Morris.Modules;
using Morris.Modules.NPC;
using Morris.Modules.Survivors;
using R2API;
using R2API.Networking;
using R2API.Networking.Interfaces;
using R2API.Utils;
using RiskOfOptions;
using RiskOfOptions.OptionConfigs;
using RiskOfOptions.Options;
using RoR2;
using RoR2.Navigation;
using RoR2.Networking;
using RoR2.Orbs;
using RoR2.Projectile;
using RoR2.Skills;
using SkillStates.Ghoul;
using SkillStates.Morris;
using SkillStates.SharedStates;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Events;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("AncientScepter")]
[assembly: IgnoresAccessChecksTo("Morris")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EvenMoreBalancedMortician")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.6.0.0")]
[assembly: AssemblyInformationalVersion("1.6.0+b236e2fb9341126bcde6edb7397cb5dd9c14aebf")]
[assembly: AssemblyProduct("EvenMoreBalancedMortician")]
[assembly: AssemblyTitle("EvenMoreBalancedMortician")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.6.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EvenMoreBalancedMortician
{
	[BepInPlugin("com.Delfofthebla.EvenMoreBalancedMortician", "EvenMoreBalancedMortician", "1.6.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	[BepInIncompatibility("com.Bloonjitsu7.BalancedMortician")]
	public class EvenMoreBalancedMorticianPlugin : BaseUnityPlugin
	{
		public const string GUID = "com.Delfofthebla.EvenMoreBalancedMortician";

		public const string NAME = "EvenMoreBalancedMortician";

		public const string VERSION = "1.6.0";

		private const string BALANCED_MORTICIAN_GUID = "com.Bloonjitsu7.BalancedMortician";

		private MorticianSettings _settings;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			_settings = new MorticianSettings(((BaseUnityPlugin)this).Config);
			DyingGhoul.Install();
			ShovelDamageSourcePatch.Install(_settings.ShovelCountsAsPrimarySkill);
			RaiseDeadMinimumCooldownPatch.Install(_settings.RaiseDeadMinimumCooldown);
			GhoulEquipmentPatch.Install();
			GhoulAspectPatch.Install(_settings.GhoulAspectInheritChance);
			GhoulRotPatch.Install(_settings.GhoulDegenGrowthPercent);
			GhoulOnKillPatch.Install(_settings.GhoulOnKillTriggerChance, _settings.SacrificeGuaranteesOnKill);
			ProcCoefficientPatch.Install(_settings);
			GhoulLimitPatch.Install(_settings.GhoulLimit);
			DetonationDamagePatch.Install(_settings.DetonationScalesWithMortician);
			TombstoneDurationPatch.Install(_settings.TombstoneDuration);
			TombstoneLimitPatch.Install(_settings.LysateCellAddsTombstone);
			TombstoneSoulPatch.Install(_settings.TombstoneSoulRecipient);
			GhoulRaiseCooldownPatch.Install(_settings.GhoulRaisingUsesCooldownReduction);
			InstallAncientScepterSupport();
			ApplySettings();
			_settings.PresetSelector.SettingsChanged += ApplySettings;
			HostSettingsSync.Install(_settings, ApplySettings);
			RiskOfOptionsMenu.Register((BaseUnityPlugin)(object)this, Log, (ConfigEntryBase entry) => (object)entry == _settings.ConfigVersion);
		}

		private void InstallAncientScepterSupport()
		{
			if (AncientScepterCompat.IsInstalled)
			{
				RestlessGraveSkill.Register(_settings.RestlessGraveEnabled);
				RestlessGrave.Install(_settings.RestlessGraveRadius, _settings.RestlessGraveRisenGhoulLimit, _settings.ShowRaiseRadius);
			}
		}

		private void ApplySettings()
		{
			MorticianTuning.Apply(_settings);
			SkillDescriptions.Apply(_settings);
			RestlessGraveSkill.ApplyEnabledSetting();
		}
	}
	internal static class LiveBodies
	{
		public static IEnumerable<CharacterBody> Of(BodyIndex bodyIndex)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if ((int)bodyIndex != -1)
			{
				return CharacterBody.readOnlyInstancesList.Where((CharacterBody body) => body.bodyIndex == bodyIndex);
			}
			return Array.Empty<CharacterBody>();
		}
	}
	internal static class MinionOwner
	{
		public static CharacterMaster MasterOf(CharacterBody minion)
		{
			if (!Object.op_Implicit((Object)(object)minion) || !Object.op_Implicit((Object)(object)minion.master))
			{
				return null;
			}
			return minion.master.minionOwnership.ownerMaster;
		}

		public static CharacterBody BodyOf(CharacterBody minion)
		{
			CharacterMaster val = MasterOf(minion);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return val.GetBody();
		}
	}
	internal sealed class MorticianSettings
	{
		private readonly ConfigFile _config;

		private readonly List<IPresetSetting> _presetSettings = new List<IPresetSetting>();

		private static readonly string GeneralSection = "General";

		private static readonly string BaseStatsSection = "Base Stats";

		private static readonly string PrimarySection = "Primary - Shovel Strike";

		private static readonly string SecondarySection = "Secondary - Raise Dead";

		private static readonly string UtilitySection = "Utility - Sacrifice";

		private static readonly string SpecialSection = "Special - Tombstone";

		private static readonly string ScepterSection = "Ancient Scepter - Restless Grave";

		private static readonly string VisualsSection = "Visuals";

		private static readonly string GhoulDamageNote = "Scales with the ghoul's damage stat (" + SecondarySection + "), not Mortician's. Uses Mortician's crit chance and on-hit items.";

		private static readonly string LaunchDamageNote = "Scales with the launched ghoul's or tombstone's damage stat, not Mortician's. Uses Mortician's crit chance and on-hit items.";

		private static readonly string SoulOrbDamageNote = "Scales with the tombstone's damage stat (" + SpecialSection + "), not Mortician's. Uses the tombstone's crit chance and items, which it copies from Mortician when placed.";

		private static readonly string ScepterNote = "Requires StandaloneAncientScepter.";

		private static readonly string ProcCoefficientVanilla = "Most survivor attacks use 1.0. Rapid multi-hit attacks use less, such as MUL-T's nailgun at 0.6.";

		public PresetSelector PresetSelector { get; }

		public PresetSetting<float> BaseHealth { get; }

		public PresetSetting<float> HealthPerLevel { get; }

		public PresetSetting<float> BaseRegen { get; }

		public PresetSetting<float> RegenPerLevel { get; }

		public PresetSetting<float> BaseArmor { get; }

		public PresetSetting<float> ArmorPerLevel { get; }

		public PresetSetting<float> BaseDamage { get; }

		public PresetSetting<float> DamagePerLevel { get; }

		public PresetSetting<bool> ShovelCountsAsPrimarySkill { get; }

		public PresetSetting<float> ShovelDamagePercent { get; }

		public PresetSetting<float> LaunchDamagePercent { get; }

		public PresetSetting<float> LaunchProcCoefficient { get; }

		public PresetSetting<float> RaiseDeadCooldown { get; }

		public PresetSetting<float> RaiseDeadMinimumCooldown { get; }

		public PresetSetting<int> GhoulLimit { get; }

		public PresetSetting<float> GhoulBaseHealth { get; }

		public PresetSetting<float> GhoulHealthPerLevel { get; }

		public PresetSetting<float> GhoulBaseDamage { get; }

		public PresetSetting<float> GhoulDamagePerLevel { get; }

		public PresetSetting<float> GhoulDegen { get; }

		public PresetSetting<float> GhoulDegenPerLevel { get; }

		public PresetSetting<float> GhoulDegenGrowthPercent { get; }

		public PresetSetting<float> GhoulBiteDamagePercent { get; }

		public PresetSetting<float> GhoulBiteProcCoefficient { get; }

		public PresetSetting<float> GhoulClingBiteProcCoefficient { get; }

		public PresetSetting<float> GhoulSpitDamagePercent { get; }

		public PresetSetting<float> GhoulSpitProcCoefficient { get; }

		public PresetSetting<float> GhoulAspectInheritChance { get; }

		public PresetSetting<float> GhoulOnKillTriggerChance { get; }

		public PresetSetting<float> SacrificeCooldown { get; }

		public PresetSetting<bool> DetonationScalesWithMortician { get; }

		public PresetSetting<float> SacrificeDamagePercent { get; }

		public PresetSetting<float> SacrificeProcCoefficient { get; }

		public PresetSetting<float> SacrificeRadius { get; }

		public PresetSetting<float> SacrificeHealPercent { get; }

		public PresetSetting<bool> SacrificeGuaranteesOnKill { get; }

		public PresetSetting<float> TombstoneCooldown { get; }

		public PresetSetting<float> TombstoneDuration { get; }

		public PresetSetting<bool> LysateCellAddsTombstone { get; }

		public PresetSetting<SoulRecipient> TombstoneSoulRecipient { get; }

		public PresetSetting<float> TombstoneBaseDamage { get; }

		public PresetSetting<float> TombstoneDamagePerLevel { get; }

		public PresetSetting<float> SoulOrbDamagePercent { get; }

		public PresetSetting<float> SoulOrbProcCoefficient { get; }

		public PresetSetting<float> TombstoneGhoulSpawnInterval { get; }

		public PresetSetting<bool> GhoulRaisingUsesCooldownReduction { get; }

		public PresetSetting<bool> RestlessGraveEnabled { get; }

		public PresetSetting<float> RestlessGraveRadius { get; }

		public PresetSetting<float> RestlessGraveCooldown { get; }

		public PresetSetting<int> RestlessGraveRisenGhoulLimit { get; }

		public ConfigEntry<bool> ShowRaiseRadius { get; }

		public ConfigEntry<string> ConfigVersion { get; }

		public MorticianSettings(ConfigFile config)
		{
			_config = config;
			ConfigEntry<MorticianPreset> preset = config.Bind<MorticianPreset>(GeneralSection, "Preset", MorticianPreset.EvenMoreBalanced, "Which preset the other settings follow. Choosing a preset overwrites every other setting with that preset's values; editing any setting afterwards switches this to Custom.\nEvenMoreBalanced: Delf's rebalance.\nBalancedMortician: Equivalent to Bloonjitsu7's BalancedMortician mod. \nOriginal: Mortician's original numbers.");
			ConfigVersion = config.Bind<string>(GeneralSection, "Config Version", "", "DO NOT EDIT. Updated automatically. The mod version that last loaded this config. When the mod updates, every setting is moved to the selected preset's new values, unless the preset is Custom.");
			BaseHealth = Bind(BaseStatsSection, "Base Health", "Mortician's maximum health at level 1.", Presets(200f, 200f, 180f), "Most survivors sit at 110. Loader and Acrid 160. MUL-T 200.");
			HealthPerLevel = Bind(BaseStatsSection, "Health Per Level", "Maximum health Mortician gains per level.", Presets(66f, 66f, 54f), "Every survivor gains 30% of their base health, so 33 for a 110 health survivor.");
			BaseRegen = Bind(BaseStatsSection, "Base Regen", "Health Mortician regenerates per second at level 1.", Presets(2.5f, 2.5f, 2.5f), "Most survivors 1. Loader and Acrid 2.5.");
			RegenPerLevel = Bind(BaseStatsSection, "Regen Per Level", "Regen per second Mortician gains per level.", Presets(0.5f, 0.5f, 0.5f), "Most survivors 0.2. Loader and Acrid 0.5.");
			BaseArmor = Bind(BaseStatsSection, "Base Armor", "Mortician's armor at level 1.", Presets(20f, 20f, 20f), "Most survivors 0. Mercenary, Loader, Acrid, REX, Seeker and Drifter 20. MUL-T 12.");
			ArmorPerLevel = Bind(BaseStatsSection, "Armor Per Level", "Armor Mortician gains per level.", Presets(0f, 0f, 0f), "Every survivor 0.");
			BaseDamage = Bind(BaseStatsSection, "Base Damage", "Mortician's damage at level 1. Only the shovel swing scales with it; ghoul and tombstone attacks use their own damage stats.", Presets(12f, 12f, 12f), "Most survivors 12. MUL-T 11. Engineer 14. Acrid 15.");
			DamagePerLevel = Bind(BaseStatsSection, "Damage Per Level", "Damage Mortician gains per level.", Presets(2.4f, 2.4f, 2.4f), "Every survivor gains 20% of their base damage, so 2.4 for a 12 damage survivor.");
			ShovelCountsAsPrimarySkill = Bind(PrimarySection, "Counts As Primary Skill Damage", "Whether shovel swings count as primary skill damage. Items that trigger on primary skill hits (such as Luminous Shot) require this.", Presets(original: false, balancedMortician: true, evenMoreBalanced: true));
			ShovelDamagePercent = Bind(PrimarySection, "Swing Damage Percent", "Shovel swing damage, as a percent of Mortician's damage stat.", Presets(800f, 360f, 340f));
			LaunchDamagePercent = Bind(PrimarySection, "Launch Damage Percent", "Damage a ghoul or tombstone deals when flung through enemies by your shovel, as a percent of their own damage stats.", Presets(350f, 600f, 400f), null, LaunchDamageNote);
			LaunchProcCoefficient = Bind(PrimarySection, "Launch Proc Coefficient", "How strongly each hit from a launched ghoul or tombstone triggers Mortician's on-hit items. 1.0 is full strength.", Presets(1f, 1f, 1f), ProcCoefficientVanilla);
			RaiseDeadCooldown = Bind(SecondarySection, "Cooldown", "Seconds Raise Dead takes to recharge one of its 2 charges. Cooldown reduction items still apply.", Presets(7f, 7f, 7f));
			RaiseDeadMinimumCooldown = Bind(SecondarySection, "Minimum Cooldown", "Time that Raise Dead's cooldown can never drop below, regardless of how much cooldown reduction you have (Brainstalks included).", Presets(0.5f, 0.5f, 2f), "Every skill's cooldown bottoms out at 0.5 seconds.", "If you decide to set a cap on ghouls, I recommend lowering this back down to 0.5", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f));
			GhoulLimit = Bind(SecondarySection, "Ghoul Limit", "Maximum number of ghouls Mortician can have at once; raising another kills the oldest. 0 means no limit.", Presets(0, 0, 0), null, "Replaces the Ghoul limit setting in Mortician's own config.");
			GhoulBaseHealth = Bind(SecondarySection, "Ghoul Base Health", "Ghoul maximum health at level 1.", Presets(150f, 150f, 150f));
			GhoulHealthPerLevel = Bind(SecondarySection, "Ghoul Health Per Level", "Maximum health ghouls gain per level.", Presets(45f, 45f, 45f));
			GhoulBaseDamage = Bind(SecondarySection, "Ghoul Base Damage", "Ghoul damage at level 1. Sets the damage of ghoul bites, spit and launched ghouls, and of Sacrifice explosions unless Detonation Scales With Mortician is on.", Presets(12f, 8f, 8f));
			GhoulDamagePerLevel = Bind(SecondarySection, "Ghoul Damage Per Level", "Damage ghouls gain per level.", Presets(2.4f, 1.6f, 1.6f));
			GhoulDegen = Bind(SecondarySection, "Ghoul Degen", "Health each ghoul loses per second at level 1. 0 means ghouls never decay.", Presets(10f, 10f, 4f), null, "With the default ghoul health (150, plus 45 per level), every preset gives an unhealed ghoul about 15 seconds to live at any level.");
			GhoulDegenPerLevel = Bind(SecondarySection, "Ghoul Degen Per Level", "Health lost per second, per level.", Presets(3f, 3f, 1.2f));
			GhoulDegenGrowthPercent = Bind(SecondarySection, "Ghoul Degen Growth Percent", "How much a ghoul's degen ramps every second, as a percent of its starting degen. 0 keeps degen constant.", Presets(0f, 0f, 20f), null, "This is to prevent immortal ghouls when you have a lot of healing. The general idea behind all degen numbers is to ensure ghouls last about 15 seconds before dying naturally, and to let heals offset that, but not prevent it outright.");
			GhoulBiteDamagePercent = Bind(SecondarySection, "Bite Damage Percent", "Ghoul bite damage as a percent of the ghoul's damage stat.", Presets(150f, 150f, 150f), null, GhoulDamageNote);
			GhoulBiteProcCoefficient = Bind(SecondarySection, "Bite Proc Coefficient", "How strongly each regular ghoul bite triggers Mortician's on-hit items. 1.0 is full strength.", Presets(1f, 1f, 1f), ProcCoefficientVanilla);
			GhoulClingBiteProcCoefficient = Bind(SecondarySection, "Cling Bite Proc Coefficient", "How strongly each bite from a clinging ghoul triggers Mortician's on-hit items. 1.0 is full strength. A ghoul launched into a large enemy latches on and bites it every 0.7 seconds.", Presets(0.8f, 0.8f, 0.8f), ProcCoefficientVanilla);
			GhoulSpitDamagePercent = Bind(SecondarySection, "Spit Damage Percent", "Ghoul bile spit damage as a percent of the ghoul's damage stat.", Presets(100f, 100f, 100f), null, GhoulDamageNote);
			GhoulSpitProcCoefficient = Bind(SecondarySection, "Spit Proc Coefficient", "How strongly each ghoul bile spit triggers Mortician's on-hit items. 1.0 is full strength.", Presets(1f, 1f, 0.7f), ProcCoefficientVanilla);
			GhoulAspectInheritChance = Bind(SecondarySection, "Aspect Inherit Chance Percent", "Chance for a newly raised ghoul to copy each elite aspect Mortician holds. An aspect equipment rolls once. Aspect items roll once for every copy you hold, and each success passes on one copy. Luck (such as 57 Leaf Clover) improves each roll. 0 disables. Ghouls never copy any other items or equipment.", Presets(100f, 0f, 33f), null, "Aspect items are any item with \"Aspect\" in its name, such as ZetAspects' aspect items. The Original preset matches the base mod for aspect equipment, but the base mod never passed on aspect items.");
			GhoulOnKillTriggerChance = Bind(SecondarySection, "On-Kill Trigger Chance Percent", "Chance for a dying ghoul to trigger Mortician's on-kill items, as if he had killed it. Rolls on every ghoul death: slain by enemies, sacrificed (unless Guarantees On-Kill Trigger is on), decayed, or replaced under the Ghoul Limit. Luck (such as 57 Leaf Clover) improves the roll. 0 disables.", Presets(100f, 100f, 50f), null, "Ghouls raised by the tombstone or by Restless Grave roll too.");
			SacrificeCooldown = Bind(UtilitySection, "Cooldown", "Seconds Sacrifice takes to recharge. Cooldown reduction items still apply.", Presets(6f, 6f, 6f));
			DetonationScalesWithMortician = Bind(UtilitySection, "Detonation Scales With Mortician", "Whether a sacrificed ghoul's explosion scales with Mortician's damage stat instead of the ghoul's. Mortician's damage stat includes his items and buffs that raise damage; the ghoul's does not.", Presets(original: false, balancedMortician: false, evenMoreBalanced: true));
			SacrificeDamagePercent = Bind(UtilitySection, "Detonation Damage Percent", "Damage of a sacrificed ghoul's explosion, as a percent of the ghoul's damage stat, or Mortician's when Detonation Scales With Mortician is on.", Presets(700f, 925f, 800f), null, "Uses Mortician's crit chance and on-hit items either way.");
			SacrificeProcCoefficient = Bind(UtilitySection, "Detonation Proc Coefficient", "How strongly a sacrificed ghoul's explosion triggers Mortician's on-hit items, against every enemy it hits. 1.0 is full strength.", Presets(1f, 1f, 1f), ProcCoefficientVanilla);
			SacrificeRadius = Bind(UtilitySection, "Detonation Radius", "Radius of a sacrificed ghoul's explosion, in meters.", Presets(18f, 20f, 20f));
			SacrificeHealPercent = Bind(UtilitySection, "Heal Percent", "Percent of Mortician's maximum health healed by each Sacrifice.", Presets(15f, 15f, 15f));
			SacrificeGuaranteesOnKill = Bind(UtilitySection, "Guarantees On-Kill Trigger", "Whether a sacrificed ghoul always triggers Mortician's on-kill items, skipping the On-Kill Trigger Chance roll (" + SecondarySection + ").", Presets(original: true, balancedMortician: true, evenMoreBalanced: true), null, "The Original and BalancedMortician presets trigger on-kill items on every ghoul death regardless.");
			TombstoneCooldown = Bind(SpecialSection, "Cooldown", "Seconds the Tombstone takes to recharge. Cooldown reduction items still apply.", Presets(30f, 30f, 30f), "Engineer's turrets are 30.", "Tombstone Duration does not follow this; adjust it separately.");
			TombstoneDuration = Bind(SpecialSection, "Tombstone Duration", "Seconds a tombstone lasts before crumbling. 0 means it lasts until replaced or destroyed.", Presets(0f, 0f, 0f));
			LysateCellAddsTombstone = Bind(SpecialSection, "Lysate Cell Adds Tombstone", "Whether holding a Lysate Cell lets Mortician keep 2 tombstones up at once instead of 1. Without this enabled, the extra charge from Lysate Cell merely replaces the existing tombstone.", Presets(original: true, balancedMortician: true, evenMoreBalanced: true), "Engineer's turret limit rises from 2 to 3 while he holds any Lysate Cells. Further stacks add charges but not turrets.");
			TombstoneSoulRecipient = Bind(SpecialSection, "Soul Recipient", "Which tombstone receives a slain ghoul's vengeful soul while you have more than one active.\nNewest: the most recently placed one.\nNearest: the one closest to where the ghoul died.\nEvery: each one receives a soul.", Presets(SoulRecipient.Nearest, SoulRecipient.Nearest, SoulRecipient.Nearest), null, "Only matters while Lysate Cell Adds Tombstone lets you keep more than one tombstone.");
			TombstoneBaseDamage = Bind(SpecialSection, "Tombstone Base Damage", "Tombstone damage stat at level 1. Sets the damage of vengeful souls and launched tombstones.", Presets(12f, 12f, 12f));
			TombstoneDamagePerLevel = Bind(SpecialSection, "Tombstone Damage Per Level", "Damage stat tombstones gain per level.", Presets(2.4f, 2.4f, 2.4f));
			SoulOrbDamagePercent = Bind(SpecialSection, "Soul Orb Damage Percent", "Vengeful soul explosion damage, as a percent of the tombstone's damage stat.", Presets(350f, 200f, 280f), null, SoulOrbDamageNote);
			SoulOrbProcCoefficient = Bind(SpecialSection, "Soul Orb Proc Coefficient", "How strongly each vengeful soul explosion triggers on-hit items. 1.0 is full strength.", Presets(0.2f, 0.2f, 0.2f), ProcCoefficientVanilla, "Triggers the tombstone's items, which it copies from Mortician when placed, not Mortician's own.");
			TombstoneGhoulSpawnInterval = Bind(SpecialSection, "Ghoul Spawn Interval", "Seconds between ghouls raised by the tombstone.", Presets(10f, 10f, 10f));
			GhoulRaisingUsesCooldownReduction = Bind(SpecialSection, "Ghoul Raising Uses Cooldown Reduction", "Whether cooldown reduction items shorten the Ghoul Spawn Interval and Restless Grave's Raise Cooldown.", Presets(original: true, balancedMortician: true, evenMoreBalanced: true));
			RestlessGraveEnabled = Bind(ScepterSection, "Enabled", "Whether the Ancient Scepter upgrades Tombstone into Restless Grave. When off, the Scepter treats Mortician as a survivor it has no upgrade for, following its own config for unusable Scepters.", Presets(original: true, balancedMortician: true, evenMoreBalanced: true), null, ScepterNote);
			RestlessGraveRadius = Bind(ScepterSection, "Raise Radius", "With the Ancient Scepter, enemies slain within this many meters of a tombstone rise as ghouls.", Presets(30f, 30f, 30f), null, ScepterNote);
			RestlessGraveCooldown = Bind(ScepterSection, "Raise Cooldown", "Seconds after raising a ghoul before the same tombstone can raise another. Each tombstone has its own cooldown; a kill goes to the nearest tombstone in range that is ready.", Presets(3f, 3f, 3f), null, "Ghouls live about 15 seconds with the default ghoul health and degen, so each tombstone keeps roughly 15 divided by this many risen ghouls alive.");
			RestlessGraveRisenGhoulLimit = Bind(ScepterSection, "Risen Ghoul Limit Per Tombstone", "Maximum number of risen ghouls each tombstone can have alive at once. 0 means no limit.", Presets(0, 0, 0), null, "Risen ghouls also count toward the Ghoul Limit.");
			ShowRaiseRadius = config.Bind<bool>(VisualsSection, "Show Raise Radius", true, "Whether tombstones show a ring marking the Restless Grave raise radius while their owner has the Ancient Scepter upgrade.\nThis only affects your own screen, so the host's settings never override it.");
			PresetSelector = new PresetSelector(config, preset, ConfigVersion, "1.6.0", _presetSettings);
		}

		public string[] SerializeLocalValues()
		{
			return _presetSettings.Select((IPresetSetting setting) => setting.SerializedLocalValue).ToArray();
		}

		public bool TryUseHostValues(IReadOnlyList<string> hostValues)
		{
			if (hostValues.Count != _presetSettings.Count)
			{
				return false;
			}
			for (int i = 0; i < hostValues.Count; i++)
			{
				_presetSettings[i].UseHostValue(hostValues[i]);
			}
			return true;
		}

		public void UseLocalValues()
		{
			foreach (IPresetSetting presetSetting in _presetSettings)
			{
				presetSetting.UseLocalValue();
			}
		}

		private static PresetValues<T> Presets<T>(T original, T balancedMortician, T evenMoreBalanced)
		{
			return new PresetValues<T>(original, balancedMortician, evenMoreBalanced);
		}

		private PresetSetting<T> Bind<T>(string section, string key, string summary, PresetValues<T> presets, string vanilla = null, string note = null, AcceptableValueBase acceptableValues = null)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			PresetSetting<T> presetSetting = new PresetSetting<T>(_config.Bind<T>(section, key, presets.EvenMoreBalanced, new ConfigDescription(Describe(summary, presets, vanilla, note), acceptableValues, Array.Empty<object>())), presets);
			_presetSettings.Add(presetSetting);
			return presetSetting;
		}

		private static string Describe<T>(string summary, PresetValues<T> presets, string vanilla, string note)
		{
			List<string> list = new List<string>
			{
				summary,
				"\nPresets:",
				"Original " + Format(presets.Original),
				"BalancedMortician " + Format(presets.BalancedMortician),
				"EvenMoreBalanced " + Format(presets.EvenMoreBalanced)
			};
			if (vanilla != null)
			{
				list.Add("\nVanilla: " + vanilla);
			}
			if (note != null)
			{
				list.Add("\nNote: " + note);
			}
			return string.Join("\n", list);
		}

		private static string Format<T>(T value)
		{
			if (value is bool)
			{
				object obj = value;
				if (!(bool)((obj is bool) ? obj : null))
				{
					return "false";
				}
				return "true";
			}
			return Convert.ToString(value, CultureInfo.InvariantCulture);
		}
	}
	internal static class MorticianTuning
	{
		public static void Apply(MorticianSettings settings)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			ApplyToBodies("Mortician", MorrisPlugin.MorrisBodyPrefab, MorrisPlugin.MorrisBodyIndex, delegate(CharacterBody body)
			{
				ApplyMorticianStats(body, settings);
			});
			ApplyCooldowns(settings);
			ApplyShovel(settings);
			ApplyGhouls(settings);
			ApplySacrifice(settings);
			ApplyTombstone(settings);
		}

		private static void ApplyShovel(MorticianSettings settings)
		{
			SwingShovel.damageCoefficient = AsCoefficient(settings.ShovelDamagePercent);
			BaseLaunchedState.damageCoefficient = AsCoefficient(settings.LaunchDamagePercent);
		}

		private static void ApplyGhouls(MorticianSettings settings)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			GhoulMelee.damageCoefficient = AsCoefficient(settings.GhoulBiteDamagePercent);
			ClingState.damageCoefficient = AsCoefficient(settings.GhoulBiteDamagePercent);
			BileSpit.damageCoefficient = AsCoefficient(settings.GhoulSpitDamagePercent);
			ApplySpitProcCoefficient(settings);
			ApplyToBodies("Ghoul", MorrisPlugin.GhoulBodyPrefab, MorrisPlugin.GhoulBodyIndex, delegate(CharacterBody body)
			{
				ApplyGhoulStats(body, settings);
			});
		}

		private static void ApplySacrifice(MorticianSettings settings)
		{
			GhoulDeath.sacrificedDamageCoefficient = AsCoefficient(settings.SacrificeDamagePercent);
			GhoulDeath.sacrificedRadius = settings.SacrificeRadius.Value;
			Sacrifice.sacrificePercentHealAmount = AsCoefficient(settings.SacrificeHealPercent);
		}

		private static void ApplyTombstone(MorticianSettings settings)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			TombstoneController.soulOrbDamage = AsCoefficient(settings.SoulOrbDamagePercent);
			TombstoneController.spawnTime = settings.TombstoneGhoulSpawnInterval.Value;
			SetRaiseCooldowns(settings);
			ApplyToBodies("Tombstone", MorrisPlugin.TombstoneBodyPrefab, MorrisPlugin.TombstoneBodyIndex, delegate(CharacterBody body)
			{
				ApplyDamageStats(body, settings.TombstoneBaseDamage, settings.TombstoneDamagePerLevel);
			});
		}

		private static void SetRaiseCooldowns(MorticianSettings settings)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)TombstoneRaiseSkills.GhoulSpawn))
			{
				return;
			}
			TombstoneRaiseSkills.GhoulSpawn.baseRechargeInterval = settings.TombstoneGhoulSpawnInterval.Value;
			TombstoneRaiseSkills.GhoulRaise.baseRechargeInterval = settings.RestlessGraveCooldown.Value;
			foreach (CharacterBody item in LiveBodies.Of(MorrisPlugin.TombstoneBodyIndex))
			{
				GenericSkill[] allSkills = item.skillLocator.allSkills;
				for (int i = 0; i < allSkills.Length; i++)
				{
					allSkills[i].RecalculateValues();
				}
			}
		}

		private static void ApplyCooldowns(MorticianSettings settings)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			SkillLocator val = (Object.op_Implicit((Object)(object)MorrisPlugin.MorrisBodyPrefab) ? MorrisPlugin.MorrisBodyPrefab.GetComponent<SkillLocator>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Mortician skill locator not found; cooldowns were not applied.");
				return;
			}
			SetCooldown(val.secondary, settings.RaiseDeadCooldown);
			SetCooldown(val.utility, settings.SacrificeCooldown);
			SetCooldown(val.special, settings.TombstoneCooldown);
			if (Object.op_Implicit((Object)(object)RestlessGraveSkill.Definition))
			{
				RestlessGraveSkill.Definition.baseRechargeInterval = settings.TombstoneCooldown.Value;
			}
			foreach (CharacterBody item in LiveBodies.Of(MorrisPlugin.MorrisBodyIndex))
			{
				RefreshCooldowns(item.skillLocator);
			}
		}

		private static void SetCooldown(GenericSkill skillSlot, PresetSetting<float> cooldown)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			Variant[] variants = skillSlot.skillFamily.variants;
			for (int i = 0; i < variants.Length; i++)
			{
				variants[i].skillDef.baseRechargeInterval = cooldown.Value;
			}
		}

		private static void RefreshCooldowns(SkillLocator skills)
		{
			skills.secondary.RecalculateValues();
			skills.utility.RecalculateValues();
			skills.special.RecalculateValues();
		}

		private static void ApplySpitProcCoefficient(MorticianSettings settings)
		{
			ProjectileController val = (Object.op_Implicit((Object)(object)BileSpit.spitPrefab) ? BileSpit.spitPrefab.GetComponent<ProjectileController>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Ghoul spit projectile not found; its proc coefficient was not applied.");
			}
			else
			{
				val.procCoefficient = settings.GhoulSpitProcCoefficient.Value;
			}
		}

		private static void ApplyMorticianStats(CharacterBody body, MorticianSettings settings)
		{
			body.baseMaxHealth = settings.BaseHealth.Value;
			body.levelMaxHealth = settings.HealthPerLevel.Value;
			body.baseRegen = settings.BaseRegen.Value;
			body.levelRegen = settings.RegenPerLevel.Value;
			body.baseArmor = settings.BaseArmor.Value;
			body.levelArmor = settings.ArmorPerLevel.Value;
			body.baseDamage = settings.BaseDamage.Value;
			body.levelDamage = settings.DamagePerLevel.Value;
		}

		private static void ApplyGhoulStats(CharacterBody body, MorticianSettings settings)
		{
			ApplyDamageStats(body, settings.GhoulBaseDamage, settings.GhoulDamagePerLevel);
			body.baseMaxHealth = settings.GhoulBaseHealth.Value;
			body.levelMaxHealth = settings.GhoulHealthPerLevel.Value;
			body.baseRegen = 0f - settings.GhoulDegen.Value;
			body.levelRegen = 0f - settings.GhoulDegenPerLevel.Value;
		}

		private static void ApplyDamageStats(CharacterBody body, PresetSetting<float> baseDamage, PresetSetting<float> damagePerLevel)
		{
			body.baseDamage = baseDamage.Value;
			body.levelDamage = damagePerLevel.Value;
		}

		private static void ApplyToBodies(string bodyName, GameObject bodyPrefab, BodyIndex bodyIndex, Action<CharacterBody> applyStats)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			CharacterBody val = (Object.op_Implicit((Object)(object)bodyPrefab) ? bodyPrefab.GetComponent<CharacterBody>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)(bodyName + " body prefab not found; its stats were not applied."));
				return;
			}
			applyStats(val);
			foreach (CharacterBody item in LiveBodies.Of(bodyIndex))
			{
				applyStats(item);
				item.MarkAllStatsDirty();
			}
		}

		private static float AsCoefficient(PresetSetting<float> percent)
		{
			return percent.Value / 100f;
		}
	}
	internal static class RiskOfOptionsMenu
	{
		[Serializable]
		private sealed class Manifest
		{
			public string description = "";
		}

		public const string GUID = "com.rune580.riskofoptions";

		public static void Register(BaseUnityPlugin plugin, ManualLogSource log, Func<ConfigEntryBase, bool> isHidden = null)
		{
			if (!Chainloader.PluginInfos.ContainsKey("com.rune580.riskofoptions"))
			{
				return;
			}
			try
			{
				AddToMenu(plugin, isHidden ?? ((Func<ConfigEntryBase, bool>)((ConfigEntryBase _) => false)));
			}
			catch (Exception arg)
			{
				log.LogWarning((object)$"Failed to add settings to Risk of Options: {arg}");
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void AddToMenu(BaseUnityPlugin plugin, Func<ConfigEntryBase, bool> isHidden)
		{
			string gUID = plugin.Info.Metadata.GUID;
			string name = plugin.Info.Metadata.Name;
			foreach (ConfigEntryBase item in from definition in plugin.Config.Keys
				select plugin.Config[definition] into entry
				where !isHidden(entry)
				select entry)
			{
				BaseOption val = OptionFor(item);
				if (val != null)
				{
					ModSettingsManager.AddOption(val, gUID, name);
				}
			}
			string? packageDirectory = Path.GetDirectoryName(plugin.Info.Location) ?? "";
			string text = ManifestDescription(packageDirectory);
			if (!string.IsNullOrEmpty(text))
			{
				ModSettingsManager.SetModDescription(text, gUID, name);
			}
			Sprite val2 = LoadIcon(packageDirectory);
			if (Object.op_Implicit((Object)(object)val2))
			{
				ModSettingsManager.SetModIcon(val2, gUID, name);
			}
		}

		private static BaseOption OptionFor(ConfigEntryBase entry)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			if (!(entry is ConfigEntry<bool> val))
			{
				if (!(entry is ConfigEntry<int> entry2))
				{
					if (!(entry is ConfigEntry<float> entry3))
					{
						if (!(entry is ConfigEntry<string> val2))
						{
							if (!(entry is ConfigEntry<KeyboardShortcut> val3))
							{
								if (entry is ConfigEntry<Color> val4)
								{
									return (BaseOption)new ColorOption(val4);
								}
								if (IsDropdownEnum(entry.SettingType))
								{
									return (BaseOption)new ChoiceOption(entry);
								}
								return null;
							}
							return (BaseOption)new KeyBindOption(val3);
						}
						return (BaseOption)new StringInputFieldOption(val2);
					}
					return FloatOption(entry3);
				}
				return IntOption(entry2);
			}
			return (BaseOption)new CheckBoxOption(val);
		}

		private static BaseOption IntOption(ConfigEntry<int> entry)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			if (((ConfigEntryBase)entry).Description.AcceptableValues is AcceptableValueRange<int> val)
			{
				return (BaseOption)new IntSliderOption(entry, new IntSliderConfig
				{
					min = val.MinValue,
					max = val.MaxValue
				});
			}
			return (BaseOption)new IntFieldOption(entry);
		}

		private static BaseOption FloatOption(ConfigEntry<float> entry)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			if (((ConfigEntryBase)entry).Description.AcceptableValues is AcceptableValueRange<float> val)
			{
				return (BaseOption)new SliderOption(entry, new SliderConfig
				{
					min = val.MinValue,
					max = val.MaxValue,
					FormatString = "{0:0.##}"
				});
			}
			return (BaseOption)new FloatFieldOption(entry);
		}

		private static bool IsDropdownEnum(Type type)
		{
			if (!type.IsEnum || type.IsDefined(typeof(FlagsAttribute), inherit: false))
			{
				return false;
			}
			return (from object value in Enum.GetValues(type)
				select Convert.ToInt64(value, CultureInfo.InvariantCulture) into value
				orderby value
				select value).SequenceEqual(Enumerable.Range(0, Enum.GetValues(type).Length).Select((Func<int, long>)((int position) => position)));
		}

		private static string ManifestDescription(string packageDirectory)
		{
			string path = Path.Combine(packageDirectory, "manifest.json");
			if (!File.Exists(path))
			{
				return null;
			}
			return JsonUtility.FromJson<Manifest>(File.ReadAllText(path))?.description;
		}

		private static Sprite LoadIcon(string packageDirectory)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			string path = Path.Combine(packageDirectory, "icon.png");
			if (!File.Exists(path))
			{
				return null;
			}
			Texture2D val = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(path)))
			{
				return null;
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
		}
	}
	internal static class SkillDescriptions
	{
		private static readonly string TokenPrefix = "BOG_MORRIS_BODY_";

		private static LanguageOverlay _overlay;

		public static void Apply(MorticianSettings settings)
		{
			LanguageOverlay overlay = _overlay;
			if (overlay != null)
			{
				overlay.Remove();
			}
			_overlay = LanguageAPI.AddOverlay(BuildDescriptions(settings));
		}

		private static Dictionary<string, string> BuildDescriptions(MorticianSettings settings)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			string key = TokenPrefix + "PASSIVE_DESCRIPTION";
			dictionary[key] = PassiveDescription(settings.GhoulOnKillTriggerChance.Value, settings.SacrificeGuaranteesOnKill.Value);
			string key2 = TokenPrefix + "PRIMARY_SHOVEL_DESCRIPTION";
			dictionary[key2] = "Swing your shovel for " + Damage(settings.ShovelDamagePercent.Value) + ". Hit ghouls and tombstones to <style=cIsUtility>launch</style> them for " + Damage(settings.LaunchDamagePercent.Value) + ".";
			string key3 = TokenPrefix + "SECONDARY_GHOUL_DESCRIPTION";
			dictionary[key3] = "<style=cIsUtility>Soulbound</style>. Spawn a ghoul on the ground in front of you. Ghouls bite for " + Damage(settings.GhoulBiteDamagePercent.Value) + ", and spit <style=cIsDamage>Blighted</style> bile for " + Damage(settings.GhoulSpitDamagePercent.Value) + ".";
			string key4 = TokenPrefix + "UTILITY_LANTERN_DESCRIPTION";
			dictionary[key4] = "<style=cIsHealth>Detonate</style> the target ghoul for " + Damage(settings.SacrificeDamagePercent.Value) + ", and <style=cIsHealing>heal " + Number(settings.SacrificeHealPercent.Value) + "% of your maximum health</style>.";
			string key5 = TokenPrefix + "SPECIAL_TOMBSTONE_DESCRIPTION";
			dictionary[key5] = TombstoneDescription(settings);
			string nameToken = RestlessGraveSkill.NameToken;
			dictionary[nameToken] = "Restless Grave";
			string descriptionToken = RestlessGraveSkill.DescriptionToken;
			dictionary[descriptionToken] = TombstoneDescription(settings) + RestlessGraveDescription(settings);
			return dictionary;
		}

		private static string PassiveDescription(float triggerChancePercent, bool sacrificeGuaranteesTrigger)
		{
			if (!(triggerChancePercent >= 100f))
			{
				if (triggerChancePercent <= 0f)
				{
					if (sacrificeGuaranteesTrigger)
					{
						return "<style=cIsHealth>Sacrificed</style> ghouls <style=cIsUtility>activate your On-Kill effects</style>.";
					}
					return "Ghouls do not activate your On-Kill effects.";
				}
				return "Ghouls have a <style=cIsUtility>" + Number(triggerChancePercent) + "% chance</style> to <style=cIsUtility>activate your On-Kill effects</style> when they die." + (sacrificeGuaranteesTrigger ? " <style=cIsHealth>Sacrificed</style> ghouls always do." : "");
			}
			return "Ghouls <style=cIsUtility>activate your On-Kill effects</style> when they die.";
		}

		private static string TombstoneDescription(MorticianSettings settings)
		{
			return "Erect a tombstone" + DescribeDuration(settings.TombstoneDuration.Value) + " that spawns a ghoul every <style=cIsUtility>" + Number(settings.TombstoneGhoulSpawnInterval.Value) + " seconds</style>. Whenever a ghoul is slain, the tombstone generates an <style=cIsDamage>explosive</style> <style=cIsUtility>vengeful soul</style> which it will fire at a nearby enemy for " + Damage(settings.SoulOrbDamagePercent.Value) + ".";
		}

		private static string RestlessGraveDescription(MorticianSettings settings)
		{
			return "\n<color=#d299ff>SCEPTER: Enemies slain within " + Number(settings.RestlessGraveRadius.Value) + "m of a tombstone rise as ghouls, at most once every " + Number(settings.RestlessGraveCooldown.Value) + " seconds per tombstone." + DescribeRisenGhoulLimit(settings.RestlessGraveRisenGhoulLimit.Value) + "</color>";
		}

		private static string DescribeRisenGhoulLimit(int limit)
		{
			if (limit <= 0)
			{
				return "";
			}
			return $" Each tombstone keeps up to {limit} risen ghouls.";
		}

		private static string DescribeDuration(float seconds)
		{
			if (!(seconds > 0f))
			{
				return "";
			}
			return " lasting <style=cIsUtility>" + Number(seconds) + " seconds</style>";
		}

		private static string Damage(float percent)
		{
			return "<style=cIsDamage>" + Number(percent) + "% damage</style>";
		}

		private static string Number(float value)
		{
			return value.ToString("0.##", CultureInfo.InvariantCulture);
		}
	}
	internal enum SoulRecipient
	{
		Newest,
		Nearest,
		Every
	}
	internal static class TombstoneRaiseSkills
	{
		private static readonly string GhoulSpawnName = "DELFOFTHEBLA_TOMBSTONE_GHOUL_SPAWN";

		private static readonly string GhoulRaiseName = "DELFOFTHEBLA_TOMBSTONE_GHOUL_RAISE";

		public static SkillDef GhoulSpawn { get; private set; }

		public static SkillDef GhoulRaise { get; private set; }

		public static bool Register()
		{
			GameObject tombstoneBodyPrefab = MorrisPlugin.TombstoneBodyPrefab;
			SkillLocator val = (Object.op_Implicit((Object)(object)tombstoneBodyPrefab) ? tombstoneBodyPrefab.GetComponent<SkillLocator>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Tombstone skill locator not found; the tombstone keeps Mortician's own ghoul spawn timer.");
				return false;
			}
			GenericSkill val2 = AddHiddenSlot(tombstoneBodyPrefab, "GhoulSpawn", GhoulSpawnName);
			GenericSkill obj = AddHiddenSlot(tombstoneBodyPrefab, "GhoulRaise", GhoulRaiseName);
			val.primary = val2;
			GhoulSpawn = val2.skillFamily.defaultSkillDef;
			GhoulRaise = obj.skillFamily.defaultSkillDef;
			return true;
		}

		public static GenericSkill GhoulSpawnSlotOf(CharacterBody tombstone)
		{
			return SlotOf(tombstone, GhoulSpawn);
		}

		public static GenericSkill GhoulRaiseSlotOf(CharacterBody tombstone)
		{
			return SlotOf(tombstone, GhoulRaise);
		}

		public static bool TryConsume(GenericSkill slot)
		{
			if (!Object.op_Implicit((Object)(object)slot) || slot.stock <= 0)
			{
				return false;
			}
			slot.DeductStock(1);
			return true;
		}

		private static GenericSkill SlotOf(CharacterBody tombstone, SkillDef skillDef)
		{
			if (!Object.op_Implicit((Object)(object)skillDef) || !Object.op_Implicit((Object)(object)tombstone) || !Object.op_Implicit((Object)(object)tombstone.skillLocator))
			{
				return null;
			}
			return tombstone.skillLocator.FindSkillByDef(skillDef);
		}

		private static GenericSkill AddHiddenSlot(GameObject bodyPrefab, string familyName, string skillName)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			SkillDef val = ScriptableObject.CreateInstance<SkillDef>();
			((Object)val).name = skillName;
			val.skillName = skillName;
			val.skillNameToken = skillName;
			val.activationState = new SerializableEntityStateType(typeof(Idle));
			val.dontAllowPastMaxStocks = true;
			Content.AddSkillDef(val);
			GenericSkill obj = Skills.CreateGenericSkillWithSkillFamily(bodyPrefab, familyName, true);
			Skills.AddSkillToFamily(obj.skillFamily, val, (UnlockableDef)null);
			return obj;
		}
	}
}
namespace EvenMoreBalancedMortician.Scepter
{
	internal static class AncientScepterCompat
	{
		private delegate bool TryGetScepterSlot(AncientScepterItem self, CharacterBody body, out SkillSlot slot);

		public const string GUID = "com.DestroyedClone.AncientScepter";

		private static Hook _handleScepterSkillHook;

		private static Hook _tryGetScepterSlotHook;

		private static Func<CharacterBody, bool> _isUpgradeWithheld;

		public static bool IsInstalled => Chainloader.PluginInfos.ContainsKey("com.DestroyedClone.AncientScepter");

		private static AncientScepterItem Scepter => ItemBase<AncientScepterItem>.instance;

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void RegisterSpecialUpgrade(SkillDef upgrade, string bodyName)
		{
			Scepter.RegisterScepterSkill(upgrade, bodyName, (SkillSlot)3, 0);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void WithholdUpgradeFrom(Func<CharacterBody, bool> isUpgradeWithheld)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			_isUpgradeWithheld = isUpgradeWithheld;
			_handleScepterSkillHook = new Hook((MethodBase)ScepterMethod("HandleScepterSkill"), (Delegate)new Func<Func<AncientScepterItem, CharacterBody, bool, bool>, AncientScepterItem, CharacterBody, bool, bool>(SkipWithheldUpgrade));
			_tryGetScepterSlotHook = new Hook((MethodBase)ScepterMethod("TryGetScepterSlot"), (Delegate)new <>F{00000400}<TryGetScepterSlot, AncientScepterItem, CharacterBody, SkillSlot, bool>(SkipWithheldCooldownReduction));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void ReapplyUpgrade(CharacterBody body)
		{
			Scepter.HandleScepterSkill(body, false);
		}

		private static MethodInfo ScepterMethod(string name)
		{
			return typeof(AncientScepterItem).GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		}

		private static bool SkipWithheldUpgrade(Func<AncientScepterItem, CharacterBody, bool, bool> orig, AncientScepterItem self, CharacterBody body, bool forceOff)
		{
			if (!_isUpgradeWithheld(body))
			{
				return orig(self, body, forceOff);
			}
			return false;
		}

		private static bool SkipWithheldCooldownReduction(TryGetScepterSlot orig, AncientScepterItem self, CharacterBody body, out SkillSlot slot)
		{
			if (!_isUpgradeWithheld(body))
			{
				return orig(self, body, out slot);
			}
			slot = (SkillSlot)(-1);
			return false;
		}
	}
	internal sealed class GraveRaiser : MonoBehaviour
	{
		private readonly List<CharacterBody> _risenGhouls = new List<CharacterBody>();

		private TombstoneController _tombstone;

		private CharacterBody _tombstoneBody;

		private GenericSkill _raiseCooldown;

		private TeamIndex Team => _tombstoneBody.teamComponent.teamIndex;

		private CharacterBody Owner => MinionOwner.BodyOf(_tombstoneBody);

		private void Awake()
		{
			_tombstone = ((Component)this).GetComponent<TombstoneController>();
			_tombstoneBody = ((Component)this).GetComponent<CharacterBody>();
			_raiseCooldown = TombstoneRaiseSkills.GhoulRaiseSlotOf(_tombstoneBody);
		}

		private void OnEnable()
		{
			InstanceTracker.Add<GraveRaiser>(this);
		}

		private void OnDisable()
		{
			InstanceTracker.Remove<GraveRaiser>(this);
		}

		public bool CanRaise(TeamIndex victimTeam, int risenGhoulLimit)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)_raiseCooldown) || _raiseCooldown.stock <= 0 || victimTeam == Team || (int)victimTeam == 0)
			{
				return false;
			}
			if (!RestlessGraveSkill.IsEquippedBy(Owner))
			{
				return false;
			}
			_risenGhouls.RemoveAll(IsGone);
			if (risenGhoulLimit > 0)
			{
				return _risenGhouls.Count < risenGhoulLimit;
			}
			return true;
		}

		public void Raise(Vector3 corpsePosition)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			_raiseCooldown.DeductStock(1);
			CharacterMaster val = new MasterSummon
			{
				masterPrefab = GhoulMinion.ghoulMasterPrefab,
				ignoreTeamMemberLimit = true,
				teamIndexOverride = Team,
				summonerBodyObject = ((Component)Owner).gameObject,
				position = GroundNear(corpsePosition),
				rotation = ((Component)this).transform.rotation
			}.Perform();
			CharacterBody val2 = (Object.op_Implicit((Object)(object)val) ? val.GetBody() : null);
			if (Object.op_Implicit((Object)(object)val2))
			{
				_risenGhouls.Add(val2);
			}
		}

		private Vector3 GroundNear(Vector3 position)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			NodeGraph nodeGraph = _tombstone.nodeGraph;
			if (!Object.op_Implicit((Object)(object)nodeGraph))
			{
				return position;
			}
			NodeIndex val = nodeGraph.FindClosestNodeWithFlagConditions(position, (HullClassification)0, (NodeFlags)0, (NodeFlags)4, false);
			Vector3 result = default(Vector3);
			if (!nodeGraph.GetNodePosition(val, ref result))
			{
				return position;
			}
			return result;
		}

		private static bool IsGone(CharacterBody ghoul)
		{
			if (Object.op_Implicit((Object)(object)ghoul))
			{
				return !ghoul.healthComponent.alive;
			}
			return true;
		}
	}
	internal sealed class RaiseRadiusIndicator : MonoBehaviour
	{
		private static readonly string IndicatorPrefabKey = "RoR2/Base/Common/TeamAreaIndicator, GroundOnly.prefab";

		private static GameObject _indicatorPrefab;

		private static PresetSetting<float> _radius;

		private static ConfigEntry<bool> _isShown;

		private CharacterBody _tombstone;

		private GameObject _indicator;

		public static void Configure(PresetSetting<float> radius, ConfigEntry<bool> isShown)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			_radius = radius;
			_isShown = isShown;
			_indicatorPrefab = Addressables.LoadAssetAsync<GameObject>((object)IndicatorPrefabKey).WaitForCompletion();
			if (!Object.op_Implicit((Object)(object)_indicatorPrefab))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Area indicator prefab not found; the Restless Grave radius will not be shown.");
			}
		}

		private void Start()
		{
			_tombstone = ((Component)this).GetComponent<CharacterBody>();
			if (Object.op_Implicit((Object)(object)_indicatorPrefab))
			{
				_indicator = Object.Instantiate<GameObject>(_indicatorPrefab, ((Component)this).transform);
				_indicator.GetComponentInChildren<TeamAreaIndicator>().teamComponent = ((Component)this).GetComponent<TeamComponent>();
				_indicator.SetActive(false);
			}
		}

		private void Update()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)_indicator))
			{
				bool flag = _isShown.Value && _radius.Value > 0f && RestlessGraveSkill.IsEquippedBy(MinionOwner.BodyOf(_tombstone));
				if (_indicator.activeSelf != flag)
				{
					_indicator.SetActive(flag);
				}
				if (flag)
				{
					_indicator.transform.localScale = Vector3.one * (_radius.Value / ((Component)this).transform.lossyScale.x);
				}
			}
		}
	}
	internal static class RestlessGrave
	{
		private static Hook _tombstoneStartHook;

		private static PresetSetting<float> _radius;

		private static PresetSetting<int> _risenGhoulLimit;

		public static void Install(PresetSetting<float> radius, PresetSetting<int> risenGhoulLimit, ConfigEntry<bool> showRadius)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			_radius = radius;
			_risenGhoulLimit = risenGhoulLimit;
			RaiseRadiusIndicator.Configure(radius, showRadius);
			_tombstoneStartHook = new Hook((MethodBase)MorticianMethods.TombstoneStart, (Delegate)new Action<Action<TombstoneController>, TombstoneController>(AddRestlessGraveComponents));
			GlobalEventManager.onDeathProcServer += RaiseSlainEnemy;
		}

		private static void AddRestlessGraveComponents(Action<TombstoneController> orig, TombstoneController self)
		{
			orig(self);
			((Component)self).gameObject.AddComponent<RaiseRadiusIndicator>();
			if (NetworkServer.active)
			{
				((Component)self).gameObject.AddComponent<GraveRaiser>();
			}
		}

		private static void RaiseSlainEnemy(DamageReport report)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkServer.active && Object.op_Implicit((Object)(object)report.victimMaster) && Object.op_Implicit((Object)(object)report.victimBody))
			{
				Vector3 corePosition = report.victimBody.corePosition;
				GraveRaiser graveRaiser = NearestReadyGrave(report.victimTeamIndex, corePosition);
				if (Object.op_Implicit((Object)(object)graveRaiser))
				{
					graveRaiser.Raise(corePosition);
				}
			}
		}

		private static GraveRaiser NearestReadyGrave(TeamIndex victimTeam, Vector3 corpsePosition)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			float radiusSquared = _radius.Value * _radius.Value;
			return (from grave in InstanceTracker.GetInstancesList<GraveRaiser>()
				where DistanceSquared(grave, corpsePosition) <= radiusSquared
				orderby DistanceSquared(grave, corpsePosition)
				select grave).FirstOrDefault((GraveRaiser grave) => grave.CanRaise(victimTeam, _risenGhoulLimit.Value));
		}

		private static float DistanceSquared(GraveRaiser grave, Vector3 position)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)grave).transform.position - position;
			return ((Vector3)(ref val)).sqrMagnitude;
		}
	}
	internal static class RestlessGraveSkill
	{
		private static readonly string SkillName = "DELFOFTHEBLA_MORTICIAN_SPECIAL_RESTLESS_GRAVE";

		public static readonly string NameToken = SkillName + "_NAME";

		public static readonly string DescriptionToken = SkillName + "_DESCRIPTION";

		private static PresetSetting<bool> _enabled;

		public static SkillDef Definition { get; private set; }

		public static void Register(PresetSetting<bool> enabled)
		{
			_enabled = enabled;
			GameObject morrisBodyPrefab = MorrisPlugin.MorrisBodyPrefab;
			SkillLocator val = (Object.op_Implicit((Object)(object)morrisBodyPrefab) ? morrisBodyPrefab.GetComponent<SkillLocator>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Mortician skill locator not found; the Ancient Scepter will not upgrade Tombstone.");
				return;
			}
			Definition = Object.Instantiate<SkillDef>(val.special.skillFamily.variants[0].skillDef);
			((Object)Definition).name = SkillName;
			Definition.skillName = SkillName;
			Definition.skillNameToken = NameToken;
			Definition.skillDescriptionToken = DescriptionToken;
			Definition.icon = ScepterIcon.TintedCopyOf(Definition.icon);
			ContentAddition.AddSkillDef(Definition);
			AncientScepterCompat.RegisterSpecialUpgrade(Definition, ((Object)morrisBodyPrefab).name);
			AncientScepterCompat.WithholdUpgradeFrom(IsWithheldFrom);
		}

		public static void ApplyEnabledSetting()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Definition))
			{
				return;
			}
			foreach (CharacterBody item in LiveBodies.Of(MorrisPlugin.MorrisBodyIndex))
			{
				if (_enabled.Value)
				{
					AncientScepterCompat.ReapplyUpgrade(item);
				}
				else
				{
					item.skillLocator.special.UnsetSkillOverride((object)item, Definition, (SkillOverridePriority)2);
				}
				item.MarkAllStatsDirty();
			}
		}

		public static bool IsEquippedBy(CharacterBody body)
		{
			if (Object.op_Implicit((Object)(object)Definition) && Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.skillLocator) && Object.op_Implicit((Object)(object)body.skillLocator.special))
			{
				return (Object)(object)body.skillLocator.special.skillDef == (Object)(object)Definition;
			}
			return false;
		}

		private static bool IsWithheldFrom(CharacterBody body)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!_enabled.Value)
			{
				return body.bodyIndex == MorrisPlugin.MorrisBodyIndex;
			}
			return false;
		}
	}
	internal static class ScepterIcon
	{
		private static readonly float ScepterPurpleHue = 0.75f;

		public static Sprite TintedCopyOf(Sprite source)
		{
			//IL_002f: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)source))
			{
				return source;
			}
			Texture2D obj = ReadableCopyOf((Texture)(object)source.texture);
			obj.SetPixels32(TintAll(obj.GetPixels32()));
			obj.Apply();
			float x = source.pivot.x;
			Rect rect = source.rect;
			float num = x / ((Rect)(ref rect)).width;
			float y = source.pivot.y;
			rect = source.rect;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(num, y / ((Rect)(ref rect)).height);
			return Sprite.Create(obj, source.textureRect, val, source.pixelsPerUnit);
		}

		private static Texture2D ReadableCopyOf(Texture source)
		{
			//IL_0035: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0);
			Graphics.Blit(source, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(source.width, source.height, (TextureFormat)4, false);
			val.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0);
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			return val;
		}

		private static Color32[] TintAll(Color32[] pixels)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < pixels.Length; i++)
			{
				pixels[i] = Tint(pixels[i]);
			}
			return pixels;
		}

		private static Color32 Tint(Color32 pixel)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			float num = default(float);
			float num2 = default(float);
			float num3 = default(float);
			Color.RGBToHSV(Color32.op_Implicit(pixel), ref num, ref num2, ref num3);
			Color32 result = Color32.op_Implicit(Color.HSVToRGB(ScepterPurpleHue, num2, num3));
			result.a = pixel.a;
			return result;
		}
	}
}
namespace EvenMoreBalancedMortician.Presets
{
	internal interface IPresetSetting
	{
		string SerializedLocalValue { get; }

		void ApplyPreset(MorticianPreset preset);

		bool Matches(MorticianPreset preset);

		void UseHostValue(string serializedValue);

		void UseLocalValue();
	}
	internal enum MorticianPreset
	{
		Original,
		BalancedMortician,
		EvenMoreBalanced,
		Custom
	}
	internal sealed class PresetSelector
	{
		private readonly ConfigFile _config;

		private readonly ConfigEntry<MorticianPreset> _preset;

		private readonly IReadOnlyList<IPresetSetting> _settings;

		private bool _isRewritingSettings;

		public event Action SettingsChanged;

		public PresetSelector(ConfigFile config, ConfigEntry<MorticianPreset> preset, ConfigEntry<string> configVersion, string modVersion, IReadOnlyList<IPresetSetting> settings)
		{
			_config = config;
			_preset = preset;
			_settings = settings;
			UpdatePresetFromEarlierVersion(configVersion, modVersion);
			SelectCustomIfSettingsDiverge();
			config.SettingChanged += OnSettingChanged;
		}

		private void UpdatePresetFromEarlierVersion(ConfigEntry<string> configVersion, string modVersion)
		{
			if (!(configVersion.Value == modVersion))
			{
				ApplySelectedPreset();
				configVersion.Value = modVersion;
			}
		}

		private void OnSettingChanged(object sender, SettingChangedEventArgs args)
		{
			if (!_isRewritingSettings)
			{
				if ((object)args.ChangedSetting == _preset)
				{
					ApplySelectedPreset();
				}
				else
				{
					SelectCustomIfSettingsDiverge();
				}
				this.SettingsChanged?.Invoke();
			}
		}

		private void ApplySelectedPreset()
		{
			if (_preset.Value == MorticianPreset.Custom)
			{
				return;
			}
			RewriteSettings(delegate
			{
				foreach (IPresetSetting setting in _settings)
				{
					setting.ApplyPreset(_preset.Value);
				}
			});
		}

		private void SelectCustomIfSettingsDiverge()
		{
			if (_preset.Value != MorticianPreset.Custom && !_settings.All((IPresetSetting setting) => setting.Matches(_preset.Value)))
			{
				RewriteSettings(delegate
				{
					_preset.Value = MorticianPreset.Custom;
				});
			}
		}

		private void RewriteSettings(Action rewrite)
		{
			bool saveOnConfigSet = _config.SaveOnConfigSet;
			_config.SaveOnConfigSet = false;
			_isRewritingSettings = true;
			try
			{
				rewrite();
			}
			finally
			{
				_isRewritingSettings = false;
				_config.SaveOnConfigSet = saveOnConfigSet;
				_config.Save();
			}
		}
	}
	internal sealed class PresetSetting<T>(ConfigEntry<T> entry, PresetValues<T> presetValues) : IPresetSetting
	{
		private bool _hasHostValue;

		private T _hostValue;

		public T Value
		{
			get
			{
				if (!_hasHostValue)
				{
					return <entry>P.Value;
				}
				return _hostValue;
			}
		}

		public string SerializedLocalValue => TomlTypeConverter.ConvertToString((object)<entry>P.Value, typeof(T));

		public void ApplyPreset(MorticianPreset preset)
		{
			<entry>P.Value = <presetValues>P.For(preset);
		}

		public bool Matches(MorticianPreset preset)
		{
			return EqualityComparer<T>.Default.Equals(<entry>P.Value, <presetValues>P.For(preset));
		}

		public void UseHostValue(string serializedValue)
		{
			_hostValue = TomlTypeConverter.ConvertToValue<T>(serializedValue);
			_hasHostValue = true;
		}

		public void UseLocalValue()
		{
			_hasHostValue = false;
		}
	}
	internal readonly record struct PresetValues<T>(T Original, T BalancedMortician, T EvenMoreBalanced)
	{
		public T For(MorticianPreset preset)
		{
			return preset switch
			{
				MorticianPreset.Original => Original, 
				MorticianPreset.BalancedMortician => BalancedMortician, 
				MorticianPreset.EvenMoreBalanced => EvenMoreBalanced, 
				_ => throw new ArgumentOutOfRangeException("preset", preset, "Custom has no preset values."), 
			};
		}
	}
}
namespace EvenMoreBalancedMortician.Patches
{
	internal static class DetonationDamagePatch
	{
		private static Hook _explodeHook;

		private static PresetSetting<bool> _scalesWithMortician;

		public static void Install(PresetSetting<bool> scalesWithMortician)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			_scalesWithMortician = scalesWithMortician;
			_explodeHook = new Hook((MethodBase)typeof(GhoulDeath).GetMethod("Explode"), (Delegate)new Action<Action<GhoulDeath>, GhoulDeath>(ExplodeWithDetonationDamageStat));
		}

		private static void ExplodeWithDetonationDamageStat(Action<GhoulDeath> orig, GhoulDeath self)
		{
			if (!_scalesWithMortician.Value)
			{
				orig(self);
				return;
			}
			float damageStat = ((BaseState)self).damageStat;
			((BaseState)self).damageStat = DetonationDamageStat(self);
			orig(self);
			((BaseState)self).damageStat = damageStat;
		}

		private static float DetonationDamageStat(GhoulDeath ghoulDeath)
		{
			MorrisMinionController minionController = ghoulDeath.minionController;
			GameObject val = (Object.op_Implicit((Object)(object)minionController.sacrificeOwner) ? minionController.sacrificeOwner : minionController.owner);
			CharacterBody val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<CharacterBody>() : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return ((BaseState)ghoulDeath).damageStat;
			}
			return val2.damage;
		}
	}
	internal static class DyingGhoul
	{
		private static readonly ScopedValue<MorrisMinionController> _scope = new ScopedValue<MorrisMinionController>();

		public static MorrisMinionController Current => _scope.Current;

		public static void Install()
		{
			_scope.SetDuring(MorticianMethods.MinionDeathStart);
		}
	}
	internal static class GhoulAspectPatch
	{
		private static readonly string AspectNameFragment = "Aspect";

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

		private static Hook _minionStartHook;

		private static Hook _minionDeathStartHook;

		private static PresetSetting<float> _inheritChancePercent;

		public static void Install(PresetSetting<float> inheritChancePercent)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			_inheritChancePercent = inheritChancePercent;
			_minionStartHook = new Hook((MethodBase)MorticianMethods.MinionStart, (Delegate)new Action<Action<MorrisMinionController>, MorrisMinionController>(InheritAspects));
			_minionDeathStartHook = new Hook((MethodBase)MorticianMethods.MinionDeathStart, (Delegate)new Action<Action<MorrisMinionController>, MorrisMinionController>(ShedAspectsBeforeOnKillProc));
		}

		private static void InheritAspects(Action<MorrisMinionController> orig, MorrisMinionController self)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			orig(self);
			if (!NetworkServer.active || (int)self.minionType != 1 || _inheritChancePercent.Value <= 0f)
			{
				return;
			}
			Inventory val = (Object.op_Implicit((Object)(object)self.characterBody) ? self.characterBody.inventory : null);
			CharacterMaster val2 = (Object.op_Implicit((Object)(object)self.ownerBody) ? self.ownerBody.master : null);
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val2.inventory))
			{
				return;
			}
			InheritAspectEquipment(val2, val);
			foreach (ItemIndex item in val2.inventory.itemAcquisitionOrder)
			{
				if (IsAspectItem(item))
				{
					LogFirstDetection("item", ((Object)ItemCatalog.GetItemDef(item)).name);
					InheritAspectItemStacks(item, val2, val);
				}
			}
		}

		private static void InheritAspectEquipment(CharacterMaster owner, Inventory ghoulInventory)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			EquipmentIndex currentEquipmentIndex = owner.inventory.currentEquipmentIndex;
			if (IsAspectEquipment(currentEquipmentIndex))
			{
				LogFirstDetection("equipment", ((Object)EquipmentCatalog.GetEquipmentDef(currentEquipmentIndex)).name);
				if (RollInheritChance(owner))
				{
					EquipmentLocation val = ghoulInventory.FindBestEquipmentLocationOrCurrent(ref EquipmentLocationQueryArgs.defaultPickup);
					ghoulInventory.SetEquipmentIndex(currentEquipmentIndex, ref val);
				}
			}
		}

		private static void InheritAspectItemStacks(ItemIndex aspect, CharacterMaster owner, Inventory ghoulInventory)
		{
			//IL_0008: 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)
			int num = 0;
			int itemCountEffective = owner.inventory.GetItemCountEffective(aspect);
			for (int i = 0; i < itemCountEffective; i++)
			{
				if (RollInheritChance(owner))
				{
					num++;
				}
			}
			if (num > 0)
			{
				ghoulInventory.GiveItemPermanent(aspect, num);
			}
		}

		private static void ShedAspectsBeforeOnKillProc(Action<MorrisMinionController> orig, MorrisMinionController self)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			if (NetworkServer.active && (int)self.minionType == 1 && Object.op_Implicit((Object)(object)self.characterBody))
			{
				ShedAspects(self.characterBody);
			}
			orig(self);
		}

		private static void ShedAspects(CharacterBody ghoul)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			BuffIndex[] array = ((IEnumerable<BuffIndex>)BuffCatalog.eliteBuffIndices).Where((Func<BuffIndex, bool>)ghoul.HasBuff).ToArray();
			if (array.Length != 0)
			{
				if (Object.op_Implicit((Object)(object)ghoul.inventory))
				{
					RemoveAspects(ghoul.inventory);
				}
				BuffIndex[] array2 = array;
				foreach (BuffIndex val in array2)
				{
					ghoul.ClearTimedBuffs(val);
					ghoul.SetBuffCount(val, 0);
				}
				RefreshEliteStatus(ghoul);
			}
		}

		private static void RemoveAspects(Inventory ghoulInventory)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (IsAspectEquipment(ghoulInventory.currentEquipmentIndex))
			{
				EquipmentLocation activeEquipmentLocation = ghoulInventory.activeEquipmentLocation;
				ghoulInventory.SetEquipmentIndex((EquipmentIndex)(-1), ref activeEquipmentLocation);
			}
			ItemIndex[] array = ghoulInventory.itemAcquisitionOrder.Where(IsAspectItem).ToArray();
			foreach (ItemIndex val in array)
			{
				ghoulInventory.ResetItemPermanent(val);
			}
		}

		private static void RefreshEliteStatus(CharacterBody ghoul)
		{
			ghoul.RecalculateStats();
		}

		private static bool IsAspectEquipment(EquipmentIndex equipment)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			EquipmentDef equipmentDef = EquipmentCatalog.GetEquipmentDef(equipment);
			if (Object.op_Implicit((Object)(object)equipmentDef) && Object.op_Implicit((Object)(object)equipmentDef.passiveBuffDef))
			{
				return equipmentDef.passiveBuffDef.isElite;
			}
			return false;
		}

		private static bool IsAspectItem(ItemIndex item)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			ItemDef itemDef = ItemCatalog.GetItemDef(item);
			if (!itemDef.hidden)
			{
				return ((Object)itemDef).name.IndexOf(AspectNameFragment, StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return false;
		}

		private static bool RollInheritChance(CharacterMaster owner)
		{
			return Util.CheckRoll(_inheritChancePercent.Value, owner);
		}

		private static void LogFirstDetection(string aspectKind, string aspectName)
		{
			if (_detectedAspects.Add(aspectKind + ":" + aspectName))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogInfo((object)("Ghouls can inherit aspect " + aspectKind + ": " + aspectName));
			}
		}
	}
	internal static class GhoulEquipmentPatch
	{
		private static readonly ScopedValue<SpawnGhoul> _morticianSummoning = new ScopedValue<SpawnGhoul>();

		private static readonly ScopedValue<TombstoneController> _tombstoneSummoning = new ScopedValue<TombstoneController>();

		private static Hook _equipmentCopyHook;

		public static void Install()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			_morticianSummoning.SetDuring(typeof(SpawnGhoul).GetMethod("AttemptSpawnGhoul", BindingFlags.Instance | BindingFlags.NonPublic));
			_tombstoneSummoning.SetDuring(typeof(TombstoneController).GetMethod("SpawnGhoulAtClosestNode"));
			_equipmentCopyHook = new Hook((MethodBase)typeof(Inventory).GetMethod("CopyEquipmentFrom", new Type[2]
			{
				typeof(Inventory),
				typeof(bool)
			}), (Delegate)new Action<Action<Inventory, Inventory, bool>, Inventory, Inventory, bool>(SkipSummonerEquipmentCopy));
		}

		private static void SkipSummonerEquipmentCopy(Action<Inventory, Inventory, bool> orig, Inventory self, Inventory other, bool includeChargeData)
		{
			if (!IsSummonerCopyIntoGhoul(self, other))
			{
				orig(self, other, includeChargeData);
			}
		}

		private static bool IsSummonerCopyIntoGhoul(Inventory target, Inventory source)
		{
			Inventory val = SummonerInventory();
			if (Object.op_Implicit((Object)(object)val) && (Object)(object)source == (Object)(object)val)
			{
				return BelongsToGhoul(target);
			}
			return false;
		}

		private static Inventory SummonerInventory()
		{
			SpawnGhoul current = _morticianSummoning.Current;
			if (current != null)
			{
				return ((EntityState)current).characterBody.inventory;
			}
			TombstoneController current2 = _tombstoneSummoning.Current;
			if (!Object.op_Implicit((Object)(object)current2))
			{
				return null;
			}
			return current2.characterBody.inventory;
		}

		private static bool BelongsToGhoul(Inventory inventory)
		{
			CharacterMaster val = default(CharacterMaster);
			if (((Component)inventory).TryGetComponent<CharacterMaster>(ref val))
			{
				return (Object)(object)val.bodyPrefab == (Object)(object)MorrisPlugin.GhoulBodyPrefab;
			}
			return false;
		}
	}
	internal static class GhoulLimitPatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static GetDeployableSameSlotLimit <0>__GetGhoulLimit;

			public static Action<Action<MorrisMinionController>, MorrisMinionController> <1>__TrackGhoulAsDeployable;
		}

		private static Hook _minionStartHook;

		private static PresetSetting<int> _ghoulLimit;

		public static void Install(PresetSetting<int> limit)
		{
			//IL_0021: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			_ghoulLimit = limit;
			object obj = <>O.<0>__GetGhoulLimit;
			if (obj == null)
			{
				GetDeployableSameSlotLimit val = GetGhoulLimit;
				<>O.<0>__GetGhoulLimit = val;
				obj = (object)val;
			}
			Morris.ghoulSlot = DeployableAPI.RegisterDeployableSlot((GetDeployableSameSlotLimit)obj);
			EnsureGhoulsAreDeployable();
			_minionStartHook = new Hook((MethodBase)MorticianMethods.MinionStart, (Delegate)new Action<Action<MorrisMinionController>, MorrisMinionController>(TrackGhoulAsDeployable));
		}

		private static void EnsureGhoulsAreDeployable()
		{
			GameObject ghoulMasterPrefab = GhoulMinion.ghoulMasterPrefab;
			if (!Object.op_Implicit((Object)(object)ghoulMasterPrefab))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Ghoul master prefab not found; the Ghoul Limit setting will not work.");
			}
			else if (!Object.op_Implicit((Object)(object)ghoulMasterPrefab.GetComponent<Deployable>()))
			{
				ghoulMasterPrefab.AddComponent<Deployable>();
			}
		}

		private static int GetGhoulLimit(CharacterMaster master, int deployableCountMultiplier)
		{
			if (_ghoulLimit.Value <= 0)
			{
				return int.MaxValue;
			}
			return _ghoulLimit.Value;
		}

		private static void TrackGhoulAsDeployable(Action<MorrisMinionController> orig, MorrisMinionController self)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			orig(self);
			if (!MorticianTracksGhouls() && IsOwnedGhoulOnServer(self))
			{
				CharacterMaster master = self.characterBody.master;
				Deployable component = ((Component)master).GetComponent<Deployable>();
				component.onUndeploy = new UnityEvent();
				component.onUndeploy.AddListener(new UnityAction(master.TrueKill));
				self.ownerMaster.AddDeployable(component, Morris.ghoulSlot);
			}
		}

		private static bool MorticianTracksGhouls()
		{
			return Config.ghoulLimit.Value > 0;
		}

		private static bool IsOwnedGhoulOnServer(MorrisMinionController minion)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			if (NetworkServer.active && (int)minion.minionType == 1)
			{
				return Object.op_Implicit((Object)(object)minion.ownerMaster);
			}
			return false;
		}
	}
	internal static class GhoulOnKillPatch
	{
		private static Hook _onKillTriggerHook;

		private static PresetSetting<float> _triggerChancePercent;

		private static PresetSetting<bool> _sacrificeGuaranteesTrigger;

		public static void Install(PresetSetting<float> triggerChancePercent, PresetSetting<bool> sacrificeGuaranteesTrigger)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			_triggerChancePercent = triggerChancePercent;
			_sacrificeGuaranteesTrigger = sacrificeGuaranteesTrigger;
			_onKillTriggerHook = new Hook((MethodBase)typeof(GlobalEventManager).GetMethod("TriggerCharacterDeathProc"), (Delegate)new Action<Action<GlobalEventManager, DamageReport>, GlobalEventManager, DamageReport>(RollForGhoulOnKillTrigger));
		}

		private static void RollForGhoulOnKillTrigger(Action<GlobalEventManager, DamageReport> orig, GlobalEventManager self, DamageReport death)
		{
			MorrisMinionController current = DyingGhoul.Current;
			if (!IsOwnDeathProc(current, death) || PassesOnKillRoll(current, death))
			{
				orig(self, death);
			}
		}

		private static bool IsOwnDeathProc(MorrisMinionController ghoul, DamageReport death)
		{
			if (Object.op_Implicit((Object)(object)ghoul))
			{
				return (Object)(object)death.victim == (Object)(object)ghoul.healthComponent;
			}
			return false;
		}

		private static bool PassesOnKillRoll(MorrisMinionController ghoul, DamageReport death)
		{
			if (!IsGuaranteed(ghoul))
			{
				return Util.CheckRoll(_triggerChancePercent.Value, death.attackerMaster);
			}
			return true;
		}

		private static bool IsGuaranteed(MorrisMinionController ghoul)
		{
			if (ghoul.sacrificed)
			{
				return _sacrificeGuaranteesTrigger.Value;
			}
			return false;
		}
	}
	internal static class GhoulRaiseCooldownPatch
	{
		private static Hook _tombstoneStartHook;

		private static Hook _tombstoneUpdateHook;

		private static PresetSetting<bool> _usesCooldownReduction;

		public static void Install(PresetSetting<bool> usesCooldownReduction)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			_usesCooldownReduction = usesCooldownReduction;
			if (TombstoneRaiseSkills.Register())
			{
				_tombstoneStartHook = new Hook((MethodBase)MorticianMethods.TombstoneStart, (Delegate)new Action<Action<TombstoneController>, TombstoneController>(SwitchToSkillStockSpawning));
				_tombstoneUpdateHook = new Hook((MethodBase)MorticianMethods.TombstoneFixedUpdate, (Delegate)new Action<Action<TombstoneController>, TombstoneController>(SpawnGhoulsFromSkillStock));
			}
		}

		private static void SwitchToSkillStockSpawning(Action<TombstoneController> orig, TombstoneController self)
		{
			orig(self);
			DisableMorticianSpawnTimer(self);
			self.characterBody.onRecalculateStats += ApplyCooldownReductionSetting;
			self.characterBody.MarkAllStatsDirty();
		}

		private static void ApplyCooldownReductionSetting(CharacterBody tombstone)
		{
			GenericSkill val = TombstoneRaiseSkills.GhoulSpawnSlotOf(tombstone);
			GenericSkill val2 = TombstoneRaiseSkills.GhoulRaiseSlotOf(tombstone);
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val2))
			{
				if (!_usesCooldownReduction.Value)
				{
					val.cooldownScale = 1f;
					val.flatCooldownReduction = 0f;
				}
				val2.cooldownScale = val.cooldownScale;
				val2.flatCooldownReduction = val.flatCooldownReduction;
			}
		}

		private static void SpawnGhoulsFromSkillStock(Action<TombstoneController> orig, TombstoneController self)
		{
			orig(self);
			if (NetworkServer.active && Object.op_Implicit((Object)(object)self.nodeGraph) && TryConsumeGhoulSpawn(self))
			{
				self.SpawnGhoulAtClosestNode();
			}
		}

		private static void DisableMorticianSpawnTimer(TombstoneController tombstone)
		{
			tombstone.spawnStopwatch = float.NegativeInfinity;
		}

		private static bool TryConsumeGhoulSpawn(TombstoneController tombstone)
		{
			return TombstoneRaiseSkills.TryConsume(TombstoneRaiseSkills.GhoulSpawnSlotOf(tombstone.characterBody));
		}
	}
	internal static class GhoulRotPatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static StatHookEventHandler <0>__GrowDegenWithAge;
		}

		private static PresetSetting<float> _degenGrowthPercent;

		public static bool IsRotting => _degenGrowthPercent.Value > 0f;

		public static void Install(PresetSetting<float> degenGrowthPercent)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			_degenGrowthPercent = degenGrowthPercent;
			GameObject ghoulBodyPrefab = MorrisPlugin.GhoulBodyPrefab;
			if (!Object.op_Implicit((Object)(object)ghoulBodyPrefab))
			{
				EvenMoreBalancedMorticianPlugin.Log.LogError((object)"Ghoul body prefab not found; the Ghoul Degen Growth setting will not work.");
				return;
			}
			ghoulBodyPrefab.AddComponent<GhoulRotRefresher>();
			object obj = <>O.<0>__GrowDegenWithAge;
			if (obj == null)
			{
				StatHookEventHandler val = GrowDegenWithAge;
				<>O.<0>__GrowDegenWithAge = val;
				obj = (object)val;
			}
			RecalculateStatsAPI.GetStatCoefficients += (StatHookEventHandler)obj;
		}

		private static void GrowDegenWithAge(CharacterBody body, StatHookEventArgs stats)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (body.bodyIndex == MorrisPlugin.GhoulBodyIndex && body.hasStarted)
			{
				float num = _degenGrowthPercent.Value / 100f;
				FixedTimeStamp localStartTime = body.localStartTime;
				float num2 = num * ((FixedTimeStamp)(ref localStartTime)).timeSince;
				stats.baseRegenAdd += body.baseRegen * num2;
				stats.levelRegenAdd += body.levelRegen * num2;
			}
		}
	}
	internal sealed class GhoulRotRefresher : MonoBehaviour
	{
		private static readonly float RefreshInterval = 0.5f;

		private CharacterBody _body;

		private float _untilRefresh;

		private void Awake()
		{
			_body = ((Component)this).GetComponent<CharacterBody>();
		}

		private void FixedUpdate()
		{
			if (NetworkServer.active && GhoulRotPatch.IsRotting)
			{
				_untilRefresh -= Time.fixedDeltaTime;
				if (!(_untilRefresh > 0f))
				{
					_untilRefresh = RefreshInterval;
					_body.MarkAllStatsDirty();
				}
			}
		}
	}
	internal static class MorticianMethods
	{
		public static MethodInfo MinionStart { get; } = typeof(MorrisMinionController).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic);

		public static MethodInfo MinionDeathStart { get; } = typeof(MorrisMinionController).GetMethod("OnDeathStart");

		public static MethodInfo TombstoneStart { get; } = typeof(TombstoneController).GetMethod("Start");

		public static MethodInfo TombstoneFixedUpdate { get; } = typeof(TombstoneController).GetMethod("FixedUpdate");
	}
	internal static class ProcCoefficientPatch
	{
		private static readonly ScopedValue<ClingState> _bitingGhoul = new ScopedValue<ClingState>();

		private static readonly ScopedValue<GhoulDeath> _detonatingGhoul = new ScopedValue<GhoulDeath>();

		private static readonly List<Hook> _hooks = new List<Hook>();

		private static MorticianSettings _settings;

		public static void Install(MorticianSettings settings)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			_settings = settings;
			_hooks.Add(new Hook((MethodBase)typeof(GhoulMelee).GetMethod("OnEnter"), (Delegate)new Action<Action<GhoulMelee>, GhoulMelee>(SetBiteProcCoefficient)));
			_hooks.Add(new Hook((MethodBase)typeof(BaseLaunchedState).GetMethod("OnEnter"), (Delegate)new Action<Action<BaseLaunchedState>, BaseLaunchedState>(SetLaunchProcCoefficient)));
			_hooks.Add(new Hook((MethodBase)typeof(TombstoneSoulOrb).GetMethod("Begin"), (Delegate)new Action<Action<TombstoneSoulOrb>, TombstoneSoulOrb>(SetSoulOrbProcCoefficient)));
			_bitingGhoul.SetDuring(typeof(ClingState).GetMethod("Bite"));
			_hooks.Add(new Hook((MethodBase)typeof(HealthComponent).GetMethod("TakeDamage"), (Delegate)new Action<Action<HealthComponent, DamageInfo>, HealthComponent, DamageInfo>(SetClingBiteProcCoefficient)));
			_detonatingGhoul.SetDuring(typeof(GhoulDeath).GetMethod("Explode"));
			_hooks.Add(new Hook((MethodBase)typeof(BlastAttack).GetMethod("Fire"), (Delegate)new Func<Func<BlastAttack, Result>, BlastAttack, Result>(SetDetonationProcCoefficient)));
		}

		private static void SetBiteProcCoefficient(Action<GhoulMelee> orig, GhoulMelee self)
		{
			orig(self);
			self.attack.procCoefficient = _settings.GhoulBiteProcCoefficient.Value;
		}

		private static void SetLaunchProcCoefficient(Action<BaseLaunchedState> orig, BaseLaunchedState self)
		{
			orig(self);
			self.attack.procCoefficient = _settings.LaunchProcCoefficient.Value;
		}

		private static void SetSoulOrbProcCoefficient(Action<TombstoneSoulOrb> orig, TombstoneSoulOrb self)
		{
			((GenericDamageOrb)self).procCoefficient = _settings.SoulOrbProcCoefficient.Value;
			orig(self);
		}

		private static void SetClingBiteProcCoefficient(Action<HealthComponent, DamageInfo> orig, HealthComponent self, DamageInfo damageInfo)
		{
			ClingState current = _bitingGhoul.Current;
			if (current != null && (Object)(object)damageInfo.inflictor == (Object)(object)((EntityState)current).gameObject)
			{
				damageInfo.procCoefficient = _settings.GhoulClingBiteProcCoefficient.Value;
			}
			orig(self, damageInfo);
		}

		private static Result SetDetonationProcCoefficient(Func<BlastAttack, Result> orig, BlastAttack self)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			GhoulDeath current = _detonatingGhoul.Current;
			if (current != null && self == current.attack)
			{
				self.procCoefficient = _settings.SacrificeProcCoefficient.Value;
			}
			return orig(self);
		}
	}
	internal static class RaiseDeadMinimumCooldownPatch
	{
		private static PresetSetting<float> _minimumCooldown;

		public static void Install(PresetSetting<float> minimumCooldown)
		{
			_minimumCooldown = minimumCooldown;
			CharacterBody.onBodyStartGlobal += WatchMorticianStats;
		}

		private static void WatchMorticianStats(CharacterBody body)
		{
			//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)
			if (body.bodyIndex == MorrisPlugin.MorrisBodyIndex)
			{
				body.onRecalculateStats += ApplyMinimumCooldown;
				body.MarkAllStatsDirty();
			}
		}

		private static void ApplyMinimumCooldown(CharacterBody mortician)
		{
			GenericSkill secondary = mortician.skillLocator.secondary;
			if (Object.op_Implicit((Object)(object)secondary) && !(secondary.baseRechargeInterval <= 0f) && !(secondary.baseRechargeInterval * secondary.cooldownScale - secondary.flatCooldownReduction >= _minimumCooldown.Value))
			{
				secondary.flatCooldownReduction = 0f;
				secondary.cooldownScale = _minimumCooldown.Value / secondary.baseRechargeInterval;
			}
		}
	}
	internal sealed class ScopedValue<T> where T : class
	{
		private Hook _hook;

		public T Current { get; private set; }

		public void SetDuring(MethodInfo instanceMethod)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			_hook = new Hook((MethodBase)instanceMethod, (Delegate)new Action<Action<T>, T>(HoldDuringCall));
		}

		private void HoldDuringCall(Action<T> orig, T self)
		{
			T current = Current;
			Current = self;
			try
			{
				orig(self);
			}
			finally
			{
				Current = current;
			}
		}
	}
	internal static class ShovelDamageSourcePatch
	{
		private static Hook _swingHook;

		private static PresetSetting<bool> _shovelCountsAsPrimarySkill;

		public static void Install(PresetSetting<bool> countsAsPrimarySkill)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			_shovelCountsAsPrimarySkill = countsAsPrimarySkill;
			_swingHook = new Hook((MethodBase)typeof(SwingShovel).GetMethod("OnEnter"), (Delegate)new Action<Action<SwingShovel>, SwingShovel>(TagSwingAsPrimaryIfEnabled));
		}

		private static void TagSwingAsPrimaryIfEnabled(Action<SwingShovel> orig, SwingShovel self)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			orig(self);
			if (_shovelCountsAsPrimarySkill.Value)
			{
				self.attack.damageType.damageSource = (DamageSource)1;
			}
		}
	}
	internal static class TombstoneDurationPatch
	{
		private static Hook _tombstoneStartHook;

		private static PresetSetting<float> _tombstoneDuration;

		public static void Install(PresetSetting<float> duration)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			_tombstoneDuration = duration;
			_tombstoneStartHook = new Hook((MethodBase)MorticianMethods.TombstoneStart, (Delegate)new Action<Action<TombstoneController>, TombstoneController>(StartExpiryTimer));
		}

		private static void StartExpiryTimer(Action<TombstoneController> orig, TombstoneController self)
		{
			orig(self);
			if (NetworkServer.active && !(_tombstoneDuration.Value <= 0f))
			{
				CharacterMaster master = ((Component)self).GetComponent<CharacterBody>().master;
				if (Object.op_Implicit((Object)(object)master))
				{
					((Component)master).gameObject.AddComponent<MasterSuicideOnTimer>().lifeTimer = _tombstoneDuration.Value;
				}
			}
		}
	}
	internal static class TombstoneLimitPatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static GetDeployableSameSlotLimit <0>__GetTombstoneLimit;
		}

		private static readonly int BaseTombstoneLimit = 1;

		private static PresetSetting<bool> _lysateCellAddsTombstone;

		public static void Install(PresetSetting<bool> lysateCellAddsTombstone)
		{
			//IL_0021: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			_lysateCellAddsTombstone = lysateCellAddsTombstone;
			object obj = <>O.<0>__GetTombstoneLimit;
			if (obj == null)
			{
				GetDeployableSameSlotLimit val = GetTombstoneLimit;
				<>O.<0>__GetTombstoneLimit = val;
				obj = (object)val;
			}
			Morris.tombstoneSlot = DeployableAPI.RegisterDeployableSlot((GetDeployableSameSlotLimit)obj);
		}

		private static int GetTombstoneLimit(CharacterMaster master, int deployableCountMultiplier)
		{
			if (!_lysateCellAddsTombstone.Value || !HasLysateCell(master))
			{
				return BaseTombstoneLimit;
			}
			return BaseTombstoneLimit + 1;
		}

		private static bool HasLysateCell(CharacterMaster master)
		{
			if (Object.op_Implicit((Object)(object)master.inventory))
			{
				return