Decompiled source of SkillPenaltyFix v1.0.1

SkillPenaltyFix.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("SkillPenaltyFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("SkillPenaltyFix")]
[assembly: AssemblyTitle("SkillPenaltyFix")]
[assembly: AssemblyVersion("1.0.1.0")]
[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 SkillPenaltyFix
{
	internal static class BonusEffects
	{
		internal sealed class LerpTarget
		{
			internal readonly string TypeName;

			internal readonly string MethodName;

			internal readonly int ExpectedCount;

			internal readonly int[] Indices;

			internal LerpTarget(string type, string name, int count, params int[] indices)
			{
				TypeName = type;
				MethodName = name;
				ExpectedCount = count;
				Indices = indices;
			}

			internal MethodInfo Resolve()
			{
				return AccessTools.Method(AccessTools.TypeByName(TypeName), MethodName, (Type[])null, (Type[])null) ?? throw new MissingMethodException(TypeName, MethodName);
			}
		}

		internal static void Install(Harmony harmony)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Skills), "GetSkillFactor", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(BonusEffects), "FactorTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			HarmonyMethod val = new HarmonyMethod(typeof(BonusEffects), "DamageTranspiler", (Type[])null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Skills), "GetRandomSkillRange", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Skills), "GetRandomSkillFactor", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
			HarmonyMethod val2 = new HarmonyMethod(typeof(BonusEffects), "LerpTranspiler", (Type[])null);
			foreach (LerpTarget item in LerpTargets())
			{
				harmony.Patch((MethodBase)item.Resolve(), (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		internal static IEnumerable<LerpTarget> LerpTargets()
		{
			yield return new LerpTarget("Humanoid", "GetAttackDrawPercentage", 1, default(int));
			yield return new LerpTarget("Player", "CheckRun", 1, default(int));
			yield return new LerpTarget("Player", "OnSwimming", 1, default(int));
			yield return new LerpTarget("Player", "GetDodgeStaminaUse", 1, default(int));
			yield return new LerpTarget("Player", "OnSneaking", 1, default(int));
			yield return new LerpTarget("Player", "UpdateStealth", 1, default(int));
			yield return new LerpTarget("ItemDrop+ItemData", "GetWeaponLoadingTime", 1, default(int));
			yield return new LerpTarget("Attack", "FireProjectileBurst", 3, 2);
			yield return new LerpTarget("Attack", "DoMeleeAttack", 1, default(int));
			yield return new LerpTarget("FishingFloat", "FixedUpdate", 3, 0, 1, 2);
			yield return new LerpTarget("Piece", "Awake", 1, default(int));
			yield return new LerpTarget("Piece", "OnPlaced", 1, default(int));
		}

		internal static float ClampFactor(float factor)
		{
			return Mathf.Clamp(factor, 0f, Plugin.Instance.Rules.EffectiveCap / 100f);
		}

		internal static float SkillLerp(float a, float b, float t)
		{
			if (!Plugin.Instance.Rules.BonusOverflowEnabled || t <= 1f)
			{
				return Mathf.Lerp(a, b, t);
			}
			return Mathf.Max(0f, Mathf.LerpUnclamped(a, b, t));
		}

		internal static IEnumerable<CodeInstruction> FactorTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo clamp = AccessTools.Method(typeof(Mathf), "Clamp01", (Type[])null, (Type[])null);
			if (list.Count((CodeInstruction c) => CodeInstructionExtensions.Calls(c, clamp)) != 1)
			{
				throw new InvalidOperationException("Skills.GetSkillFactor no longer contains exactly one Clamp01.");
			}
			foreach (CodeInstruction item in list.Where((CodeInstruction c) => CodeInstructionExtensions.Calls(c, clamp)))
			{
				item.opcode = OpCodes.Call;
				item.operand = AccessTools.Method(typeof(BonusEffects), "ClampFactor", (Type[])null, (Type[])null);
			}
			return list;
		}

		internal static IEnumerable<CodeInstruction> LerpTranspiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
		{
			LerpTarget target = LerpTargets().Single((LerpTarget t) => t.TypeName == __originalMethod.DeclaringType?.FullName && t.MethodName == __originalMethod.Name);
			return RewriteLerps(instructions, target);
		}

		internal static IEnumerable<CodeInstruction> RewriteLerps(IEnumerable<CodeInstruction> instructions, LerpTarget target)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo lerp = AccessTools.Method(typeof(Mathf), "Lerp", (Type[])null, (Type[])null);
			if (list.Count((CodeInstruction c) => CodeInstructionExtensions.Calls(c, lerp)) != target.ExpectedCount)
			{
				throw new InvalidOperationException("Unexpected skill interpolation layout in " + target.TypeName + "." + target.MethodName + ".");
			}
			int num = 0;
			foreach (CodeInstruction item in list.Where((CodeInstruction c) => CodeInstructionExtensions.Calls(c, lerp)))
			{
				if (target.Indices.Contains(num))
				{
					item.opcode = OpCodes.Call;
					item.operand = AccessTools.Method(typeof(BonusEffects), "SkillLerp", (Type[])null, (Type[])null);
				}
				num++;
			}
			return list;
		}

		internal static float ClampDamage(float value, float factor)
		{
			float num = (Plugin.Instance.Rules.BonusOverflowEnabled ? (0.6f * Mathf.Max(0f, Mathf.Min(factor, Plugin.Instance.Rules.EffectiveCap / 100f) - 1f)) : 0f);
			return Mathf.Clamp01(value) + num;
		}

		internal static IEnumerable<CodeInstruction> DamageTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo factor = AccessTools.Method(typeof(Skills), "GetSkillFactor", (Type[])null, (Type[])null);
			MethodInfo clamp = AccessTools.Method(typeof(Mathf), "Clamp01", (Type[])null, (Type[])null);
			int num = list.FindIndex((CodeInstruction c) => CodeInstructionExtensions.Calls(c, factor));
			if (num < 0 || num + 1 >= list.Count || list[num + 1].opcode != OpCodes.Stloc_0 || list.Count((CodeInstruction c) => CodeInstructionExtensions.Calls(c, factor)) != 1 || list.Count((CodeInstruction c) => CodeInstructionExtensions.Calls(c, clamp)) != 2)
			{
				throw new InvalidOperationException("Unexpected random skill damage layout.");
			}
			List<CodeInstruction> list2 = new List<CodeInstruction>();
			foreach (CodeInstruction item2 in list)
			{
				if (CodeInstructionExtensions.Calls(item2, clamp))
				{
					CodeInstruction item = new CodeInstruction(item2)
					{
						opcode = OpCodes.Ldloc_0,
						operand = null
					};
					list2.Add(item);
					list2.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BonusEffects), "ClampDamage", (Type[])null, (Type[])null)));
				}
				else
				{
					list2.Add(item2);
				}
			}
			return list2;
		}
	}
	internal static class DeathHooks
	{
		private static readonly Func<float, float> Requirement = (float whole) => Mathf.Pow(whole + 1f, 1.5f) * 0.5f + 0.5f;

		internal static void Install(Harmony harmony)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "OnDeath", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(DeathHooks), "RewritePlayerDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(DeathHooks), "RewriteSkillDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "SetLocalPlayer", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(DeathHooks), "DiscoverSkills", (Type[])null)
			{
				priority = 0
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static bool IsLocal(Skills skills)
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return (Object)(object)((Character)Player.m_localPlayer).GetSkills() == (Object)(object)skills;
			}
			return false;
		}

		private static void DiscoverSkills(Player __instance)
		{
			Plugin.Instance.Discover(((Character)__instance).GetSkills());
		}

		private static IEnumerable<CodeInstruction> RewritePlayerDeath(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> codes = instructions.ToList();
			MethodInfo globalKey = AccessTools.DeclaredMethod(typeof(ZoneSystem), "GetGlobalKey", new Type[1] { typeof(GlobalKeys) }, (Type[])null);
			CodeInstruction item = codes.Select((CodeInstruction code, int index) => (code: code, index: index)).Single(((CodeInstruction code, int index) entry) => entry.index > 0 && CodeInstructionExtensions.Calls(entry.code, globalKey) && CodeInstructionExtensions.LoadsConstant(codes[entry.index - 1], 22L)).code;
			MethodInfo onDeath = AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null);
			ReplaceCall(item, "IsSkillResetEnabled");
			ReplaceCall(codes.Single((CodeInstruction code) => CodeInstructionExtensions.Calls(code, onDeath)), "ApplyOnDeath");
			return codes;
		}

		private static bool IsSkillResetEnabled(ZoneSystem zone, GlobalKeys key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if ((int)key != 22)
			{
				return zone.GetGlobalKey(key);
			}
			return false;
		}

		private static void ApplyOnDeath(Skills skills)
		{
			if (IsLocal(skills))
			{
				Plugin.Instance.Discover(skills);
				Plugin.Instance.SkillManager.Refresh();
			}
			skills.OnDeath();
		}

		private static IEnumerable<CodeInstruction> RewriteSkillDeath(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo lower = AccessTools.DeclaredMethod(typeof(Skills), "LowerAllSkills", (Type[])null, (Type[])null);
			ReplaceCall(list.Single((CodeInstruction code) => CodeInstructionExtensions.Calls(code, lower)), "ApplyConfiguredLoss");
			return list;
		}

		private static void ReplaceCall(CodeInstruction instruction, string method)
		{
			instruction.opcode = OpCodes.Call;
			instruction.operand = AccessTools.DeclaredMethod(typeof(DeathHooks), method, (Type[])null, (Type[])null);
		}

		private static void ApplyConfiguredLoss(Skills skills, float vanillaFactor)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!IsLocal(skills))
			{
				skills.LowerAllSkills(vanillaFactor);
				return;
			}
			DeathRules rules = Plugin.Instance.Rules;
			bool flag = false;
			foreach (Skill skill in skills.GetSkillList())
			{
				if (skill.m_info == null || rules.Protects(skill.m_level))
				{
					continue;
				}
				float num = rules.LossFor(skill.m_info.m_skill);
				if (num != 0f)
				{
					double num2 = Progression.Read(skill.m_level, skill.m_accumulator, Requirement);
					if (num2 > 0.0 && !double.IsInfinity(num2))
					{
						(float, float) tuple = Progression.Encode(Progression.AfterPenalty(num2, num), Requirement);
						flag |= tuple.Item1 != skill.m_level || tuple.Item2 != skill.m_accumulator;
						(skill.m_level, skill.m_accumulator) = tuple;
					}
				}
			}
			if (flag)
			{
				((Character)Player.m_localPlayer).Message((MessageType)1, "$msg_skills_lowered", 0, (Sprite)null, false);
			}
		}
	}
	internal sealed class DeathRules
	{
		private enum Category
		{
			Combat,
			Movement,
			Gathering,
			Crafting,
			Modded
		}

		private const float DefaultPenalty = 5f;

		private const string UseGlobal = "Use global";

		private const string UseCategory = "Use category";

		private const string PenaltyHelp = "Percentage lost on death. 0 disables loss. 100 removes all progression.";

		private static readonly Dictionary<SkillType, Category> Vanilla = new Dictionary<SkillType, Category>
		{
			[(SkillType)1] = Category.Combat,
			[(SkillType)2] = Category.Combat,
			[(SkillType)3] = Category.Combat,
			[(SkillType)4] = Category.Combat,
			[(SkillType)5] = Category.Combat,
			[(SkillType)7] = Category.Combat,
			[(SkillType)8] = Category.Combat,
			[(SkillType)14] = Category.Combat,
			[(SkillType)6] = Category.Combat,
			[(SkillType)11] = Category.Combat,
			[(SkillType)9] = Category.Combat,
			[(SkillType)10] = Category.Combat,
			[(SkillType)102] = Category.Movement,
			[(SkillType)100] = Category.Movement,
			[(SkillType)101] = Category.Movement,
			[(SkillType)103] = Category.Movement,
			[(SkillType)108] = Category.Movement,
			[(SkillType)110] = Category.Movement,
			[(SkillType)13] = Category.Gathering,
			[(SkillType)12] = Category.Gathering,
			[(SkillType)104] = Category.Gathering,
			[(SkillType)105] = Category.Crafting,
			[(SkillType)107] = Category.Crafting,
			[(SkillType)106] = Category.Crafting
		};

		private readonly ConfigFile config;

		private readonly ConfigEntry<bool> protect100;

		private readonly ConfigEntry<bool> allowBonusOverflow;

		private readonly ConfigEntry<int> maxEffectiveLevel;

		private readonly ConfigEntry<float> globalLoss;

		private readonly Dictionary<Category, ConfigEntry<string>> categoryLosses = new Dictionary<Category, ConfigEntry<string>>();

		private readonly Dictionary<SkillType, (Category Category, ConfigEntry<string> Loss)> skills = new Dictionary<SkillType, (Category, ConfigEntry<string>)>();

		internal bool BonusOverflowEnabled => allowBonusOverflow.Value;

		internal float EffectiveCap => BonusOverflowEnabled ? maxEffectiveLevel.Value : 100;

		internal DeathRules(ConfigFile config)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Expected O, but got Unknown
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Expected I4, but got Unknown
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			this.config = config;
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				float num = TakeLegacy("Death Penalty", "DefaultLossPercent", -1f);
				globalLoss = config.Bind<float>("Death Penalty", "All skills", 5f, new ConfigDescription("Percentage lost on death. 0 disables loss. 100 removes all progression.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
				if (num >= 0f && num <= 100f)
				{
					globalLoss.Value = num;
				}
				foreach (Category value in Enum.GetValues(typeof(Category)))
				{
					ConfigEntry<string> val = config.Bind<string>("Category penalties", value.ToString(), "Use global", "Percentage lost on death. 0 disables loss. 100 removes all progression. Enter a number from 0 to 100, or 'Use global' to use All skills.");
					float num2 = TakeLegacy("Categories", value.ToString(), -1f);
					if (num2 >= 0f && num2 <= 100f)
					{
						val.Value = num2.ToString(CultureInfo.InvariantCulture);
					}
					categoryLosses.Add(value, val);
				}
				bool num3 = TakeLegacy("Advanced", "ProtectLevel100Skills", fallback: false);
				bool flag = TakeLegacy("Advanced", "AllowBonusEffectsAbove100", fallback: false);
				int num4 = TakeLegacy("Advanced", "MaxEffectiveSkillLevel", 120);
				protect100 = config.Bind<bool>("Advanced", "Protect level 100 skills", false, "Exempts skills whose trained level is at least 100. Temporary bonuses do not count.");
				allowBonusOverflow = config.Bind<bool>("Advanced", "Allow bonus effects above 100", false, "Allows gear and status bonuses above 100 to improve supported skill effects. Training stops at 100.");
				maxEffectiveLevel = config.Bind<int>("Advanced", "Max effective skill level", 120, new ConfigDescription("Maximum skill used by supported effects when bonus effects above 100 are allowed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(100, 120), Array.Empty<object>()));
				if (num3)
				{
					protect100.Value = true;
				}
				if (flag)
				{
					allowBonusOverflow.Value = true;
				}
				if (num4 != 120)
				{
					maxEffectiveLevel.Value = num4;
				}
				foreach (KeyValuePair<SkillType, Category> item in Vanilla)
				{
					SkillType key2 = item.Key;
					string text = (key2 - 9) switch
					{
						1 => "Blood Magic", 
						0 => "Elemental Magic", 
						4 => "Wood Cutting", 
						_ => ((object)item.Key/*cast due to .constrained prefix*/).ToString(), 
					};
					string text2 = ((object)item.Key/*cast due to .constrained prefix*/).ToString();
					float previousValue = ((text2 == text) ? 5f : TakeLegacy("Skills", text2, 5f));
					skills.Add(item.Key, (item.Value, BindSkill("Skill penalties", "Skills", text, $"Category: {item.Value}.", previousValue)));
				}
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			if (saveOnConfigSet)
			{
				config.Save();
			}
		}

		internal bool Protects(float trainedLevel)
		{
			if (protect100.Value)
			{
				return trainedLevel >= 100f;
			}
			return false;
		}

		internal void Discover(SkillDef definition, Func<string, string> localize = null)
		{
			//IL_0004: 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_0016: Invalid comparison between Unknown and I4
			//IL_001f: 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_0034: Expected I4, but got Unknown
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			if (definition != null && (int)definition.m_skill != 0 && (int)definition.m_skill != 999 && !skills.ContainsKey(definition.m_skill))
			{
				string text = ((int)definition.m_skill).ToString(CultureInfo.InvariantCulture);
				string text2 = definition.m_description ?? "";
				string text3 = (text2.StartsWith("$skilldesc_", StringComparison.OrdinalIgnoreCase) ? text2.Substring("$skilldesc_".Length) : "");
				Category category;
				switch (text3.ToLowerInvariant())
				{
				case "throwing":
				case "scythes":
					category = Category.Combat;
					break;
				case "foraging":
					category = Category.Gathering;
					break;
				case "jewelcrafting":
					category = Category.Crafting;
					break;
				default:
					category = Category.Modded;
					break;
				}
				Category category2 = category;
				string text4 = localize?.Invoke("$skill_" + text);
				if (!string.IsNullOrWhiteSpace(text4) && !text4.StartsWith("$") && !text4.StartsWith("["))
				{
					text3 = text4;
				}
				if (string.IsNullOrWhiteSpace(text3))
				{
					text3 = (Enum.IsDefined(typeof(SkillType), definition.m_skill) ? ((object)Unsafe.As<SkillType, SkillType>(ref definition.m_skill)/*cast due to .constrained prefix*/).ToString() : "Custom skill");
				}
				text3 = text3.Replace('\r', ' ').Replace('\n', ' ');
				bool saveOnConfigSet = config.SaveOnConfigSet;
				config.SaveOnConfigSet = false;
				try
				{
					skills.Add(definition.m_skill, (category2, BindSkill("Modded skill penalties", "Modded Skills", text, $"{text3} (category: {category2}).")));
				}
				finally
				{
					config.SaveOnConfigSet = saveOnConfigSet;
				}
				if (saveOnConfigSet)
				{
					config.Save();
				}
			}
		}

		internal float LossFor(SkillType skill)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			Category key = Category.Modded;
			if (skills.TryGetValue(skill, out (Category, ConfigEntry<string>) value))
			{
				if (TryReadPercent(value.Item2.Value, out var percentage))
				{
					return percentage;
				}
				(key, _) = value;
			}
			if (TryReadPercent(categoryLosses[key].Value, out var percentage2))
			{
				return percentage2;
			}
			float value2 = globalLoss.Value;
			if (!(value2 >= 0f) || !(value2 <= 100f))
			{
				return 5f;
			}
			return value2;
		}

		private static bool TryReadPercent(string value, out float percentage)
		{
			if (float.TryParse(value?.Trim().TrimEnd(new char[1] { '%' }), NumberStyles.Float, CultureInfo.InvariantCulture, out percentage) && percentage >= 0f)
			{
				return percentage <= 100f;
			}
			return false;
		}

		private T TakeLegacy<T>(string section, string key, T fallback)
		{
			ConfigEntry<T> val = config.Bind<T>(section, key, fallback, (ConfigDescription)null);
			config.Remove(((ConfigEntryBase)val).Definition);
			return val.Value;
		}

		private ConfigEntry<string> BindSkill(string section, string previousSection, string key, string description, float previousValue = 5f)
		{
			float num = TakeLegacy(previousSection, key, previousValue);
			ConfigEntry<string> val = config.Bind<string>(section, key, "Use category", description + " Percentage lost on death. 0 disables loss. 100 removes all progression. Enter a number from 0 to 100, or 'Use category' to use the category setting.");
			if (num >= 0f && num <= 100f && num != 5f)
			{
				val.Value = num.ToString(CultureInfo.InvariantCulture);
			}
			return val;
		}
	}
	[BepInPlugin("local.valheim.skillpenaltyfix", "SkillPenaltyFix", "1.0.1")]
	[BepInIncompatibility("txc.skillloss")]
	[BepInIncompatibility("CustomSkillLoss")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string Id = "local.valheim.skillpenaltyfix";

		private Harmony harmony;

		internal static Plugin Instance { get; private set; }

		internal DeathRules Rules { get; private set; }

		internal SkillManagerCompatibility SkillManager { get; private set; }

		private void Awake()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			Instance = this;
			Rules = new DeathRules(((BaseUnityPlugin)this).Config);
			harmony = new Harmony("local.valheim.skillpenaltyfix");
			SkillManager = new SkillManagerCompatibility(harmony, ((BaseUnityPlugin)this).Logger);
			try
			{
				DeathHooks.Install(harmony);
			}
			catch (Exception ex)
			{
				harmony.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not install the death hooks. Valheim's skill penalty is still active. " + ex));
				return;
			}
			Harmony val = new Harmony("local.valheim.skillpenaltyfix.bonuses");
			try
			{
				if (Chainloader.PluginInfos.ContainsKey("local.valheim.bonusskilloverflow"))
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Bonus Skill Overflow handles effective skill bonuses in this profile.");
				}
				else if (Rules.BonusOverflowEnabled)
				{
					BonusEffects.Install(val);
				}
			}
			catch (Exception ex2)
			{
				val.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not extend bonus effects in this game version. Skill loss is still active. " + ex2));
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"SkillPenaltyFix ready. Skill losses are configured locally.");
		}

		private void OnDestroy()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("local.valheim.skillpenaltyfix.bonuses").UnpatchSelf();
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		internal void Discover(Skills skills)
		{
			try
			{
				Localization instance = Localization.instance;
				Func<string, string> localize = ((instance == null) ? null : new Func<string, string>(instance.Localize));
				foreach (SkillDef skill in skills.m_skills)
				{
					Rules.Discover(skill, localize);
				}
				foreach (Skill skill2 in skills.GetSkillList())
				{
					Rules.Discover(skill2.m_info, localize);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not save all discovered skill entries. Unlisted skills use the Modded category setting. " + ex));
			}
		}
	}
	internal static class Progression
	{
		internal static double Read(float level, float xp, Func<float, float> requirement)
		{
			if (level >= 100f)
			{
				return level;
			}
			float arg = (float)Math.Floor(level);
			double num = Math.Max(0.0, Math.Min(1.0, (double)xp / (double)requirement(arg)));
			return Math.Min(100.0, (double)level + num);
		}

		internal static double AfterPenalty(double progression, float percentage)
		{
			return progression * (1.0 - (double)percentage / 100.0);
		}

		internal static (float Level, float Xp) Encode(double progression, Func<float, float> requirement)
		{
			float num = (float)Math.Floor(progression);
			float num2 = requirement(num);
			float num3 = (float)((progression - (double)num) * (double)num2);
			if (num3 >= num2)
			{
				num3 = num2 * 0.9999999f;
			}
			return (Level: num, Xp: num3);
		}
	}
	internal sealed class SkillManagerCompatibility
	{
		private readonly Harmony harmony;

		private readonly ManualLogSource logger;

		private readonly HashSet<MethodInfo> handled = new HashSet<MethodInfo>();

		internal SkillManagerCompatibility(Harmony harmony, ManualLogSource logger)
		{
			this.harmony = harmony;
			this.logger = logger;
		}

		internal void Refresh()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			foreach (Patch prefix in Harmony.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null)).Prefixes)
			{
				MethodInfo patchMethod = prefix.PatchMethod;
				if (!(patchMethod.DeclaringType?.FullName != "SkillManager.Skill") && !(patchMethod.Name != "Patch_Skills_OnDeath_Prefix") && handled.Add(patchMethod))
				{
					try
					{
						harmony.Patch((MethodBase)patchMethod, new HarmonyMethod(typeof(SkillManagerCompatibility), "KeepForeignPenalty", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					catch (Exception arg)
					{
						logger.LogWarning((object)$"Could not intercept the separate skill loss from {patchMethod.DeclaringType.Assembly.GetName().Name}. {arg}");
					}
				}
			}
		}

		private static bool KeepForeignPenalty(Skills __0)
		{
			return !DeathHooks.IsLocal(__0);
		}
	}
}