Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Kratyr Legendary Skills v0.6.0
BepInEx/plugins/KratyrLegendarySkills.dll
Decompiled 6 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; 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 HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("KratyrLegendarySkills")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("KratyrLegendarySkills")] [assembly: AssemblyTitle("KratyrLegendarySkills")] [assembly: AssemblyVersion("1.0.0.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 Kratyr.LegendarySkills { internal static class GameSkillPatches { [HarmonyPatch(typeof(Skill), "Raise", new Type[] { typeof(float) })] private static class RaisePatch { private static bool Prefix(Skill __instance, float __0, ref bool __result) { __result = __instance.m_info != null && Policy.Earn(Id(__instance), ref __instance.m_level, ref __instance.m_accumulator, __0 * __instance.m_info.m_increseStep * Game.m_skillGainRate); return false; } } [HarmonyPatch(typeof(Skill), "GetLevelPercentage")] private static class ProgressPatch { private static bool Prefix(Skill __instance, ref float __result) { __result = Policy.ProgressFraction(Id(__instance), __instance.m_level, __instance.m_accumulator); return false; } } [HarmonyPatch(typeof(Skills), "RebalanceSkills", new Type[] { typeof(SkillType) })] private static class RebalancePatch { private static bool Prefix(Skills __instance, SkillType __0) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) if (!Policy.NoNegativeCredit) { return true; } Dictionary<SkillType, Skill> dictionary = KratyrLegendarySkills.Entries(__instance); dictionary.TryGetValue(__0, out var value); float num = Math.Max(0f, __instance.m_totalSkillCap - Math.Max(0f, value?.m_level ?? 0f)); float num2 = 0f; foreach (KeyValuePair<SkillType, Skill> item in dictionary) { if (item.Key != __0) { Skill value2 = item.Value; if (value2 != null && value2.m_level > 0f) { num2 += item.Value.m_level; } } } if (num2 <= num) { return false; } float num3 = num / num2; foreach (KeyValuePair<SkillType, Skill> item2 in dictionary) { if (item2.Key != __0) { Skill value3 = item2.Value; if (value3 != null && value3.m_level > 0f) { Skill value4 = item2.Value; value4.m_level *= num3; } } } return false; } } [HarmonyPatch(typeof(Skills), "LowerAllSkills", new Type[] { typeof(float) })] private static class DeathPatch { private static bool Prefix(Skills __instance, float __0, Player ___m_player) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected I4, but got Unknown SkillProgression policy = Policy; if (policy.VanillaLoss) { return true; } if (!(__0 > 0f) || !SkillProgression.Finite(__0)) { return false; } Dictionary<string, string> dictionary = (Object.op_Implicit((Object)(object)___m_player) ? ___m_player.m_customData : null); long num = ((dictionary != null && policy.GraceMinutes > 0) ? DateTimeOffset.UtcNow.ToUnixTimeSeconds() : 0); bool flag = false; foreach (KeyValuePair<SkillType, Skill> item in KratyrLegendarySkills.Entries(__instance)) { Skill value = item.Value; if (value == null) { continue; } int num2 = (int)item.Key; float num3 = policy.LevelWithProgress(num2, value.m_level, value.m_accumulator); string text = ((num > 0) ? ("com.kratyr.expandedskills.grace." + num2.ToString(CultureInfo.InvariantCulture)) : null); long result = 0L; if (text != null && dictionary.TryGetValue(text, out var value2)) { long.TryParse(value2, NumberStyles.None, CultureInfo.InvariantCulture, out result); } bool protectedLevel; float num4 = policy.AfterDeath(num2, num3, __0, num, result, out protectedLevel); if (protectedLevel) { dictionary[text] = num.ToString(CultureInfo.InvariantCulture); } if (num4 != num3) { Set(value, num4); flag = true; if (KratyrLegendarySkills.Diagnostics.Value) { KratyrLegendarySkills.Instance.AdminLog($"Death loss for {num2}: {num3:0.###} to {num4:0.###}, grace used {protectedLevel}."); } } } if (flag && Object.op_Implicit((Object)(object)___m_player)) { ((Character)___m_player).Message((MessageType)1, "$msg_skills_lowered", 0, (Sprite)null, false); } return false; } private static void Postfix(Skills __instance) { SkillProgression policy = Policy; if (policy.VanillaLoss && !policy.NegativeSkills) { ApplyLimits(__instance, policy); } } } [HarmonyPatch(typeof(Skills), "GetSkillLevel", new Type[] { typeof(SkillType) })] private static class NegativeLevelPatch { private static void Postfix(ref float __result) { if (!Policy.NegativeSkills && __result < 0f) { __result = 0f; } } } [HarmonyPatch(typeof(Skills), "GetTotalSkill")] private static class SkillTotalPatch { private static bool Prefix(Skills __instance, ref float __result) { if (!Policy.NoNegativeCredit) { return true; } float num = 0f; foreach (Skill value in KratyrLegendarySkills.Entries(__instance).Values) { if (value != null && value.m_level > 0f) { num += value.m_level; } } __result = num; return false; } } [HarmonyPatch(typeof(Skills), "Load", new Type[] { typeof(ZPackage) })] private static class LoadPatch { private static void Postfix(Skills __instance) { CleanStorage(__instance); } } [HarmonyPatch(typeof(Skills), "Save", new Type[] { typeof(ZPackage) })] private static class SavePatch { private static void Prefix(Skills __instance) { CleanStorage(__instance); } } [HarmonyPatch(typeof(Skills), "CheatRaiseSkill", new Type[] { typeof(string), typeof(float), typeof(bool) })] private static class CheatRaisePatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod) { return ReplaceCheatClamp(instructions, __originalMethod); } } private const string GraceKeyPrefix = "com.kratyr.expandedskills.grace."; private static SkillProgression Policy => KratyrLegendarySkills.Policy; private static int Id(Skill skill) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected I4, but got Unknown SkillDef info = skill.m_info; if (info == null) { return 0; } return (int)info.m_skill; } internal static void Set(Skill skill, float level) { skill.m_level = level; skill.m_accumulator = 0f; } internal static void ApplyLimits(Skills skills, SkillProgression policy) { foreach (Skill value in KratyrLegendarySkills.Entries(skills).Values) { if (value != null) { float num = policy.Limits(Id(value)).Clamp(value.m_level); if (num != value.m_level) { Set(value, num); } } } } private static void CleanStorage(Skills skills) { foreach (Skill value in KratyrLegendarySkills.Entries(skills).Values) { if (value != null) { if (!SkillProgression.Finite(value.m_level)) { Set(value, 0f); } else if (!SkillProgression.Finite(value.m_accumulator) || value.m_accumulator < 0f) { value.m_accumulator = 0f; } } } } internal static IEnumerable<CodeInstruction> ReplaceCheatClamp(IEnumerable<CodeInstruction> instructions, MethodBase original) { //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); LocalVariableInfo[] locals = original.GetMethodBody()?.LocalVariables.Where((LocalVariableInfo v) => v.LocalType == typeof(Skill)).ToArray(); MethodInfo clamp = typeof(Mathf).GetMethod("Clamp", new Type[3] { typeof(float), typeof(float), typeof(float) }); CodeInstruction[] array = list.Where((CodeInstruction i) => CodeInstructionExtensions.Calls(i, clamp)).ToArray(); LocalVariableInfo[] array2 = locals; CodeInstruction val = ((array2 != null && array2.Length == 1) ? ((IEnumerable<CodeInstruction>)list).FirstOrDefault((Func<CodeInstruction, bool>)((CodeInstruction i) => Loads(i, locals[0].LocalIndex))) : null); if (val == null || array.Length != 1) { KratyrLegendarySkills.Instance?.AdminWarn("Skill cap hook did not match " + original.DeclaringType?.Name + "." + original.Name + "."); return list; } CodeInstruction val2 = new CodeInstruction(val.opcode, val.operand); val2.labels.AddRange(array[0].labels); array[0].labels.Clear(); list.Insert(list.IndexOf(array[0]), val2); array[0].operand = typeof(GameSkillPatches).GetMethod("ClampCheatLevel", BindingFlags.Static | BindingFlags.NonPublic); return list; } private static bool Loads(CodeInstruction i, int slot) { if ((!(i.opcode == OpCodes.Ldloc_0) || slot != 0) && (!(i.opcode == OpCodes.Ldloc_1) || slot != 1) && (!(i.opcode == OpCodes.Ldloc_2) || slot != 2) && (!(i.opcode == OpCodes.Ldloc_3) || slot != 3)) { if ((i.opcode == OpCodes.Ldloc || i.opcode == OpCodes.Ldloc_S) && i.operand is LocalBuilder localBuilder) { return localBuilder.LocalIndex == slot; } return false; } return true; } private static float ClampCheatLevel(float raw, float minimum, float maximum, Skill skill) { if (skill == null) { return Math.Max(minimum, Math.Min(maximum, raw)); } skill.m_accumulator = 0f; return Policy.Limits(Id(skill)).Clamp(raw); } } [BepInPlugin("com.kratyr.legendaryskills", "Kratyr Legendary Skills", "0.6.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class KratyrLegendarySkills : BaseUnityPlugin { [HarmonyPatch(typeof(Terminal), "InitTerminal")] private static class Commands { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__1_0; internal void <Postfix>b__1_0(ConsoleEventArgs args) { Instance.Execute(args.Context, (args.Length > 1) ? args[1] : "status", (args.Length > 2) ? args[2] : null, (args.Length > 3) ? args[3] : null, (args.Length > 4) ? args[4] : null); } } private static bool _registered; [HarmonyPostfix] private static void Postfix() { //IL_003b: 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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (_registered) { return; } object obj = <>c.<>9__1_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { Instance.Execute(args.Context, (args.Length > 1) ? args[1] : "status", (args.Length > 2) ? args[2] : null, (args.Length > 3) ? args[3] : null, (args.Length > 4) ? args[4] : null); }; <>c.<>9__1_0 = val; obj = (object)val; } new ConsoleCommand("kskills", "Kratyr Legendary Skills: status | sort | players | inspect <player> | preview <player> [skill] | half <player> | reset <player> [skill] | set <player> <skill> <raw level> (admin). Raw 150 displays as 50★.", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); _registered = true; } } public const string GUID = "com.kratyr.legendaryskills"; public const string Name = "Kratyr Legendary Skills"; public const string Version = "0.6.0"; private const string LegendaryPurple = "#B58AFF"; internal const string BalrondSkills = "balrond.astafaraios.BalrondExtraSkills"; private const string BalrondNegative = "balrond.astafaraios.BalrondNegativeSkills"; private const string PreviousKratyr = "kratyr.valheim.unifiedskills.playtest"; private const string PreviousExpanded = "com.kratyr.expandedskills"; private const string Uncapped = "com.koalaking.uncappedskills"; internal static KratyrLegendarySkills Instance; internal static ConfigEntry<bool> Diagnostics; internal static ConfigEntry<bool> AllowHostTestSet; internal static ConfigEntry<bool> LockConfig; internal static ConfigEntry<SkillSortMode> SkillSortOrder; internal static ConfigEntry<bool> ShowSkillSortButton; internal static ConfigEntry<float> SkillSortButtonX; internal static ConfigEntry<float> SkillSortButtonY; internal static ConfigEntry<string> SkillSortCategoryOverrides; internal static ConfigEntry<string> NegativeColor; internal static ConfigEntry<string> ExtendedColor; internal static ConfigEntry<string> TwoStarColor; internal static ConfigEntry<string> ThreeStarColor; private static readonly FieldRef<Skills, Dictionary<SkillType, Skill>> SkillData = AccessTools.FieldRefAccess<Skills, Dictionary<SkillType, Skill>>("m_skillData"); private Harmony _harmony; private bool _active; private SkillSettings settings; private Player appliedPlayer; private SkillProgression appliedPolicy; internal static SkillProgression LocalPolicy { get; private set; } internal static int Revision { get; private set; } internal static SkillProgression Policy => SkillConfigSync.Remote ?? LocalPolicy; internal bool ActiveForAdmin => _active; private void Awake() { //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Expected O, but got Unknown Instance = this; if (Chainloader.PluginInfos.ContainsKey("balrond.astafaraios.BalrondNegativeSkills") || Chainloader.PluginInfos.ContainsKey("kratyr.valheim.unifiedskills.playtest") || Chainloader.PluginInfos.ContainsKey("com.kratyr.expandedskills") || Chainloader.PluginInfos.ContainsKey("com.koalaking.uncappedskills") || AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetName().Name == "UncappedSkills")) { ((BaseUnityPlugin)this).Logger.LogError((object)"Legendary Skills requires a single skill progression provider. Disable Expanded Skills, Unified Skills, Balrond Negative Skills and other cap overrides before launching."); return; } try { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; settings = new SkillSettings(((BaseUnityPlugin)this).Config, AdminWarn, SkillSettings.Import(((BaseUnityPlugin)this).Config, AdminWarn)); Diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("5 - Diagnostics", "Detailed Logging", false, "Log level changes locally."); AllowHostTestSet = ((BaseUnityPlugin)this).Config.Bind<bool>("5 - Diagnostics", "Allow Host Test Set Command", false, "Enable guarded kskills set in a locally hosted world."); LockConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("6 - Multiplayer", "Lock Host Configuration", true, "Send the host's caps, progression and loss settings to clients that run Legendary Skills."); SkillSortOrder = ((BaseUnityPlugin)this).Config.Bind<SkillSortMode>("7 - Skills Window", "Sort Order", SkillSortMode.Default, "Default keeps game order. Name sorts alphabetically. Type groups related skills."); ShowSkillSortButton = ((BaseUnityPlugin)this).Config.Bind<bool>("7 - Skills Window", "Show Sort Button", true, "Show the Sort control on the Skills panel."); SkillSortButtonX = SkillSettings.Number(((BaseUnityPlugin)this).Config, "7 - Skills Window", "Sort Button Offset X", -110f, -800f, 200f, "Horizontal offset from the upper right."); SkillSortButtonY = SkillSettings.Number(((BaseUnityPlugin)this).Config, "7 - Skills Window", "Sort Button Offset Y", -53f, -400f, 50f, "Vertical offset from the upper right."); SkillSortCategoryOverrides = ((BaseUnityPlugin)this).Config.Bind<string>("7 - Skills Window", "Skill Category Overrides", "", "Optional category mappings such as 16050:Magic;Throwing:Combat. See the README for valid categories."); NegativeColor = ((BaseUnityPlugin)this).Config.Bind<string>("7 - Skills Window", "Negative Skill Color", "#E8827A", "Hex color for negative skill levels and progress bars. Leave empty for the game color."); ExtendedColor = ((BaseUnityPlugin)this).Config.Bind<string>("7 - Skills Window", "Extended Skill Color", "#B58AFF", "Hex color for one-star skill levels and bars. Leave empty for the game color."); TwoStarColor = ((BaseUnityPlugin)this).Config.Bind<string>("7 - Skills Window", "Two Star Skill Color", "#8BDF8D", "Hex color for two-star skill levels and bars. Leave empty for the game color."); ThreeStarColor = ((BaseUnityPlugin)this).Config.Bind<string>("7 - Skills Window", "Three Star Skill Color", "#FF707C", "Hex color for skill levels and bars with three or more stars. Leave empty for the game color."); ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("7 - Skills Window", "Legendary Purple Default Applied", false, "Internal marker for the Legendary color default update."); if (!val.Value) { if (string.Equals(ExtendedColor.Value.Trim(), "#8BDF8D", StringComparison.OrdinalIgnoreCase)) { ExtendedColor.Value = "#B58AFF"; } val.Value = true; } ((BaseUnityPlugin)this).Config.SaveOnConfigSet = true; ((BaseUnityPlugin)this).Config.Save(); ((BaseUnityPlugin)this).Config.SettingChanged += SettingsChanged; RefreshSettings(); _harmony = new Harmony("com.kratyr.legendaryskills"); _harmony.PatchAll(typeof(KratyrLegendarySkills).Assembly); SkillEffects.Install(_harmony, AdminWarn); _active = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Kratyr Legendary Skills 0.6.0 loaded."); } catch (Exception ex) { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Legendary Skills initialization failed: " + ex)); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = true; } } private void SettingsChanged(object sender, SettingChangedEventArgs args) { RefreshSettings(); } private void RefreshSettings() { LocalPolicy = settings.ReadLocal(); Revision = ((Revision == int.MaxValue) ? 1 : (Revision + 1)); } private void Update() { if (!_active) { return; } SkillConfigSync.Tick(); Player localPlayer = Player.m_localPlayer; ZNet instance = ZNet.instance; if (!Object.op_Implicit((Object)(object)localPlayer) || !Object.op_Implicit((Object)(object)instance)) { appliedPlayer = null; appliedPolicy = null; } else { if (!instance.IsServer() && !SkillConfigSync.Received) { return; } SkillProgression policy = Policy; if (!((Object)(object)appliedPlayer == (Object)(object)localPlayer) || appliedPolicy != policy) { Skills skills = ((Character)localPlayer).GetSkills(); if (skills != null && Object.op_Implicit((Object)(object)skills)) { GameSkillPatches.ApplyLimits(skills, policy); appliedPlayer = localPlayer; appliedPolicy = policy; } } } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.SettingChanged -= SettingsChanged; Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } SkillConfigSync.Reset(); _active = false; } internal static Dictionary<SkillType, Skill> Entries(Skills skills) { if (!Object.op_Implicit((Object)(object)skills)) { return null; } return SkillData.Invoke(skills); } internal static List<KeyValuePair<SkillType, Skill>> GetSkillEntries(Skills skills) { return Entries(skills)?.ToList(); } internal bool TrySetSkillLevel(Skills skills, SkillType type, float proposed, out float actual) { //IL_0025: 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_0044: Expected I4, but got Unknown actual = 0f; if (_active && SkillProgression.Finite(proposed)) { Dictionary<SkillType, Skill> dictionary = Entries(skills); if (dictionary != null && dictionary.TryGetValue(type, out var value) && value != null) { actual = Policy.Limits((int)type).Clamp(proposed); GameSkillPatches.Set(value, actual); return true; } } return false; } internal void AdminLog(string message) { ((BaseUnityPlugin)this).Logger.LogInfo((object)message); } internal void AdminWarn(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); } internal void LogWarningForSort(string message) { AdminWarn(message); } private void Execute(Terminal terminal, string action, string first, string second, string third) { try { string text = (action ?? "status").Trim().ToLowerInvariant(); if (text == "sort") { if (string.IsNullOrEmpty(first)) { terminal.AddString("Skills window sort: " + SkillSortOrder.Value.ToString() + ". Usage: kskills sort default | name | type"); return; } if (!Enum.TryParse<SkillSortMode>(first, ignoreCase: true, out var result) || !Enum.IsDefined(typeof(SkillSortMode), result)) { terminal.AddString("Usage: kskills sort default | name | type"); return; } SkillSortOrder.Value = result; terminal.AddString("Skills window sort changed to " + result.ToString() + ". Reopen Skills to see the result."); } else if (text == "status") { string[] obj = new string[6] { "Kratyr Legendary Skills 0.6.0 active=", _active.ToString(), " range ", null, null, null }; float minimum = Policy.DefaultLimits.Minimum; obj[3] = minimum.ToString(CultureInfo.InvariantCulture); obj[4] = ".."; minimum = Policy.DefaultLimits.Maximum; obj[5] = minimum.ToString(CultureInfo.InvariantCulture); terminal.AddString(string.Concat(obj)); terminal.AddString("Only the host and server-authorized admins may inspect or modify character skill data via kskills."); terminal.AddString("kskills players | inspect <player> | preview <player> [skill] | half <player> | reset <player> [skill] | set <player> <skill> <level>"); } else if (text != "players" && text != "inspect" && text != "preview" && text != "half" && text != "reset" && text != "set") { terminal.AddString("Usage: kskills status | sort default/name/type | players | inspect/half <player> | preview/reset <player> [skill] | set <player> <skill> <level>"); } else { KratyrSkillAdmin.ExecuteConsole(terminal, text, first, second, third); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("kskills command failed: " + ex)); terminal.AddString("kskills failed. See LogOutput.log."); } } } internal static class KratyrSkillAdmin { private struct Pending { public long Target; public long Requester; public string Action; public float SentAt; } [HarmonyPatch(typeof(ZNet), "Awake")] private static class ZNetRegisterPatch { [HarmonyPostfix] private static void Postfix() { Register(ZRoutedRpc.instance); } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class SceneRegisterPatch { [HarmonyPostfix] private static void Postfix() { Register(ZRoutedRpc.instance); } } private const int Protocol = 3; private const long LocalHostRequester = long.MinValue; private const string AdminRequest = "KratyrLS_AdminRequest_v3"; private const string ClientOperation = "KratyrLS_ClientOperation_v3"; private const string ClientReport = "KratyrLS_ClientReport_v3"; private const string AdminResult = "KratyrLS_AdminResult_v3"; private static ZRoutedRpc _registered; private static int _nextTicket; private static readonly Dictionary<int, Pending> PendingOperations = new Dictionary<int, Pending>(); private static void Register(ZRoutedRpc rpc) { if (rpc == null || _registered == rpc) { return; } try { rpc.Register<ZPackage>("KratyrLS_AdminRequest_v3", (Action<long, ZPackage>)OnAdminRequest); rpc.Register<ZPackage>("KratyrLS_ClientOperation_v3", (Action<long, ZPackage>)OnClientOperation); rpc.Register<ZPackage>("KratyrLS_ClientReport_v3", (Action<long, ZPackage>)OnClientReport); rpc.Register<ZPackage>("KratyrLS_AdminResult_v3", (Action<long, ZPackage>)OnAdminResult); _registered = rpc; PendingOperations.Clear(); KratyrLegendarySkills.Instance.AdminLog("Host-authorized skill administration RPC endpoints registered."); } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Cannot register skill admin RPCs (remote management unavailable): " + ex); } } internal static void ExecuteConsole(Terminal terminal, string action, string target, string skillName, string rawLevel) { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown if (!KratyrLegendarySkills.Instance.ActiveForAdmin) { terminal.AddString("Skill administration disabled: plugin initialization failed."); return; } if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null || (Object)(object)Player.m_localPlayer == (Object)null) { terminal.AddString("Enter a hosted or joined world before using skill admin commands."); return; } Register(ZRoutedRpc.instance); if (_registered != ZRoutedRpc.instance) { terminal.AddString("Admin RPC registration failed; see LogOutput.log. No changes made."); return; } if (action != "players" && string.IsNullOrWhiteSpace(target)) { terminal.AddString("Specify a player: kskills " + action + " <player name or peer UID>. Use 'kskills players' to see connected players."); return; } if (action == "set" && (string.IsNullOrWhiteSpace(skillName) || string.IsNullOrWhiteSpace(rawLevel))) { terminal.AddString("Usage: kskills set <player> <existing skill ID/name> <level>."); return; } if (ZNet.instance.IsServer()) { string text = Dispatch(long.MinValue, action, target, skillName, rawLevel); terminal.AddString(text); return; } ZPackage val = new ZPackage(); val.Write(3); val.Write(action); val.Write(target ?? ""); val.Write(skillName ?? ""); val.Write(rawLevel ?? ""); ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null) { terminal.AddString("Cannot identify the host connection; no request sent."); return; } Send(serverPeer.m_uid, "KratyrLS_AdminRequest_v3", val); terminal.AddString("Requested '" + action + "' from host. Only server-approved admins can use these commands. Await response."); } private static void OnAdminRequest(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } if (!IsAuthorizedOnServer(sender)) { KratyrLegendarySkills.Instance.AdminWarn("Rejected unauthorized remote kskills request from peer " + sender); Reply(sender, "Denied: only the host or players authorized in Valheim's server admin list can manage skills."); return; } try { if (package.ReadInt() != 3) { Reply(sender, "Skill admin protocol mismatch. Install the same Kratyr mod version on all clients."); return; } string action = package.ReadString(); string target = package.ReadString(); string skill = package.ReadString(); string value = package.ReadString(); Reply(sender, Dispatch(sender, action, target, skill, value)); } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Malformed skill admin request from " + sender + ": " + ex); Reply(sender, "Malformed administration request rejected."); } } private static bool IsAuthorizedOnServer(long sender) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return false; } ZNetPeer val = ((IEnumerable<ZNetPeer>)ZNet.instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p.m_uid == sender)); if (val == null) { return false; } try { MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "PlayerIsAdmin", new Type[1] { typeof(long) }, (Type[])null); if (methodInfo != null && methodInfo.ReturnType == typeof(bool)) { return (bool)methodInfo.Invoke(ZNet.instance, new object[1] { sender }); } MethodInfo methodInfo2 = AccessTools.Method(typeof(ZNet), "IsAdmin", new Type[1] { typeof(string) }, (Type[])null); if (methodInfo2 == null || methodInfo2.ReturnType != typeof(bool)) { return false; } ZRpc rpc = val.m_rpc; object obj; if (rpc == null) { obj = null; } else { ISocket socket = rpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; return !string.IsNullOrWhiteSpace(text) && (bool)methodInfo2.Invoke(ZNet.instance, new object[1] { text }); } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Admin authorization check unavailable (DENIED): " + ex.Message); return false; } } private static string Dispatch(long requester, string action, string target, string skill, string value) { //IL_03fa: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Expected O, but got Unknown if (action != "players" && action != "inspect" && action != "preview" && action != "half" && action != "reset" && action != "set") { return "Unknown admin command. Use players, inspect, preview, half, reset or set."; } if (action == "players") { List<string> list = new List<string>(); Player localPlayer = Player.m_localPlayer; string text = (((Object)(object)localPlayer == (Object)null) ? "Host" : SafeName(localPlayer)); list.Add("Host: " + text + " [me]"); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { list.Add((peer.m_playerName ?? "(connecting)") + " [" + peer.m_uid.ToString(CultureInfo.InvariantCulture) + "]"); } return "Connected characters: " + string.Join("; ", list.ToArray()); } if (string.IsNullOrWhiteSpace(target) || target.Length > 128) { return "Specify one connected player name or peer UID; use kskills players."; } if ((action == "reset" || action == "preview") && !string.IsNullOrWhiteSpace(skill) && skill.Length > 80) { return "Skill ID/name is too long. Use the exact skill name or numeric ID."; } if (action == "set") { if (!KratyrLegendarySkills.AllowHostTestSet.Value) { return "kskills set is disabled on the host. Enable 'Allow Host Test Set Command' for testing."; } if (string.IsNullOrWhiteSpace(skill) || skill.Length > 80 || !float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || float.IsInfinity(result)) { return "Usage: kskills set <player> <existing skill ID/name> <finite raw level>."; } } bool flag = target.Equals("me", StringComparison.OrdinalIgnoreCase); Player localPlayer2 = Player.m_localPlayer; if (!flag && (Object)(object)localPlayer2 != (Object)null && target.Equals(SafeName(localPlayer2), StringComparison.OrdinalIgnoreCase)) { flag = true; } List<ZNetPeer> list2 = (from peer in ZNet.instance.GetPeers() where peer.m_uid.ToString(CultureInfo.InvariantCulture) == target || string.Equals(peer.m_playerName, target, StringComparison.OrdinalIgnoreCase) select peer).ToList(); if ((flag && list2.Count > 0) || list2.Count > 1) { return "Ambiguous player name. Use kskills players and target a numeric peer UID."; } if (!flag && list2.Count == 0) { return "Player not connected: " + target + ". Use kskills players. Offline characters cannot be edited."; } if (flag) { if ((Object)(object)localPlayer2 == (Object)null || (Object)(object)((Character)localPlayer2).GetSkills() == (Object)null) { return "Host character is not available."; } string text2 = ApplyToLocal(action, skill, value); KratyrLegendarySkills.Instance.AdminLog("Host kskills " + action + " on " + SafeName(localPlayer2) + ": " + text2); return text2; } ZNetPeer val = list2[0]; int num = ++_nextTicket; if (num == 0) { num = ++_nextTicket; } float now = Time.realtimeSinceStartup; int[] array = (from entry in PendingOperations where now - entry.Value.SentAt > 30f select entry.Key).ToArray(); foreach (int key in array) { PendingOperations.Remove(key); } if (PendingOperations.Count >= 64) { return "Too many outstanding skill operations; check if target clients have this mod installed."; } PendingOperations[num] = new Pending { Requester = requester, Target = val.m_uid, Action = action, SentAt = now }; ZPackage val2 = new ZPackage(); val2.Write(3); val2.Write(num); val2.Write(action); val2.Write(skill ?? ""); val2.Write(value ?? ""); Send(val.m_uid, "KratyrLS_ClientOperation_v3", val2); KratyrLegendarySkills.Instance.AdminLog("Host authorized kskills " + action + " on " + val.m_playerName + " (UID " + val.m_uid + ") request=" + num); return "Sent '" + action + "' to " + val.m_playerName + " (" + val.m_uid + "), request #" + num + ". Await result; player must have v0.2.4 installed."; } private static void OnClientOperation(long sender, ZPackage package) { //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return; } ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null || sender != serverPeer.m_uid) { KratyrLegendarySkills.Instance.AdminWarn("Rejected skill modification RPC from NON-SERVER peer " + sender); return; } int num = 0; string text2; try { if (package.ReadInt() != 3) { return; } num = package.ReadInt(); string text = package.ReadString(); string skillName = package.ReadString(); string rawLevel = package.ReadString(); object obj; switch (text) { default: obj = "Rejected unknown operation"; break; case "inspect": case "preview": case "half": case "reset": case "set": obj = ApplyToLocal(text, skillName, rawLevel); break; } text2 = (string)obj; } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Failed host-requested skill operation: " + ex); text2 = "Target error: " + ex.Message; } ZPackage val = new ZPackage(); val.Write(3); val.Write(num); val.Write((text2.Length > 3500) ? text2.Substring(0, 3500) : text2); Send(sender, "KratyrLS_ClientReport_v3", val); } private static bool TryResolveExistingSkill(List<KeyValuePair<SkillType, Skill>> entries, string requested, out KeyValuePair<SkillType, Skill> resolved, out string error) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Invalid comparison between Unknown and I4 //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) resolved = default(KeyValuePair<SkillType, Skill>); error = ""; if (string.IsNullOrWhiteSpace(requested)) { error = "Specify an exact skill name or numeric ID."; return false; } string text = requested.Trim(); if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { foreach (KeyValuePair<SkillType, Skill> entry in entries) { if (entry.Value != null && (int)entry.Key == result) { resolved = entry; return true; } } error = "Skill ID " + result + " is not recorded on the target character. No change made."; return false; } string text2 = NormalizeSkillName(text); if (text2.Length == 0) { error = "Invalid skill name; no change made."; return false; } List<KeyValuePair<SkillType, Skill>> list = new List<KeyValuePair<SkillType, Skill>>(); foreach (KeyValuePair<SkillType, Skill> entry2 in entries) { if (entry2.Value != null) { string b = NormalizeSkillName(((object)entry2.Key/*cast due to .constrained prefix*/).ToString()); string b2 = NormalizeSkillName(KratyrSkillSorting.GetSkillDisplayName(entry2.Value)); if (string.Equals(text2, b, StringComparison.OrdinalIgnoreCase) || string.Equals(text2, b2, StringComparison.OrdinalIgnoreCase)) { list.Add(entry2); } } } if (list.Count != 1) { error = ((list.Count == 0) ? ("Skill not found on target: " + text + ". Use its numeric ID from kskills inspect <player>.") : ("Ambiguous skill name: " + text + ". Use its numeric skill ID from kskills inspect <player>.")); return false; } resolved = list[0]; return true; } private static string NormalizeSkillName(string value) { return new string((value ?? "").Where(char.IsLetterOrDigit).ToArray()); } private static string ApplyToLocal(string action, string skillName, string rawLevel) { //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected I4, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected I4, but got Unknown //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_045d: Unknown result type (might be due to invalid IL or missing references) //IL_0462: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Expected I4, but got Unknown //IL_03de: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ff: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Expected I4, but got Unknown Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)((Character)localPlayer).GetSkills() == (Object)null) { return "Target character is not loaded; no change made."; } Skills skills = ((Character)localPlayer).GetSkills(); List<KeyValuePair<SkillType, Skill>> skillEntries = KratyrLegendarySkills.GetSkillEntries(skills); if (skillEntries == null) { return "Skill records unavailable; no change made."; } if (action == "set") { if (string.IsNullOrEmpty(skillName) || !float.TryParse(rawLevel, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || float.IsInfinity(result)) { return "Invalid set value; no change made."; } if (!TryResolveExistingSkill(skillEntries, skillName, out var resolved, out var error)) { return error; } float level = resolved.Value.m_level; if (!KratyrLegendarySkills.Instance.TrySetSkillLevel(skills, resolved.Key, result, out var actual)) { return "Skill could not be set."; } return "Set " + KratyrSkillSorting.GetSkillDisplayName(resolved.Value) + " (" + (int)resolved.Key + ") " + F(level) + " -> " + F(actual) + " for " + SafeName(localPlayer); } if ((action == "reset" || action == "preview") && !string.IsNullOrWhiteSpace(skillName)) { if (!TryResolveExistingSkill(skillEntries, skillName, out var resolved2, out var error2)) { return error2; } float level2 = resolved2.Value.m_level; if (float.IsNaN(level2) || float.IsInfinity(level2)) { return "Invalid stored skill level; no change made."; } string text = KratyrSkillSorting.GetSkillDisplayName(resolved2.Value) + " (ID " + (int)resolved2.Key + ")"; if (action == "preview") { return "Preview: reset " + text + " on " + SafeName(localPlayer) + ": " + F(level2) + " -> 0 (NO change made)."; } if (level2 == 0f) { return "Skill " + text + " on " + SafeName(localPlayer) + " is already at 0; no change made."; } if (!KratyrLegendarySkills.Instance.TrySetSkillLevel(skills, resolved2.Key, 0f, out var actual2)) { return "Could not reset " + text + "."; } string text2 = "Reset ONLY " + text + " on " + SafeName(localPlayer) + ": " + F(level2) + " -> " + F(actual2) + ". Other skills unchanged."; KratyrLegendarySkills.Instance.AdminLog(text2); return text2; } List<KeyValuePair<SkillType, Skill>> list = (from entry in skillEntries where entry.Value != null && !float.IsNaN(entry.Value.m_level) && !float.IsInfinity(entry.Value.m_level) && (action == "inspect" || entry.Value.m_level < 0f) orderby (int)entry.Key select entry).ToList(); int num = 0; int num2 = 0; List<string> list2 = new List<string>(); foreach (KeyValuePair<SkillType, Skill> item in list) { float level3 = item.Value.m_level; if (action == "half" || action == "reset") { float proposed = ((action == "reset") ? 0f : (level3 * 0.5f)); if (KratyrLegendarySkills.Instance.TrySetSkillLevel(skills, item.Key, proposed, out var actual3)) { num++; list2.Add(((object)item.Key/*cast due to .constrained prefix*/).ToString() + "[" + (int)item.Key + "]:" + F(level3) + "->" + F(actual3)); } else { num2++; } } else if (list2.Count < 24) { list2.Add(((object)item.Key/*cast due to .constrained prefix*/).ToString() + "[" + (int)item.Key + "]=" + F(level3)); } } string text3 = "kskills " + action + " on " + SafeName(localPlayer) + ": " + list.Count + " records; changed " + num + ", failed " + num2 + ". " + string.Join(", ", list2.Take(24).ToArray()); KratyrLegendarySkills.Instance.AdminLog(text3); return text3; } private static void OnClientReport(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } try { if (package.ReadInt() == 3) { int key = package.ReadInt(); string text = package.ReadString(); if (PendingOperations.TryGetValue(key, out var value) && value.Target == sender) { PendingOperations.Remove(key); Reply(value.Requester, "Remote " + value.Action + " completed [#" + key + "]: " + text); } } } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Malformed target result: " + ex); } } private static void OnAdminResult(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return; } ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null || sender != serverPeer.m_uid) { return; } try { if (package.ReadInt() == 3) { ShowResult(package.ReadString()); } } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Malformed admin response: " + ex); } } private static void Reply(long requester, string message) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (requester == long.MinValue) { ShowResult(message); return; } ZPackage val = new ZPackage(); val.Write(3); val.Write((message.Length > 3700) ? message.Substring(0, 3700) : message); Send(requester, "KratyrLS_AdminResult_v3", val); } private static void Send(long target, string method, ZPackage package) { if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.InvokeRoutedRPC(target, method, new object[1] { package }); } } private static void ShowResult(string message) { KratyrLegendarySkills.Instance.AdminLog(message); try { Type type = AccessTools.TypeByName("Console"); FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "instance")); object obj = ((fieldInfo == null) ? null : fieldInfo.GetValue(null)); if (obj == null && type != null) { PropertyInfo propertyInfo = AccessTools.Property(type, "instance"); if (propertyInfo != null) { obj = propertyInfo.GetValue(null, null); } } Terminal val = (Terminal)((obj is Terminal) ? obj : null); if (val != null) { val.AddString(message); } } catch { } } private static string SafeName(Player player) { try { MethodInfo methodInfo = AccessTools.Method(typeof(Player), "GetPlayerName", Type.EmptyTypes, (Type[])null); if (methodInfo != null) { return (methodInfo.Invoke(player, null) as string) ?? "Host"; } } catch { } return "Host"; } private static string F(float value) { return value.ToString("0.###", CultureInfo.InvariantCulture); } } public enum SkillSortMode { Default, Name, Type } internal static class KratyrSkillSorting { private sealed class LevelColor { internal Color Default; } [HarmonyPatch(typeof(SkillsDialog), "Setup", new Type[] { typeof(Player) })] private static class DialogSetupPatch { [HarmonyPrefix] private static void Prefix() { if (_skillsDialogDepth == 0) { _dialogTimer = Stopwatch.StartNew(); } _skillsDialogDepth++; } [HarmonyPostfix] private static void Postfix(SkillsDialog __instance, Player player, List<GameObject> ___m_elements) { try { ColorLevels(player, ___m_elements); if (KratyrLegendarySkills.ShowSkillSortButton.Value) { EnsureButton(__instance); } } catch (Exception ex) { WarnOnce("Cannot display the sort button", ex); } } [HarmonyFinalizer] private static Exception Finalizer(Exception __exception) { _skillsDialogDepth = Math.Max(0, _skillsDialogDepth - 1); if (_skillsDialogDepth == 0 && _dialogTimer != null) { _dialogTimer.Stop(); if (_dialogTimer.ElapsedMilliseconds >= 500 && (Object)(object)KratyrLegendarySkills.Instance != (Object)null) { KratyrLegendarySkills.Instance.LogWarningForSort("SkillsDialog.Setup took " + _dialogTimer.ElapsedMilliseconds + " ms (sort mode " + KratyrLegendarySkills.SkillSortOrder.Value.ToString() + "). Other mods and UI construction are included in this timing."); } _dialogTimer = null; } return __exception; } } [HarmonyPatch(typeof(Skills), "GetSkillList")] private static class GetSkillListPatch { [HarmonyPostfix] [HarmonyPriority(0)] private static void Postfix(ref List<Skill> __result) { if (_skillsDialogDepth <= 0 || __result == null || __result.Count <= 1) { return; } SkillSortMode value = KratyrLegendarySkills.SkillSortOrder.Value; if (value == SkillSortMode.Default) { return; } Stopwatch stopwatch = Stopwatch.StartNew(); try { var source = __result.Select((Skill skill, int index) => new { Skill = skill, Index = index }); switch (value) { case SkillSortMode.Name: __result = (from item in source.OrderBy(item => GetName(item.Skill), StringComparer.CurrentCultureIgnoreCase).ThenBy(item => item.Index) select item.Skill).ToList(); break; case SkillSortMode.Type: __result = (from item in source.OrderBy(item => GetGroupIndex(item.Skill)).ThenBy(item => GetName(item.Skill), StringComparer.CurrentCultureIgnoreCase).ThenBy(item => item.Index) select item.Skill).ToList(); break; } } catch (Exception ex) { WarnOnce("Skills window sort failed; leaving original order", ex); } finally { stopwatch.Stop(); if (stopwatch.ElapsedMilliseconds >= 100 && (Object)(object)KratyrLegendarySkills.Instance != (Object)null) { KratyrLegendarySkills.Instance.LogWarningForSort("GetSkillList sort spent " + stopwatch.ElapsedMilliseconds + " ms sorting " + __result.Count + " skill entries."); } } } } [ThreadStatic] private static int _skillsDialogDepth; [ThreadStatic] private static Stopwatch _dialogTimer; private static bool _warned; private const string ButtonName = "KratyrLegendarySkillsSortButton"; private static readonly ConditionalWeakTable<TMP_Text, LevelColor> LevelColors = new ConditionalWeakTable<TMP_Text, LevelColor>(); private static readonly ConditionalWeakTable<GuiBar, LevelColor> BarColors = new ConditionalWeakTable<GuiBar, LevelColor>(); private static readonly Dictionary<int, string> KnownCustomNames = new Dictionary<int, string> { { 15001, "Vitality" }, { 15002, "Arcana" }, { 15003, "Endurance" }, { 15004, "Exploration" }, { 15005, "Fortitude" }, { 15006, "Hauling" }, { 15007, "Sailing" }, { 15008, "Taming" }, { 16050, "Runeforging" } }; private static readonly Dictionary<int, string> CachedNames = new Dictionary<int, string>(); private static readonly Dictionary<int, int> CachedGroups = new Dictionary<int, int>(); private static string CachedOverrides = ""; private static bool LocalizerInitialized; private static object LocalizerObject; private static MethodInfo LocalizeMethod; private static readonly Dictionary<string, string> DefaultGroups = BuildDefaultGroups(); private static readonly string[] GroupOrder = new string[7] { "Movement", "Combat", "Magic", "Survival", "Gathering", "Crafting", "Other" }; private static Dictionary<string, string> BuildDefaultGroups() { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); AddGroup(dictionary, "Movement", "Run", "Jump", "Swim", "Sneak", "Dodge", "Riding", "Sailing", "Exploration"); AddGroup(dictionary, "Combat", "Swords", "Knives", "Clubs", "Polearms", "Spears", "Axes", "Bows", "Crossbows", "Unarmed", "Fists", "Blocking", "Slingshots", "Throwing", "Dual Mastery", "DualMastery"); AddGroup(dictionary, "Magic", "ElementalMagic", "Elemental Magic", "BloodMagic", "Blood Magic", "Arcana", "Runeforging", "MagicSupremacy", "Magic Supremacy", "Wizardry"); AddGroup(dictionary, "Survival", "Vitality", "Endurance", "Fortitude", "Taming"); AddGroup(dictionary, "Gathering", "WoodCutting", "Wood Cutting", "Pickaxes", "Fishing", "Farming", "Hauling", "Mining"); AddGroup(dictionary, "Crafting", "Crafting", "Cooking", "Fermenting", "Blacksmithing", "Smelting"); return dictionary; } private static void AddGroup(Dictionary<string, string> groups, string group, params string[] names) { foreach (string value in names) { groups[Normalize(value)] = group; } } private static string Normalize(string value) { return new string((value ?? string.Empty).Where(char.IsLetterOrDigit).ToArray()); } internal static string GetSkillDisplayName(Skill skill) { return GetName(skill); } private unsafe static string GetName(Skill skill) { //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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown if (skill == null || skill.m_info == null) { return string.Empty; } SkillType skill2 = skill.m_info.m_skill; int key = (int)skill2; if (KnownCustomNames.TryGetValue(key, out var value)) { return value; } if (CachedNames.TryGetValue(key, out var value2)) { return value2; } string text = ((object)(*(SkillType*)(&skill2))/*cast due to .constrained prefix*/).ToString(); if (string.IsNullOrEmpty(text)) { text = key.ToString(CultureInfo.InvariantCulture); } if (!LocalizerInitialized) { LocalizerInitialized = true; try { Type type = AccessTools.TypeByName("Localization"); if (type != null) { FieldInfo fieldInfo = AccessTools.Field(type, "instance"); LocalizerObject = ((fieldInfo != null) ? fieldInfo.GetValue(null) : null); if (LocalizerObject == null) { PropertyInfo propertyInfo = AccessTools.Property(type, "instance"); if (propertyInfo != null) { LocalizerObject = propertyInfo.GetValue(null, null); } } if (LocalizerObject != null) { LocalizeMethod = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo method) => method.Name == "Localize" && method.GetParameters().Length >= 1 && method.GetParameters()[0].ParameterType == typeof(string)); } } } catch { LocalizeMethod = null; } } string text2 = text; if (LocalizeMethod != null && LocalizerObject != null) { try { ParameterInfo[] parameters = LocalizeMethod.GetParameters(); object[] array = new object[parameters.Length]; array[0] = "$skill_" + text.ToLowerInvariant(); for (int num = 1; num < array.Length; num++) { array[num] = ((parameters[num].ParameterType == typeof(string[])) ? new string[0] : (parameters[num].IsOptional ? parameters[num].DefaultValue : null)); } string text3 = LocalizeMethod.Invoke(LocalizerObject, array) as string; if (!string.IsNullOrEmpty(text3) && (!text3.StartsWith("[") || !text3.EndsWith("]"))) { text2 = text3; } } catch { } } CachedNames[key] = text2; return text2; } private static string GroupOverride(int id, string enumName, string displayName) { string value = KratyrLegendarySkills.SkillSortCategoryOverrides.Value; if (string.IsNullOrWhiteSpace(value)) { return null; } string[] array = value.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array) { int num = text.IndexOf(':'); if (num <= 0) { continue; } string text2 = text.Substring(0, num).Trim(); string proposed = text.Substring(num + 1).Trim(); if (text2.Equals(id.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) || Normalize(text2).Equals(Normalize(enumName), StringComparison.OrdinalIgnoreCase) || Normalize(text2).Equals(Normalize(displayName), StringComparison.OrdinalIgnoreCase)) { return GroupOrder.FirstOrDefault((string group) => group.Equals(proposed, StringComparison.OrdinalIgnoreCase)); } } return null; } private static int GetGroupIndex(Skill skill) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected I4, but got Unknown if (skill == null || skill.m_info == null) { return GroupOrder.Length - 1; } string text = KratyrLegendarySkills.SkillSortCategoryOverrides.Value ?? ""; if (!string.Equals(CachedOverrides, text, StringComparison.Ordinal)) { CachedOverrides = text; CachedGroups.Clear(); } int num = (int)skill.m_info.m_skill; if (CachedGroups.TryGetValue(num, out var value)) { return value; } string text2 = ((object)Unsafe.As<SkillType, SkillType>(ref skill.m_info.m_skill)/*cast due to .constrained prefix*/).ToString(); string name = GetName(skill); string value2 = GroupOverride(num, text2, name); if (value2 == null && !DefaultGroups.TryGetValue(Normalize(name), out value2)) { DefaultGroups.TryGetValue(Normalize(text2), out value2); } int num2 = GroupOrder.Length - 1; if (value2 != null) { for (int i = 0; i < GroupOrder.Length; i++) { if (GroupOrder[i].Equals(value2, StringComparison.OrdinalIgnoreCase)) { num2 = i; break; } } } CachedGroups[num] = num2; return num2; } private static void ColorLevels(Player player, List<GameObject> rows) { //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected I4, but got Unknown //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)((Character)player).GetSkills()) || rows == null) { return; } Color? val = ParseColor(KratyrLegendarySkills.NegativeColor.Value); Color? val2 = ParseColor(KratyrLegendarySkills.ExtendedColor.Value); Color? val3 = ParseColor(KratyrLegendarySkills.TwoStarColor.Value); Color? val4 = ParseColor(KratyrLegendarySkills.ThreeStarColor.Value); Skills skills = ((Character)player).GetSkills(); List<Skill> skillList = skills.GetSkillList(); SkillProgression policy = KratyrLegendarySkills.Policy; TMP_Text val8 = default(TMP_Text); for (int i = 0; i < skillList.Count && i < rows.Count; i++) { GameObject val5 = rows[i]; Skill val6 = skillList[i]; if (!Object.op_Implicit((Object)(object)val5) || val6?.m_info == null) { continue; } Transform val7 = Utils.FindChild(val5.transform, "leveltext", (IterativeSearchType)0); if (!Object.op_Implicit((Object)(object)val7) || !((Component)val7).TryGetComponent<TMP_Text>(ref val8)) { continue; } int id = (int)val6.m_info.m_skill; float num = policy.LevelWithProgress(id, val6.m_level, val6.m_accumulator); (int Level, int Stars) tuple = SkillProgression.DisplayLevel(num); int item = tuple.Level; int item2 = tuple.Stars; LevelColor value = LevelColors.GetValue(val8, (TMP_Text text) => new LevelColor { Default = ((Graphic)text).color }); Color? val9 = item2 switch { 0 => (num < 0f) ? val : ((Color?)null), 1 => val2, 2 => val3, _ => val4, }; ((Graphic)val8).color = (Color)(((??)val9) ?? value.Default); val8.text = item.ToString(CultureInfo.InvariantCulture) + ((item2 > 0) ? new string(LegendaryStar(val8), item2) : ""); GuiBar val10 = FindBar(val5, "currentlevel"); if (Object.op_Implicit((Object)(object)val10)) { val10.SetValue(policy.ProgressFraction(id, val6.m_level, val6.m_accumulator)); ColorBar(val10, val9); } GuiBar val11 = FindBar(val5, "levelbar"); GuiBar val12 = FindBar(val5, "levelbar_total"); Color? color = ((item2 > 0) ? val9 : ((Color?)null)); if (Object.op_Implicit((Object)(object)val11)) { ColorBar(val11, color); } if (Object.op_Implicit((Object)(object)val12)) { ColorBar(val12, color.HasValue ? new Color?(Color.Lerp(color.Value, Color.white, 0.25f)) : ((Color?)null)); } if (item2 != 0) { float maximum = policy.Limits(id).Maximum; if (Object.op_Implicit((Object)(object)val11)) { val11.SetValue(SkillProgression.TierProgress(num, maximum, item2)); } if (Object.op_Implicit((Object)(object)val12)) { val12.SetValue(SkillProgression.TierProgress(skills.GetSkillLevel(val6.m_info.m_skill), maximum, item2)); } } } } private static Color? ParseColor(string value) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) Color value2 = default(Color); if (!ColorUtility.TryParseHtmlString(value, ref value2)) { return null; } return value2; } private static char LegendaryStar(TMP_Text label) { if (!Object.op_Implicit((Object)(object)label.font) || !label.font.HasCharacter('★', true, true)) { return '*'; } return '★'; } private static GuiBar FindBar(GameObject row, string path) { Transform val = Utils.FindChild(row.transform, path, (IterativeSearchType)0); if (!Object.op_Implicit((Object)(object)val)) { return null; } return ((Component)val).GetComponent<GuiBar>(); } private static void ColorBar(GuiBar bar, Color? color) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) LevelColor value; if (color.HasValue) { BarColors.GetValue(bar, (GuiBar b) => new LevelColor { Default = b.GetColor() }); bar.SetColor(color.Value); } else if (BarColors.TryGetValue(bar, out value)) { bar.SetColor(value.Default); BarColors.Remove(bar); } } private static void EnsureButton(SkillsDialog dialog) { //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Expected O, but got Unknown if ((Object)(object)dialog == (Object)null) { return; } Transform transform = ((Component)dialog).transform; RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null); if ((Object)(object)val == (Object)null) { val = ((Component)dialog).GetComponentInParent<RectTransform>(); } if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).GetComponentInParent<Canvas>() == (Object)null) { WarnOnce("Sort button has no compatible RectTransform / Canvas parent", new InvalidOperationException("SkillsDialog UI hierarchy is incompatible")); return; } Transform val2 = ((Transform)val).Find("KratyrLegendarySkillsSortButton"); GameObject val3; TMP_Text val4; if ((Object)(object)val2 != (Object)null) { val3 = ((Component)val2).gameObject; Button component = val3.GetComponent<Button>(); val4 = val3.GetComponentInChildren<TMP_Text>(true); } else { val3 = new GameObject("KratyrLegendarySkillsSortButton", new Type[3] { typeof(RectTransform), typeof(Image), typeof(Button) }); val3.transform.SetParent((Transform)(object)val, false); Image component2 = val3.GetComponent<Image>(); ((Graphic)component2).color = new Color(0.21f, 0.13f, 0.075f, 0.94f); Button component = val3.GetComponent<Button>(); ((Selectable)component).targetGraphic = (Graphic)(object)component2; GameObject val5 = new GameObject("Label", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }); val5.transform.SetParent(val3.transform, false); val4 = (TMP_Text)(object)val5.GetComponent<TextMeshProUGUI>(); val4.alignment = (TextAlignmentOptions)514; ((Graphic)val4).color = new Color(1f, 0.78f, 0.34f, 1f); val4.fontSize = 16f; ((Graphic)val4).raycastTarget = false; val4.textWrappingMode = (TextWrappingModes)0; TMP_Text val6 = ((IEnumerable<TMP_Text>)((Component)dialog).GetComponentsInChildren<TMP_Text>(true)).FirstOrDefault((Func<TMP_Text, bool>)((TMP_Text text) => ((Object)text).name.Equals("name", StringComparison.OrdinalIgnoreCase))); if ((Object)(object)val6 != (Object)null) { val4.font = val6.font; val4.fontSize = Mathf.Clamp(val6.fontSize * 0.9f, 13f, 19f); } RectTransform val7 = (RectTransform)val5.transform; val7.anchorMin = Vector2.zero; val7.anchorMax = Vector2.one; val7.offsetMin = Vector2.zero; val7.offsetMax = Vector2.zero; ((UnityEvent)component.onClick).AddListener((UnityAction)delegate { CycleMode(dialog); }); } RectTransform val8 = (RectTransform)val3.transform; val8.anchorMin = Vector2.one; val8.anchorMax = Vector2.one; val8.pivot = new Vector2(0.5f, 0.5f); val8.sizeDelta = new Vector2(166f, 32f); val8.anchoredPosition = new Vector2(KratyrLegendarySkills.SkillSortButtonX.Value, KratyrLegendarySkills.SkillSortButtonY.Value); val3.transform.SetAsLastSibling(); if ((Object)(object)val4 != (Object)null) { val4.text = "Sort: " + ((KratyrLegendarySkills.SkillSortOrder.Value == SkillSortMode.Default) ? "Default" : KratyrLegendarySkills.SkillSortOrder.Value.ToString()); } } private static void CycleMode(SkillsDialog dialog) { SkillSortMode value = KratyrLegendarySkills.SkillSortOrder.Value; KratyrLegendarySkills.SkillSortOrder.Value = value switch { SkillSortMode.Name => SkillSortMode.Type, SkillSortMode.Default => SkillSortMode.Name, _ => SkillSortMode.Default, }; try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)dialog != (Object)null && (Object)(object)localPlayer != (Object)null) { MethodInfo methodInfo = AccessTools.Method(typeof(SkillsDialog), "Setup", new Type[1] { typeof(Player) }, (Type[])null); if (methodInfo != null) { methodInfo.Invoke(dialog, new object[1] { localPlayer }); } } } catch (Exception ex) { WarnOnce("Cannot refresh skills menu; reopen it after sorting", ex); } } private static void WarnOnce(string message, Exception ex) { if (!_warned) { _warned = true; if ((Object)(object)KratyrLegendarySkills.Instance != (Object)null) { KratyrLegendarySkills.Instance.LogWarningForSort(message + ": " + ex); } } } } internal static class SkillConfigSync { private const int WireVersion = 4; private const string Request = "KratyrLegendarySkills.ConfigRequest.v4"; private const string Response = "KratyrLegendarySkills.ConfigResponse.v4"; private static readonly Dictionary<long, float> nextResponse = new Dictionary<long, float>(); private static ZRoutedRpc registered; private static long serverId; private static float nextRequest; private static int remoteRevision = -1; internal static SkillProgression Remote { get; private set; } internal static bool Received { get; private set; } internal static void Tick() { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown ZNet instance = ZNet.instance; ZRoutedRpc instance2 = ZRoutedRpc.instance; if (!Object.op_Implicit((Object)(object)instance) || instance2 == null) { if (registered != null) { Reset(); } return; } if (registered != instance2) { Reset(); instance2.Register<ZPackage>("KratyrLegendarySkills.ConfigRequest.v4", (Action<long, ZPackage>)OnRequest); instance2.Register<ZPackage>("KratyrLegendarySkills.ConfigResponse.v4", (Action<long, ZPackage>)OnResponse); registered = instance2; } if (instance.IsServer()) { return; } ZNetPeer serverPeer = instance.GetServerPeer(); if (serverPeer != null && serverPeer.m_uid != 0L) { if (serverPeer.m_uid != serverId) { ClearRemote(); serverId = serverPeer.m_uid; } if (!(Time.unscaledTime < nextRequest)) { nextRequest = Time.unscaledTime + (Received ? 3f : 1f); ZPackage val = new ZPackage(); val.Write(4); val.Write(remoteRevision); instance2.InvokeRoutedRPC(serverId, "KratyrLegendarySkills.ConfigRequest.v4", new object[1] { val }); } } } private static void OnRequest(long sender, ZPackage packet) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown ZNet instance = ZNet.instance; if (!Object.op_Implicit((Object)(object)instance) || !instance.IsServer() || instance.GetPeer(sender) == null || packet == null || packet.Size() != 8 || packet.ReadInt() != 4) { return; } int num = packet.ReadInt(); float unscaledTime = Time.unscaledTime; if (nextResponse.TryGetValue(sender, out var value) && unscaledTime < value) { return; } if (nextResponse.Count > 512) { nextResponse.Clear(); } nextResponse[sender] = unscaledTime + 0.75f; int revision = KratyrLegendarySkills.Revision; if (num != revision) { ZPackage val = new ZPackage(); val.Write(4); val.Write(revision); bool value2 = KratyrLegendarySkills.LockConfig.Value; val.Write(value2); if (value2) { SkillSettings.Write(val, KratyrLegendarySkills.LocalPolicy); } registered.InvokeRoutedRPC(sender, "KratyrLegendarySkills.ConfigResponse.v4", new object[1] { val }); } } private static void OnResponse(long sender, ZPackage packet) { ZNet instance = ZNet.instance; if (!Object.op_Implicit((Object)(object)instance) || instance.IsServer() || sender == 0L || sender != serverId) { return; } ZNetPeer serverPeer = instance.GetServerPeer(); if (serverPeer == null || serverPeer.m_uid != sender || packet == null || packet.Size() < 9 || packet.Size() > 8192) { return; } try { if (packet.ReadInt() != 4) { return; } int num = packet.ReadInt(); if (num != remoteRevision) { SkillProgression remote = (packet.ReadBool() ? SkillSettings.ReadRemote(packet) : null); if (packet.GetPos() == packet.Size()) { Remote = remote; remoteRevision = num; Received = true; } } } catch (Exception ex) { KratyrLegendarySkills.Instance.AdminWarn("Invalid host skill settings: " + ex.Message); } } private static void ClearRemote() { serverId = 0L; nextRequest = 0f; remoteRevision = -1; Received = false; Remote = null; } internal static void Reset() { registered = null; nextResponse.Clear(); ClearRemote(); } } internal static class SkillEffects { private static readonly MethodInfo Lerp = typeof(Mathf).GetMethod("Lerp", new Type[3] { typeof(float), typeof(float), typeof(float) }); private static readonly MethodInfo Pow = typeof(Mathf).GetMethod("Pow", new Type[2] { typeof(float), typeof(float) }); private static readonly MethodInfo Clamp01 = typeof(Mathf).GetMethod("Clamp01", new Type[1] { typeof(float) }); private static readonly MethodInfo Clamp = typeof(Mathf).GetMethod("Clamp", new Type[3] { typeof(float), typeof(float), typeof(float) }); private static readonly FieldInfo SummonCoefficient = typeof(SpawnAbility).GetField("m_copySkillToRandomFactor"); private static SkillProgression Policy => KratyrLegendarySkills.Policy; internal static void Install(Harmony harmony, Action<string> warn) { //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Expected O, but got Unknown //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Expected O, but got Unknown Patch(AccessTools.DeclaredMethod(typeof(Skills), "GetSkillFactor", new Type[1] { typeof(SkillType) }, (Type[])null), "SignedFactorTranspiler"); Patch(AccessTools.DeclaredMethod(typeof(Skills), "GetRandomSkillRange", (Type[])null, (Type[])null), "FirstLerp"); Patch(AccessTools.DeclaredMethod(typeof(Skills), "GetRandomSkillFactor", (Type[])null, (Type[])null), "FirstLerp"); string[] array = new string[4] { "CheckRun", "OnSwimming", "GetDodgeStaminaUse", "UpdateStealth" }; foreach (string text in array) { Patch(AccessTools.DeclaredMethod(typeof(Player), text, (Type[])null, (Type[])null), "SkillLerp"); } Patch(AccessTools.DeclaredMethod(typeof(Player), "OnSneaking", (Type[])null, (Type[])null), "SneakLerp"); Patch(AccessTools.DeclaredMethod(typeof(Humanoid), "GetAttackDrawPercentage", (Type[])null, (Type[])null), "SkillLerp"); Patch(AccessTools.DeclaredMethod(typeof(ItemData), "GetWeaponLoadingTime", (Type[])null, (Type[])null), "SkillLerp"); Patch(AccessTools.DeclaredMethod(typeof(Sadle), "UpdateRiding", (Type[])null, (Type[])null), "SkillLerp"); Patch(AccessTools.DeclaredMethod(typeof(FishingFloat), "FixedUpdate", (Type[])null, (Type[])null), "FishingLerp"); Patch(AccessTools.DeclaredMethod(typeof(Piece), "Awake", (Type[])null, (Type[])null), "HarvestLerp"); Patch(AccessTools.DeclaredMethod(typeof(Piece), "OnPlaced", (Type[])null, (Type[])null), "HarvestLerp"); Patch(AccessTools.DeclaredMethod(typeof(Attack), "DoMeleeAttack", (Type[])null, (Type[])null), "SkillLerp"); Patch(AccessTools.DeclaredMethod(typeof(Attack), "FireProjectileBurst", (Type[])null, (Type[])null), "SkillLerp"); MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(SpawnAbility), "Spawn", (Type[])null, (Type[])null); Patch((methodInfo == null) ? null : AccessTools.EnumeratorMoveNext((MethodBase)methodInfo), "SummonTranspiler"); MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(SE_Shield), "SetLevel", new Type[2] { typeof(int), typeof(float) }, (Type[])null); if (methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(SkillEffects), "ShieldPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } if (Chainloader.PluginInfos.TryGetValue("balrond.astafaraios.BalrondExtraSkills", out var value) && Object.op_Implicit((Object)(object)value.Instance)) { Assembly assembly = ((object)value.Instance).GetType().Assembly; Type type = assembly.GetType("BalrondExtraSkills.Compatibility.NegativeSkillsCompat"); MethodInfo methodInfo3 = ((type == null) ? null : AccessTools.PropertyGetter(type, "IsActive")); if (methodInfo3?.ReturnType == typeof(bool)) { harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(SkillEffects), "ExtraSkillsDetected", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Type type2 = assembly.GetType("BalrondExtraSkills.BesSkillPersistence"); Patch((type2 == null) ? null : AccessTools.DeclaredMethod(type2, "RestoreAfterPlayerLoad", new Type[1] { typeof(Player) }, (Type[])null), "ExtraSkillsRestore"); Type type3 = assembly.GetType("BalrondExtraSkills.BalrondSkillSystem+Skills_CheatRaiseSkill_Patch"); Patch((type3 == null) ? null : AccessTools.DeclaredMethod(type3, "Prefix", (Type[])null, (Type[])null), "ExtraSkillsCheat"); Type type4 = assembly.GetType("BalrondExtraSkills.SkillRuntime"); if (type4 != null) { Patch(AccessTools.DeclaredMethod(type4, "GetLevel", new Type[3] { typeof(Player), typeof(SkillType), typeof(bool) }, (Type[])null), "ExtraSkillsLevel"); Patch(AccessTools.DeclaredMethod(type4, "SignedFactor", new Type[1] { typeof(float) }, (Type[])null), "ExtraSkillsFactor"); Patch(AccessTools.DeclaredMethod(type4, "SignedFactor", new Type[2] { typeof(Player), typeof(SkillType) }, (Type[])null), "ExtraSkillsFactor"); } } void Patch(MethodInfo method, string hook) { //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_004e: Expected O, but got Unknown if (method == null) { warn("A skill effect entry point for " + hook + " was unavailable."); return; } try { harmony.Patch((MethodBase)method, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(SkillEffects), hook, (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { warn("Skill effect hook for " + method.Name + " was unavailable: " + ex.Message); } } } private static void ExtraSkillsDetected(ref bool __result) { __result = Policy.NegativeSkills; } private static float SignedFactor(float normalized) { return Policy.Factor(normalized * 100f); } private static float SignedPower(float value, float exponent) { if (!(value < 0f)) { return Mathf.Pow(value, exponent); } return 0f - Mathf.Pow(0f - value, exponent); } private static float ExtendLerp(float baseline, float trained, float factor) { if (!(factor < 0f)) { return Mathf.Lerp(baseline, trained, factor); } return Mathf.LerpUnclamped(baseline, trained, factor); } private static float Harvest(float baseline, float trained, float factor) { if (!(factor < 0f)) { return Mathf.Lerp(baseline, trained, factor); } return Math.Max(baseline * Policy.HarvestFloor, ExtendLerp(baseline, trained, factor)); } private static float Fish(float baseline, float trained, float factor) { if (!(factor < 0f)) { return Mathf.Lerp(baseline, trained, factor); } return Math.Max(baseline * Policy.FishingFloor, ExtendLerp(baseline, trained, factor)); } private static float AddSummonFactor(float baseline, float adjustment) { if (!(adjustment < 0f)) { return baseline + adjustment; } return Math.Max(baseline * Policy.SummonFloor, baseline + adjustment * Policy.NegativeEffect); } private static void ShieldPrefix(SE_Shield __instance, ref float __1) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 if (!(__1 >= 0f) && (int)__instance.m_levelUpSkillOnBreak == 10 && __instance.m_absorbDamagePerSkillLevel > 0f) { float val = (0f - __instance.m_absorbDamage) * (1f - Policy.ShieldFloor) / __instance.m_absorbDamagePerSkillLevel; __1 = Math.Max(val, __1 * Policy.NegativeEffect); } } private static IEnumerable<CodeInstruction> SignedFactorTranspiler(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return Replace(source, __originalMethod, Clamp01, "SignedFactor", 1); } private static IEnumerable<CodeInstruction> FirstLerp(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return Replace(source, __originalMethod, Lerp, "ExtendLerp", (!(__originalMethod.Name == "GetRandomSkillFactor")) ? 1 : 2, 1); } private static IEnumerable<CodeInstruction> SkillLerp(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return ReplaceAfterSkill(source, __originalMethod, "ExtendLerp", 1); } private static IEnumerable<CodeInstruction> HarvestLerp(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return ReplaceAfterSkill(source, __originalMethod, "Harvest", 1); } private static IEnumerable<CodeInstruction> FishingLerp(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return ReplaceAfterSkill(source, __originalMethod, "Fish", 3); } private static IEnumerable<CodeInstruction> SneakLerp(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return Replace(ReplaceAfterSkill(source, __originalMethod, "ExtendLerp", 1), __originalMethod, Pow, "SignedPower", 1); } private static IEnumerable<CodeInstruction> Replace(IEnumerable<CodeInstruction> source, MethodBase original, MethodInfo call, string hook, int expected, int count = 0) { List<CodeInstruction> list = source.ToList(); CodeInstruction[] array = list.Where((CodeInstruction i) => CodeInstructionExtensions.Calls(i, call)).ToArray(); if (array.Length == expected) { foreach (CodeInstruction item in array.Take((count == 0) ? expected : count)) { item.operand = Hook(hook); } } else { Unexpected(original, hook); } return list; } private static IEnumerable<CodeInstruction> ReplaceAfterSkill(IEnumerable<CodeInstruction> source, MethodBase original, string hook, int count) { List<CodeInstruction> list = source.ToList(); int num = list.FindIndex((CodeInstruction i) => i.operand is MethodInfo methodInfo && (methodInfo.Name == "GetSkillFactor" || methodInfo.Name == "GetRiderSkill") && (methodInfo.DeclaringType == typeof(Skills) || methodInfo.DeclaringType == typeof(Character) || methodInfo.DeclaringType == typeof(Sadle))); CodeInstruction[] array = ((num < 0) ? Array.Empty<CodeInstruction>() : (from i in list.Skip(num + 1) where CodeInstructionExtensions.Calls(i, Lerp) select i).ToArray()); if (array.Length == count) { CodeInstruction[] array2 = array; for (int num2 = 0; num2 < array2.Length; num2++) { array2[num2].operand = Hook(hook); } } else { Unexpected(original, hook); } return list; } private static IEnumerable<CodeInstruction> SummonTranspiler(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { List<CodeInstruction> code = source.ToList(); int[] array = (from i in Enumerable.Range(1, Math.Max(0, code.Count - 3)) where object.Equals(code[i].operand, SummonCoefficient) && code[i + 1].opcode == OpCodes.Mul && code[i + 2].opcode == OpCodes.Add select i).ToArray(); if (array.Length == 1) { code[array[0] + 2].opcode = OpCodes.Call; code[array[0] + 2].operand = Hook("AddSummonFactor"); } else { Unexpected(__originalMethod, "AddSummonFactor"); } return code; } private static IEnumerable<CodeInstruction> ExtraSkillsRestore(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return Replace(source, __originalMethod, Clamp, "KeepStoredLevel", 1); } private static IEnumerable<CodeInstruction> ExtraSkillsCheat(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return GameSkillPatches.ReplaceCheatClamp(source, __originalMethod); } private static IEnumerable<CodeInstruction> ExtraSkillsLevel(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return Replace(source, __originalMethod, Clamp, "ExtraSkillLevel", 4); } private static IEnumerable<CodeInstruction> ExtraSkillsFactor(IEnumerable<CodeInstruction> source, MethodBase __originalMethod) { return Replace(source, __originalMethod, Clamp, "ExtraSkillFactor", 1); } private static float KeepStoredLevel(float value, float previousMin, float previousMax) { if (!SkillProgression.Finite(value)) { return 0f; } return value; } private static float ExtraSkillLevel(float value, float minimum, float maximum) { return Mathf.Clamp(value, minimum, Policy.ExtendFactors ? (100f * Policy.FactorCap) : maximum); } private static float ExtraSkillFactor(float value, float minimum, float maximum) { return SignedFactor(value); } private static MethodInfo Hook(string name) { return typeof(SkillEffects).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic); } private static void Unexpected(MethodBase original, string hook) { KratyrLegendarySkills.Instance?.AdminWarn("Skill effect " + hook + " did not match " + original.DeclaringType?.Name + "." + original.Name + "."); } } internal enum SkillLossCurve { VeryForgiving, Forgiving, Normal, Harsh, VeryHarsh } internal readonly struct SkillLimits { internal readonly float Minimum; internal readonly float Maximum; internal SkillLimits(float minimum, float maximum) { Minimum = minimum; Maximum = maximum; } internal float Clamp(float level) { if (!SkillProgression.Finite(level)) { return 0f; } return Math.Max(Minimum, Math.Min(Maximum, level)); } } internal readonly struct SkillBand { internal readonly float Gain; internal readonly float Cost; internal readonly float Exponent; internal readonly float Loss; internal readonly float MinimumLoss; internal readonly SkillLossCurve Curve; internal SkillBand(float gain, float cost, float exponent, float loss, float minimumLoss, SkillLossCurve curve = SkillLossCurve.Normal) { Gain = gain; Cost = cost; Exponent = exponent; Loss = loss; MinimumLoss = minimumLoss; Curve = curve; } } internal sealed class SkillProgression { internal const float AbsoluteLimit = 500f; private const int LevelsPerTier = 100; internal const float MaximumFactor = 5f; internal readonly SkillLimits DefaultLimits; internal readonly SkillBand Negative; internal readonly SkillBand Standard; internal readonly SkillBand Extended; internal readonly bool CrossZero; internal readonly bool ProtectZero; internal readonly bool NoNegativeCredit; internal readonly bool ExtendFactors; internal readonly bool VanillaLoss; internal readonly bool NegativeSkills; internal readonly int GraceMinutes; internal readonly float ZeroBand; internal readonly float NegativeEffect; internal readonly float FactorCap; internal readonly float HarvestFloor; internal readonly float FishingFloor; internal readonly float SummonFloor; internal readonly float ShieldFloor; internal readonly string CapOverrides; private readonly Dictionary<int, SkillLimits> limits; internal SkillProgression(SkillLimits defaultLimits, SkillBand negative, SkillBand standard, SkillBand extended, bool crossZero, bool protectZero, bool noNegativeCredit, float zeroBand, float negativeEffect, bool extendFactors, float factorCap, float harvestFloor, float fishingFloor, float summonFloor, float shieldFloor, string capOverrides, Dictionary<int, SkillLimits> limits, bool vanillaLoss = false, int graceMinutes = 60, bool negativeSkills = true) { NegativeSkills = negativeSkills; DefaultLimits = (negativeSkills ? defaultLimits : new SkillLimits(0f, defaultLimits.Maximum)); Negative = negative; Standard = standard; Extended = extended; CrossZero = negativeSkills && crossZero; ProtectZero = protectZero; NoNegativeCredit = noNegativeCredit; ZeroBand = zeroBand; NegativeEffect = (negativeSkills ? negativeEffect : 0f); ExtendFactors = extendFactors; FactorCap = factorCap; HarvestFloor = harvestFloor; FishingFloor = fishingFloor; SummonFloor = summonFloor; ShieldFloor = shieldFloor; CapOverrides = capOverrides; this.limits = limits; VanillaLoss = vanillaLoss; GraceMinutes = graceMinutes; } internal SkillLimits Limits(int id) { if (!limits.TryGetValue(id, out var value)) { return DefaultLimits; } if (!NegativeSkills) { return new SkillLimits(0f, value.Maximum); } return value; } internal SkillBand Band(float level) { if (!(level < 0f)) { if (!(level < 100f)) { return Extended; } return Standard; } return Negative; } internal static bool Finite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } internal float Required(float level) { SkillBand skillBand = Band(level); double val = ((level < 0f) ? Math.Ceiling(0f - level) : Math.Floor(level + 1f)); return (float)((double)skillBand.Cost * (0.5 * Math.Pow(Math.Max(1.0, val), skillBand.Exponent) + 0.5)); } private static float NextLevel(float level, SkillLimits limits) { return Math.Min(limits.Maximum, (float)Math.Floor(level) + 1f); } internal float LevelWithProgress(int id, float rawLevel, float progress) { SkillLimits skillLimits = Limits(id); float num = skillLimits.Clamp(rawLevel); if (!(progress > 0f) || !Finite(progress) || num >= skillLimits.Maximum) { return num; } float num2 = NextLevel(num, skillLimits); float num3 = num + progress / Required(num); if (!(num3 < num2)) { return Math.Max(num, num2 - 0.0001f); } return num3; } internal float ProgressFraction(int id, float rawLevel, float progress) { if (rawLevel >= Limits(id).Maximum) { return 1f; } float num = LevelWithProgress(id, rawLevel, progress); return num - (float)Math.Floor(num); } internal static (int Level, int Stars) DisplayLevel(float rawLevel) { int num = (int)Math.Floor(rawLevel); if (num <= 100) { return (Level: num, Stars: 0); } int num2 = (num - 1) / 100; return (Level: num - num2 * 100, Stars: num2); } internal static float TierProgress(float rawLevel, float maximum, int stars) { float num = stars * 100; float num2 = Math.Min(100f, maximum - num); if (!(num2 > 0f)) { return 0f; } return Math.Max(0f, Math.Min(1f, (rawLevel - num) / num2)); } internal bool Earn(int id, ref float level, ref float progress, float xp) { if (!(xp > 0f) || !Finite(xp)) { return false; } SkillLimits skillLimits = Limits(id); float num = skillLimits.Clamp(level); if (num != level) { progress = 0f; } level = num; if (level >= skillLimits.Maximum) { return false; } double num2 = (Finite(progress) ? ((double)Math.Max(0f, progress)) : 0.0); double num3 = xp; bool result = false; while (level < skillLimits.Maximum) { float gain = Band(level).Gain; if (!(gain > 0f)) { break; } float num4 = NextLevel(level, skillLimits); float num5 = Required(level) * (num4 - level); if (num2 > (double)num5) { num3 += (num2 - (double)num5) / (double)gain; num2 = num5; } double num6 = Math.Max(0.0, (double)num5 - num2) / (double)gain; if (num3 < num6) { num2 += num3 * (double)gain; break; } num3 -= num6; num2 = 0.0; level = num4; result = true; if (num3 <= 0.0) { break; } } progress = ((level >= skillLimits.Maximum) ? 0f : ((float)num2)); return result; } internal float AfterDeath(int id, float currentLevel, float factor, long now, long lastGrace, out bool protectedLevel) { protectedLevel = false; if (!(factor > 0f) || !Finite(factor)) { return currentLevel; } SkillLimits skillLimits = Limits(id); float num = skillLimits.Clamp(currentLevel); if (ProtectZero && num >= 0f && num < 1f) { return num; } SkillBand skillBand = ((num == 100f) ? Standard : Band(num)); float num2 = factor * skillBand.Loss; float num3 = Math.Max(Math.Abs(num) * num2 * LossWeight(num, skillBand.Curve), skillBand.MinimumLoss); if (CrossZero && num >= 0f && num <= ZeroBand && num2 > 0f) { num3 = Math.Max(num3, Math.Max(Negative.MinimumLoss, ZeroBand * num2)); } float num4 = num - num3; if (!CrossZero && num >= 0f) { num4 = Math.Max(0f, num4); } num4 = skillLimits.Clamp(num4); float num5 = (float)Math.Floor(num); if (num4 < num5 && GraceMinutes > 0 && now > 0 && (lastGrace <= 0 || (now >= lastGrace && now - lastGrace >= (long)GraceMinutes * 60L))) { protectedLevel = true; return num5; } return num4; } private unsafe static float LossWeight(float level, SkillLossCurve curve) { object obj = curve switch { SkillLossCurve.VeryForgiving => (0.4, 1.3), SkillLossCurve.Forgiving => (0.7, 1.1), SkillLossCurve.Harsh => (1.25, 0.5), SkillLossCurve.VeryHarsh => (1.55, 0.2), _ => (1.0, 0.95), }; double item = ((ValueTuple<double, double>*)(&obj))->Item1; double item2 = ((ValueTuple<double, double>*)(&obj))->Item2; double num = (double)Math.Abs(level) / 100.0; if (num > 1.0) { num = 1.0 + 0.18 * (1.0 - 1.0 / num); } return (float)(item * Math.Pow(num, item2)); } internal float Factor(float level) { if (!Finite(level)) { return 0f; } if (level < 0f) { return Math.Max(-1f, level * (NegativeEffect / 100f)); } return Math.Min(ExtendFactors ? FactorCap : 1f, level / 100f); } internal static bool TryParseLimits(string text, Func<string, int?> parseId, out Dictionary<int, SkillLimits> parsed) { parsed = new Dictionary<int, SkillLimits>(); if (string.IsNullOrWhiteSpace(text)) { return true; } if (text.Length > 4096) { return false; } string[] array = text.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text2 in array) { int num = text2.IndexOf('='); if (num <= 0) { return false; } int? num2 = parseId(text2.Substring(0, num).Trim()); string[] array2 = text2.Substring(num + 1).Split(new char[1] { ',' }); if (!num2.HasValue || num2.Value <= 0 || parsed.ContainsKey(num2.Value) || array2.Length != 2 || parsed.Count >= 128 || !float.TryParse(array2[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || !float.TryParse(array2[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) || !(result >= -500f) || !(result <= 0f) || !(result2 >= 1f) || !(result2 <= 500f)) { return false; } parsed.Add(num2.Value, new SkillLimits(result, result2)); } return true; } } internal sealed class SkillSettings { private sealed class BandEntries { private readonly ConfigEntry<float> gain; private readonly ConfigEntry<float> cost; private readonly ConfigEntry<float> exponent; private readonly ConfigEntry<float> loss; private readonly ConfigEntry<float> minimumLoss; private readonly ConfigEntry<SkillLossCurve> lossCurve; internal BandEntries(ConfigFile config, string name, string gainName, float defaultGain, float defaultMinimumLoss) { gain = Number(config, "2 - Experience", gainName, defaultGain, 0f, 20f, "Amount of XP that counts toward progress in this band. 0 pauses gain."); cost = Number(config, "2 - Experience", name + " XP Cost Multiplier", 1f, 0.05f, 20f, "Multiplier on the XP required for each level in this band."); exponent = Number(config, "2 - Experience", name + " XP Curve Exponent", 1.5f, 0.25f, 3f, "Controls how much more XP is required for higher levels, or for recovery from deeper negative levels."); loss = Number(config, "3 - Death", name + " Skill Loss Multiplier", 1f, 0f, 20f, "Multiplier on Valheim's configured death loss for levels in this band."); minimumLoss = Number(config, "3 - Death", name + " Minimum Death Loss", defaultMinimumLoss, 0f, 50f, "Minimum raw levels lost on a death that incurs skill loss."); lossCurve = config.Bind<SkillLossCurve>("3 - Death", ((name == "Extended") ? "Legendary" : name) + " Skill Loss Curve", SkillLossCurve.Normal, "Curve applied to the world's skill loss in this band."); } internal SkillBand Read() { SkillLossCurve skillLossCurve = lossCurve.Value; if (skillLossCurve < SkillLossCurve.VeryForgiving || skillLossCurve > SkillLossCurve.VeryHarsh) { skillLossCurve = SkillLossCurve.Normal; } return new SkillBand(SkillSettings.Read(gain), SkillSettings.Read(cost), SkillSettings.Read(exponent), SkillSettings.Read(loss), SkillSettings.Read(minimumLoss), skillLossCurve); } } internal const string OldConfig = "kratyr.valheim.unifiedskills.playtest.cfg"; internal const string ExpandedConfig = "com.kratyr.expandedskills.cfg"; internal const string BalrondConfig = "balrond.astafaraios.BalrondNegativeSkills.cfg"; private const string Caps = "1 - Skill Caps"; private const string Xp = "2 - Experience"; private const string Death = "3 - Death"; private const string Effects = "4 - Effects"; private readonly ConfigEntry<float> minimum; private readonly ConfigEntry<float> maximum; private readonly ConfigEntry<float> zeroBand; private readonly ConfigEntry<float> negativeEffect; private readonly ConfigEntry<float> factorCap; private readonly ConfigEntry<float> harvestFloor; private readonly ConfigEntry<float> fishingFloor; private readonly ConfigEntry<float> summonFloor; private readonly ConfigEntry<float> shieldFloor; private readonly ConfigEntry<bool> negativeSkills; private readonly ConfigEntry<bool> crossZero; private readonly ConfigEntry<bool> protectZero; private readonly ConfigEntry<bool> noNegativeCredit; private readonly ConfigEntry<bool> extendFactors; private readonly ConfigEntry<bool> vanillaLoss; private readonly ConfigEntry<int> graceMinutes; private readonly ConfigEntry<string> overrides; private readonly BandEntries negative; private readonly BandEntries standard; private readonly BandEntries extended; private readonly Action<string> warn; private string acceptedOverrides = ""; private string rejectedOverrides; internal SkillSettings(ConfigFile config, Action<string> warn, ConfigFile legacy) { //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown ConfigFile legacy2 = legacy; ConfigFile config2 = config; base..ctor(); this.warn = warn; negativeSkills = config2.Bind<bool>("1 - Skill Caps", "Enable Negative Skills", true, "Allow skill levels and penalties below zero. False applies a zero floor to all skills, including per-skill overrides."); minimum = Number(config2, "1 - Skill Caps", "Minimum Negative Skill Level", -100f, -500f, 0f, "Lowest trainable level. Set 0 to disable negative levels."); maximum = Number(config2, "1 - Skill Caps", "Maximum Positive Skill Level", 200f, 1f, 500f, "Highest trainable level."); overrides = config2.Bind<string>("1 - Skill Caps", "Skill Cap Overrides", "", "Optional Name=minimum,maximum or numeric ID=minimum,maximum entries separated by semicolons. Use IDs for custom skills such as Leadership."); vanillaLoss = config2.Bind<bool>("3 - Death", "Use Vanilla Skill Loss", false, "Use Valheim's unmodified world death penalty. Custom curves and skill grace apply when false."); graceMinutes = config2.Bind<int>("3 - Death", "Skill Level Grace Cooldown Minutes", 60, new ConfigDescription("Real-time cooldown per skill after grace prevents a whole level from being lost. 0 disables grace.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1440), Array.Empty<object>())); crossZero = config2.Bind<bool>("3 - Death", "Death Can Cross Zero", ReadLegacy<bool>("2 - Skill Loss", "Death Can Cross Zero", fallback: true), "Let death reduce a nonnegative skill below zero."); protectZero = config2.Bind<bool>("3 - Death", "Protect Zero Skills On Death", false, "Preserve the level and XP of existing skills at raw level 0 up to, but excluding, 1."); zeroBand = Number(config2, "3 - Death", "Zero Crossing Band", ReadLegacy<float>("2 - Skill Loss", "Zero Crossing Band", 1f), 0f, 25f, "At or below this nonnegative