Decompiled source of CaveCrawlersLeveling v2.2.1
BepInEx/plugins/CaveCrawlersTweaks/CaveCrawlersTweaks.dll
Decompiled a month 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Json; using BepInEx; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Microsoft.CodeAnalysis; using Photon.Pun; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("CaveCrawlersTweaks")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("Cave Crawlers Leveling")] [assembly: AssemblyTitle("CaveCrawlersTweaks")] [assembly: AssemblyVersion("2.2.1.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace CaveCrawlersTweaks { [BepInPlugin("pedro.cavecrawlers.tweaks", "Cave Crawlers Leveling", "2.2.1")] public class Plugin : BasePlugin { public override void Load() { ((BasePlugin)this).Log.LogInfo((object)"Cave Crawlers Leveling loaded."); SoloLevelingPersistence.Initialize(((BasePlugin)this).Log); AttributeBonusSession.Initialize(((BasePlugin)this).Log); ((BasePlugin)this).AddComponent<StatsController>(); SoloLevelingXpObserver.Install(((BasePlugin)this).Log); } public override bool Unload() { SoloLevelingPersistence.Flush(); return false; } } public class StatsController : MonoBehaviour { private int controllerId; public StatsController(IntPtr pointer) : base(pointer) { } public void Start() { controllerId = ((Object)this).GetInstanceID(); AttributeBonusSession.Attach(controllerId); SoloLevelingTheme.Attach(controllerId); } public void Update() { SoloLevelingPersistence.Tick(); AttributeBonusSession.Tick(Time.frameCount); SoloLevelingStatusMenu.Tick(controllerId); SoloLevelingMenuInput.Refresh(controllerId); } public void LateUpdate() { SoloLevelingMenuInput.Refresh(controllerId); } public void OnDisable() { SoloLevelingMenuInput.Detach(controllerId); } public void OnGUI() { SoloLevelingProfileMenu.Draw(controllerId); SoloLevelingXpHud.Draw(controllerId); SoloLevelingStatusMenu.Draw(controllerId); } public void OnApplicationQuit() { SoloLevelingPersistence.Shutdown(); SoloLevelingTheme.Release(); } public void OnApplicationPause(bool paused) { if (paused) { SoloLevelingPersistence.Flush(); } } public void OnDestroy() { if (controllerId != 0) { SoloLevelingPersistence.Flush(); SoloLevelingStatusMenu.Detach(controllerId); SoloLevelingMenuInput.Detach(controllerId); AttributeBonusSession.Detach(controllerId); SoloLevelingTheme.Detach(controllerId); } } } internal static class SoloLevelingUiText { internal const string ProfileTitle = "SYSTEM / PROFILE SELECTION"; internal const string CompactProfileTitle = "SYSTEM / PROFILES"; internal const string PlayerStatusTitle = "SYSTEM / PLAYER STATUS"; internal static readonly IReadOnlyDictionary<string, string> StatNames = new Dictionary<string, string>(StringComparer.Ordinal) { ["ExtraDamage"] = "Extra Damage", ["DamageMultiplier"] = "Damage Multiplier", ["CriticalChance"] = "Critical Chance", ["CriticalDamage"] = "Critical Damage", ["AttackSpeed"] = "Attack Speed", ["WeaponRange"] = "Weapon Range", ["Knockback"] = "Knockback", ["DodgeChance"] = "Dodge Chance", ["BlockChance"] = "Block Chance", ["MoveSpeed"] = "Move Speed", ["SpellHaste"] = "Spell Haste", ["MaxTorchDuration"] = "Max Torch Duration", ["Dexterity"] = "Dexterity" }; private static readonly IReadOnlyDictionary<string, string> Descriptions = new Dictionary<string, string>(StringComparer.Ordinal) { ["ExtraDamage"] = "Adds flat weapon damage.", ["DamageMultiplier"] = "Increases the weapon damage multiplier.", ["CriticalChance"] = "Increases the chance of a critical hit.", ["CriticalDamage"] = "Increases damage dealt by critical hits.", ["AttackSpeed"] = "Increases melee swing speed.", ["WeaponRange"] = "Extends melee weapon reach.", ["Knockback"] = "Increases how far enemies are knocked back.", ["DodgeChance"] = "Increases the chance to dodge an incoming attack.", ["BlockChance"] = "Increases the chance to block an incoming attack.", ["MoveSpeed"] = "Increases normal movement speed.", ["SpellHaste"] = "Reduces spell cooldowns, within native limits.", ["MaxTorchDuration"] = "Extends your held torch's maximum duration.", ["Dexterity"] = "Increases movement speed while attacking or reloading." }; internal const string DexterityDescription = "pp; movement while attacking/reloading; native range -100 to +100"; internal static string Description(string id) { if (!Descriptions.TryGetValue(id, out string value)) { return Stat(id); } return value; } internal static string Stat(string id) { if (!StatNames.TryGetValue(id, out string value)) { return id; } return value; } internal static string Number(double value) { return value.ToString("0.##", CultureInfo.InvariantCulture); } } internal static class SoloLevelingTheme { internal readonly struct PaintScope : IDisposable { private readonly Color color; private readonly Color background; private readonly Color content; internal PaintScope(bool initialize) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_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_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) color = GUI.color; background = GUI.backgroundColor; content = GUI.contentColor; GUI.color = (GUI.backgroundColor = (GUI.contentColor = new Color(1f, 1f, 1f, 1f))); try { if (initialize) { Ensure(); } } catch { Dispose(); throw; } } public void Dispose() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) GUI.color = color; GUI.backgroundColor = background; GUI.contentColor = content; } } internal static readonly Color Background = new Color(0.027f, 0.071f, 0.145f, 0.94f); internal static readonly Color Secondary = new Color(0.063f, 0.137f, 0.263f, 0.9f); internal static readonly Color Blue = new Color(0.212f, 0.725f, 1f, 1f); internal static readonly Color Cyan = new Color(0.471f, 0.89f, 1f, 1f); internal static readonly Color Purple = new Color(0.525f, 0.345f, 1f, 1f); internal static readonly Color Text = new Color(0.918f, 0.969f, 1f, 1f); internal static readonly Color Gold = new Color(0.953f, 0.792f, 0.439f, 1f); internal static readonly Color Danger = new Color(1f, 0.55f, 0.61f, 1f); private static readonly List<Texture2D> owned = new List<Texture2D>(); private static readonly HashSet<int> controllers = new HashSet<int>(); private static GUIStyle? body; private static GUIStyle? small; private static GUIStyle? title; private static GUIStyle? gold; private static GUIStyle? button; private static GUIStyle? field; private static Texture2D? gradient; private static Texture2D? white; internal static int ResourceCount => owned.Count; internal static void Attach(int id) { controllers.Add(id); } internal static void Detach(int id) { controllers.Remove(id); if (controllers.Count == 0) { Release(); } } internal static void Release() { foreach (Texture2D item in owned) { if ((Object)(object)item != (Object)null && Object.op_Implicit((Object)(object)item)) { Object.Destroy((Object)(object)item); } } owned.Clear(); gradient = null; body = (small = (title = (gold = (button = (field = null))))); } internal static PaintScope Paint() { return new PaintScope(initialize: true); } private static void Ensure() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Expected O, but got Unknown //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Expected O, but got Unknown //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Expected O, but got Unknown //IL_01f5: Expected O, but got Unknown //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0267: 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_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029f: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Expected O, but got Unknown //IL_02b3: Expected O, but got Unknown //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) if (body != null) { return; } try { white = Texture2D.whiteTexture; GUISkin skin = GUI.skin; Texture2D background = Pixel(Secondary); Texture2D background2 = Pixel(new Color(0.08f, 0.27f, 0.43f, 1f)); Texture2D background3 = Pixel(new Color(0.23f, 0.19f, 0.48f, 1f)); gradient = new Texture2D(128, 1, (TextureFormat)4, false); owned.Add(gradient); ((Object)gradient).hideFlags = (HideFlags)61; ((Texture)gradient).wrapMode = (TextureWrapMode)1; ((Texture)gradient).filterMode = (FilterMode)1; for (int i = 0; i < 128; i++) { gradient.SetPixel(i, 0, Color.Lerp(Blue, Purple, (float)i / 127f)); } gradient.Apply(false, true); body = new GUIStyle(skin.label) { fontSize = 14, wordWrap = false, richText = false, clipping = (TextClipping)1 }; body.normal.textColor = Text; small = new GUIStyle(body) { fontSize = 12, wordWrap = true }; small.normal.textColor = Cyan; title = new GUIStyle(body) { fontSize = 17, fontStyle = (FontStyle)1 }; title.normal.textColor = Cyan; gold = new GUIStyle(body) { fontStyle = (FontStyle)1 }; gold.normal.textColor = Gold; button = new GUIStyle(skin.button) { fontSize = 13, richText = false, wordWrap = false, alignment = (TextAnchor)4, padding = new RectOffset(5, 5, 2, 2) }; button.normal.background = background; button.hover.background = background2; button.active.background = background3; button.focused.background = background2; button.normal.textColor = Text; button.hover.textColor = Cyan; button.active.textColor = Gold; button.focused.textColor = Cyan; field = new GUIStyle(skin.textField) { fontSize = 14, richText = false, padding = new RectOffset(7, 7, 4, 4) }; field.normal.background = background; field.hover.background = background2; field.focused.background = background3; GUIStyleState normal = field.normal; GUIStyleState hover = field.hover; Color val = (field.focused.textColor = Text); Color textColor = (hover.textColor = val); normal.textColor = textColor; } catch { Release(); throw; } } private static Texture2D Pixel(Color color) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(1, 1, (TextureFormat)4, false); owned.Add(val); ((Object)val).hideFlags = (HideFlags)61; val.SetPixel(0, 0, color); val.Apply(false, true); return val; } internal static void Solid(Rect rect, Color color) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (((Rect)(ref rect)).width <= 0f || ((Rect)(ref rect)).height <= 0f || (int)Event.current.type != 7) { return; } Color color2 = GUI.color; try { GUI.color = color; GUI.DrawTexture(rect, (Texture)(object)white); } finally { GUI.color = color2; } } internal static void Border(Rect r, Color color, float thickness = 1f) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) Solid(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, ((Rect)(ref r)).width, thickness), color); Solid(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y + ((Rect)(ref r)).height - thickness, ((Rect)(ref r)).width, thickness), color); Solid(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, thickness, ((Rect)(ref r)).height), color); Solid(new Rect(((Rect)(ref r)).x + ((Rect)(ref r)).width - thickness, ((Rect)(ref r)).y, thickness, ((Rect)(ref r)).height), color); } internal static void Panel(Rect r) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) Solid(new Rect(((Rect)(ref r)).x + 4f, ((Rect)(ref r)).y + 5f, ((Rect)(ref r)).width, ((Rect)(ref r)).height), new Color(0f, 0f, 0f, 0.25f)); Solid(r, Background); Border(new Rect(((Rect)(ref r)).x - 2f, ((Rect)(ref r)).y - 2f, ((Rect)(ref r)).width + 4f, ((Rect)(ref r)).height + 4f), new Color(Blue.r, Blue.g, Blue.b, 0.14f), 3f); Border(r, Blue); Solid(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, Math.Min(46f, ((Rect)(ref r)).width / 5f), 3f), Cyan); Solid(new Rect(((Rect)(ref r)).x + ((Rect)(ref r)).width - 46f, ((Rect)(ref r)).y + ((Rect)(ref r)).height - 3f, 46f, 3f), Purple); } internal static void Card(Rect r, bool selected = false) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) Solid(r, (Color)(selected ? new Color(0.08f, 0.23f, 0.36f, 0.95f) : Secondary)); Border(r, (Color)(selected ? Cyan : new Color(Blue.r, Blue.g, Blue.b, 0.35f))); Solid(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y + 4f, 2f, ((Rect)(ref r)).height - 8f), selected ? Gold : Blue); } internal static void Label(Rect rect, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) GUI.Label(rect, text, body); } internal static void Small(Rect rect, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) GUI.Label(rect, text, small); } internal static void Title(Rect rect, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) GUI.Label(rect, text, title); } internal static void Points(Rect rect, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) GUI.Label(rect, text, gold); } internal static void Divider(float x, float y, float width) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) Solid(new Rect(x, y, width, 1f), new Color(Blue.r, Blue.g, Blue.b, 0.45f)); } internal static bool Button(Rect rect, string text, bool destructive = false) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) bool flag = GUI.enabled && ((Rect)(ref rect)).Contains(Event.current.mousePosition); Border(new Rect(((Rect)(ref rect)).x - 1f, ((Rect)(ref rect)).y - 1f, ((Rect)(ref rect)).width + 2f, ((Rect)(ref rect)).height + 2f), (Color)((!GUI.enabled) ? new Color(0.2f, 0.3f, 0.4f, 0.5f) : (destructive ? Danger : (flag ? Cyan : Blue)))); return GUI.Button(rect, text, button); } internal static string TextField(Rect rect, string value, int maxLength) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) Border(new Rect(((Rect)(ref rect)).x - 1f, ((Rect)(ref rect)).y - 1f, ((Rect)(ref rect)).width + 2f, ((Rect)(ref rect)).height + 2f), Cyan); return GUI.TextField(rect, value, maxLength, field); } internal static void Progress(Rect rect, double current, double required) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Invalid comparison between Unknown and I4 //IL_0085: Unknown result type (might be due to invalid IL or missing references) double num = ((double.IsFinite(current) && double.IsFinite(required) && required > 0.0) ? Math.Clamp(current / required, 0.0, 1.0) : 0.0); Solid(rect, Secondary); if (num > 0.0 && (int)Event.current.type == 7) { GUI.DrawTexture(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * (float)num, ((Rect)(ref rect)).height), (Texture)(object)gradient); } Border(new Rect(((Rect)(ref rect)).x - 1f, ((Rect)(ref rect)).y - 1f, ((Rect)(ref rect)).width + 2f, ((Rect)(ref rect)).height + 2f), new Color(Blue.r, Blue.g, Blue.b, 0.5f)); } internal static string Fit(string text, float width, float characterWidth = 7.6f) { int num = Math.Max(1, (int)(width / characterWidth)); if (text.Length > num) { return text.Substring(0, Math.Max(0, num - 1)) + "…"; } return text; } internal static void Tooltip(string text) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type == 7 && !string.IsNullOrEmpty(text)) { float num = Math.Min(390, Screen.width - 28); float num2 = Math.Min(150f, 26f + 17f * MathF.Ceiling((float)text.Length / Math.Max(1f, num / 7f))); Vector2 mousePosition = Event.current.mousePosition; Rect r = default(Rect); ((Rect)(ref r))..ctor(Math.Clamp(mousePosition.x + 16f, 8f, Math.Max(8f, (float)Screen.width - num - 8f)), Math.Clamp(mousePosition.y + 20f, 8f, Math.Max(8f, (float)Screen.height - num2 - 8f)), num, num2); Panel(r); Small(new Rect(((Rect)(ref r)).x + 10f, ((Rect)(ref r)).y + 8f, ((Rect)(ref r)).width - 20f, ((Rect)(ref r)).height - 16f), text); } } } internal readonly record struct SoloLevelingMenuLayout(Rect Panel, int Rows, float RowY, float RowHeight, bool Compact) { internal static SoloLevelingMenuLayout Status(int width, int height) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) float num = Math.Min(760, Math.Max(120, width - 24)); float num2 = Math.Min(680, Math.Max(160, height - 24)); bool flag = num2 < 400f; float num3 = (flag ? 112 : 172); float num4 = (flag ? 64 : 78); int num5 = Math.Clamp((int)((num2 - num3 - num4) / (float)(flag ? 44 : 64)), 1, 6); float rowHeight = Math.Max(30f, Math.Min(flag ? 48 : 64, (num2 - num3 - num4) / (float)num5)); return new SoloLevelingMenuLayout(new Rect(12f, 12f, num, num2), num5, 12f + num3, rowHeight, flag); } internal static Rect Profiles(int width, int height) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) return new Rect(Math.Max(12f, (float)(width - 720) / 2f), Math.Max(12f, (float)(height - 720) / 2f), (float)Math.Min(720, Math.Max(120, width - 24)), (float)Math.Min(720, Math.Max(160, height - 24))); } } internal static class SoloLevelingMenuInput { private static bool ownsCursor; private static Player? lookPlayer; private static PlayerIdentity? lookIdentity; internal static void Refresh(int controllerId) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (!AttributeBonusSession.IsPrimaryController(controllerId)) { return; } try { if (SoloLevelingProfileMenu.IsBlocking || SoloLevelingStatusMenu.IsOpen) { ownsCursor = true; Player val = Local(); if (!Same(val, lookIdentity)) { ReleaseLook(); } if ((Object)(object)val != (Object)null && !lookIdentity.HasValue) { if (PositiveInt.op_Implicit(val.NonLookInt) == int.MaxValue) { throw new InvalidOperationException("Native look gate is full."); } val.NonLookInt += 1; lookPlayer = val; lookIdentity = new PlayerIdentity(((Il2CppObjectBase)val).Pointer, ((Object)val).GetInstanceID()); } Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; } else { Release(); } } catch (Exception ex) { AttributeBonusSession.LogMenuException("Menu cursor/look ownership", ex.ToString()); } } internal static void Detach(int controllerId) { if (!AttributeBonusSession.IsPrimaryController(controllerId)) { return; } try { Release(); } catch (Exception ex) { AttributeBonusSession.LogMenuException("Menu input teardown", ex.ToString()); } } private static void Release() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) ReleaseLook(); if (ownsCursor) { bool flag = true; try { Player val = Local(); GameManagerCC instance = Singleton<GameManagerCC>.Instance; GUIManager instance2 = Singleton<GUIManager>.Instance; flag = !Application.isFocused || !Alive((Object?)(object)instance) || instance.GameOver || instance.LeavingGame || (Object)(object)val == (Object)null || PositiveInt.op_Implicit(val.NonLookInt) > 0 || InputManager.CursorShown || (Alive((Object?)(object)instance2) && instance2.IsInventoryOpen); } catch { } Cursor.lockState = (CursorLockMode)(!flag); Cursor.visible = flag; ownsCursor = false; } } private static void ReleaseLook() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (lookIdentity.HasValue) { if (Same(lookPlayer, lookIdentity) && Alive((Object?)(object)((Entity)lookPlayer).view) && ((Entity)lookPlayer).view.IsMine) { Player? obj = lookPlayer; obj.NonLookInt -= 1; } lookPlayer = null; lookIdentity = null; } } private static Player? Local() { GUIManager instance = Singleton<GUIManager>.Instance; if (!Alive((Object?)(object)instance)) { return null; } Player client = instance.GetClient(false); if (!Alive((Object?)(object)client) || !((Behaviour)client).isActiveAndEnabled || client.isCharacter || ((Entity)client).IsDead || !Alive((Object?)(object)((Entity)client).view) || !((Entity)client).view.IsMine) { return null; } return client; } private static bool Same(Player? player, PlayerIdentity? identity) { if (identity.HasValue) { PlayerIdentity valueOrDefault = identity.GetValueOrDefault(); if (Alive((Object?)(object)player) && ((Il2CppObjectBase)player).Pointer == valueOrDefault.Pointer) { return ((Object)player).GetInstanceID() == valueOrDefault.InstanceId; } } return false; } private static bool Alive(Object? value) { if (value != null && ((Il2CppObjectBase)value).Pointer != IntPtr.Zero) { return Object.op_Implicit(value); } return false; } } internal static class SoloLevelingHudObstacles { private static Il2CppStructArray<Vector3>? corners; private static bool warned; internal static SoloLevelingHudObstacle? HealthBar(GUIManager? gui, int screenHeight) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) try { if (gui == null || ((Il2CppObjectBase)gui).Pointer == IntPtr.Zero || !Object.op_Implicit((Object)(object)gui)) { return null; } Canvas myCanvas = gui.myCanvas; if (myCanvas == null || ((Il2CppObjectBase)myCanvas).Pointer == IntPtr.Zero || !Object.op_Implicit((Object)(object)myCanvas) || (int)myCanvas.renderMode != 0) { return null; } PlayerHealthBar healthBar = gui.HealthBar; if (healthBar == null || ((Il2CppObjectBase)healthBar).Pointer == IntPtr.Zero || !Object.op_Implicit((Object)(object)healthBar) || !((Behaviour)healthBar).isActiveAndEnabled) { return null; } RectTransform val = ((Il2CppObjectBase)((Component)healthBar).transform).TryCast<RectTransform>(); if (val == null || ((Il2CppObjectBase)val).Pointer == IntPtr.Zero || !Object.op_Implicit((Object)(object)val)) { return null; } if (corners == null) { corners = new Il2CppStructArray<Vector3>(4L); } val.GetWorldCorners(corners); float num = float.PositiveInfinity; float num2 = float.NegativeInfinity; float num3 = float.PositiveInfinity; float num4 = float.NegativeInfinity; for (int i = 0; i < 4; i++) { Vector3 val2 = ((Il2CppArrayBase<Vector3>)(object)corners)[i]; if (!float.IsFinite(val2.x) || !float.IsFinite(val2.y)) { return null; } num = Math.Min(num, val2.x); num2 = Math.Max(num2, val2.x); num3 = Math.Min(num3, val2.y); num4 = Math.Max(num4, val2.y); } return new SoloLevelingHudObstacle(num, (float)screenHeight - num4, num2 - num, num4 - num3); } catch (Exception ex) { if (!warned) { warned = true; AttributeBonusSession.LogHudException("Optional health-bar bounds; using corner layout", ex.ToString()); } return null; } } } internal static class SoloLevelingStatRules { internal static readonly IReadOnlyDictionary<string, float> Steps = new Dictionary<string, float>(StringComparer.Ordinal) { ["ExtraDamage"] = 0.2f, ["DamageMultiplier"] = 5f, ["CriticalChance"] = 1f, ["CriticalDamage"] = 5f, ["AttackSpeed"] = 1f, ["WeaponRange"] = 0.1f, ["Knockback"] = 1f, ["DodgeChance"] = 1f, ["BlockChance"] = 1f, ["MoveSpeed"] = 5f, ["SpellHaste"] = 1f, ["MaxTorchDuration"] = 5f, ["Dexterity"] = 1f }; } internal sealed class SoloLevelingSaveDocument { public int SchemaVersion { get; set; } = 3; public string ProfileScope { get; set; } = "ExplicitAccountProfiles"; internal int SourceSchemaVersion { get; set; } = 3; public Dictionary<string, SoloLevelingSaveProfile> Profiles { get; set; } = new Dictionary<string, SoloLevelingSaveProfile>(StringComparer.Ordinal); } internal sealed class SoloLevelingSaveProfile { public string AccountKey { get; set; } = ""; public string ProfileId { get; set; } = Guid.NewGuid().ToString("D"); public string Name { get; set; } = "Hunter Profile"; public bool IsLegacy { get; set; } public int Level { get; set; } = 1; public double Xp { get; set; } public long FreePoints { get; set; } public Dictionary<string, long> Investments { get; set; } = new Dictionary<string, long>(StringComparer.Ordinal); public Dictionary<string, long> RetiredInvestments { get; set; } = new Dictionary<string, long>(StringComparer.Ordinal); internal ProgressionSnapshot Snapshot => new ProgressionSnapshot(Level, Xp, SoloLevelingSaveCodec.RequiredXp(Level), FreePoints); internal SoloLevelingSaveProfile Copy() { return new SoloLevelingSaveProfile { AccountKey = AccountKey, ProfileId = ProfileId, Name = Name, IsLegacy = IsLegacy, Level = Level, Xp = Xp, FreePoints = FreePoints, Investments = new Dictionary<string, long>(Investments, StringComparer.Ordinal), RetiredInvestments = new Dictionary<string, long>(RetiredInvestments, StringComparer.Ordinal) }; } } internal static class SoloLevelingSaveCodec { private sealed class LegacyDocument { public int SchemaVersion { get; set; } public string ProfileScope { get; set; } = ""; public Dictionary<string, SoloLevelingSaveProfile> Profiles { get; set; } = new Dictionary<string, SoloLevelingSaveProfile>(StringComparer.Ordinal); } internal const int MaxBytes = 1048576; private static readonly JsonSerializerOptions Options = new JsonSerializerOptions { WriteIndented = true, MaxDepth = 12 }; internal static string ProfileKey(ulong account) { return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("CaveCrawlersTweaks/SoloLeveling/account/v1:" + account.ToString(CultureInfo.InvariantCulture)))); } internal static string ProfileKey(string accountKey, string profileId) { return accountKey + ":" + profileId.ToLowerInvariant(); } internal static double RequiredXp(int level) { return SoloLevelingXpCurve.Required(level); } internal static void Validate(SoloLevelingSaveProfile profile) { ValidateProfile(profile, legacyDexterity: false); } private static void ValidateProfile(SoloLevelingSaveProfile profile, bool legacyDexterity) { if (profile == null || !IsHash(profile.AccountKey) || !Guid.TryParseExact(profile.ProfileId, "D", out var _) || string.IsNullOrWhiteSpace(profile.Name) || profile.Name.Length > 32 || profile.Name.Any(char.IsControl) || !SoloLevelingXpCurve.ValidSavedXp(profile.Level, profile.Xp) || profile.FreePoints < 0 || profile.Investments == null || profile.RetiredInvestments == null) { throw new InvalidDataException("Invalid profile metadata or progression values."); } checked { long earned = (unchecked((long)profile.Level) - 1L) * 5; long num = 0L; foreach (KeyValuePair<string, long> investment in profile.Investments) { if ((!SoloLevelingStatRules.Steps.ContainsKey(investment.Key) && (!legacyDexterity || !(investment.Key == "Dexterity"))) || investment.Value < 0 || investment.Value > earned) { throw new InvalidDataException("Invalid or unsupported investment."); } num += investment.Value; if (investment.Key == "Dexterity" && !legacyDexterity && investment.Value > 100) { throw new InvalidDataException("Permanent Dexterity exceeds the native +100 limit."); } } if (profile.RetiredInvestments.Any<KeyValuePair<string, long>>((KeyValuePair<string, long> p) => p.Key != "Dexterity" || p.Value < 0 || p.Value > earned) || profile.FreePoints + num != earned) { throw new InvalidDataException("Point budget or retired-investment audit is invalid."); } } } internal static void Validate(SoloLevelingSaveDocument document) { if (document == null || document.SchemaVersion != 3 || document.ProfileScope != "ExplicitAccountProfiles" || document.Profiles == null || document.Profiles.Count > 512) { throw new InvalidDataException("Unsupported schema or profile count."); } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, SoloLevelingSaveProfile> profile in document.Profiles) { Validate(profile.Value); if (profile.Key != ProfileKey(profile.Value.AccountKey, profile.Value.ProfileId) || !hashSet.Add(profile.Key)) { throw new InvalidDataException("Profile key does not match account and UUID."); } } } internal static byte[] Encode(SoloLevelingSaveDocument document) { Validate(document); byte[] array = JsonSerializer.SerializeToUtf8Bytes(document, Options); if (array.Length > 1048576) { throw new InvalidDataException("Save too large."); } return array; } internal static SoloLevelingSaveDocument Decode(byte[] bytes) { if (bytes.Length > 1048576) { throw new InvalidDataException("Save too large."); } checked { using JsonDocument jsonDocument = JsonDocument.Parse((ReadOnlyMemory<byte>)bytes, new JsonDocumentOptions { MaxDepth = 12 }); int @int = jsonDocument.RootElement.GetProperty("SchemaVersion").GetInt32(); if ((@int < 1 || @int > 3) ? true : false) { throw new InvalidDataException("Unsupported schema."); } switch (@int) { case 1: ExactProperties(jsonDocument.RootElement, "SchemaVersion", "Profiles"); break; case 2: ExactProperties(jsonDocument.RootElement, "SchemaVersion", "ProfileScope", "Profiles"); break; default: ExactProperties(jsonDocument.RootElement, "SchemaVersion", "ProfileScope", "Profiles"); break; } JsonElement property = jsonDocument.RootElement.GetProperty("Profiles"); ExactProperties(property, (from p in property.EnumerateObject() select p.Name).ToArray()); foreach (JsonProperty item in property.EnumerateObject()) { switch (@int) { case 1: ExactProperties(item.Value, "Level", "Xp", "FreePoints", "Investments"); break; case 2: ExactProperties(item.Value, "Level", "Xp", "FreePoints", "Investments", "RetiredInvestments"); ExactProperties(item.Value.GetProperty("RetiredInvestments"), (from p in item.Value.GetProperty("RetiredInvestments").EnumerateObject() select p.Name).ToArray()); break; default: ExactProperties(item.Value, "AccountKey", "ProfileId", "Name", "IsLegacy", "Level", "Xp", "FreePoints", "Investments", "RetiredInvestments"); ExactProperties(item.Value.GetProperty("Investments"), (from p in item.Value.GetProperty("Investments").EnumerateObject() select p.Name).ToArray()); ExactProperties(item.Value.GetProperty("RetiredInvestments"), (from p in item.Value.GetProperty("RetiredInvestments").EnumerateObject() select p.Name).ToArray()); break; } ExactProperties(item.Value.GetProperty("Investments"), (from p in item.Value.GetProperty("Investments").EnumerateObject() select p.Name).ToArray()); } if (@int == 3) { SoloLevelingSaveDocument? obj = JsonSerializer.Deserialize<SoloLevelingSaveDocument>(bytes, Options) ?? throw new InvalidDataException("Empty save."); obj.SourceSchemaVersion = 3; Validate(obj); return obj; } LegacyDocument legacyDocument = JsonSerializer.Deserialize<LegacyDocument>(bytes, Options) ?? throw new InvalidDataException("Empty legacy save."); if (legacyDocument.Profiles == null || legacyDocument.Profiles.Count > 64 || (@int == 2 && legacyDocument.ProfileScope != "Account")) { throw new InvalidDataException("Invalid legacy account save."); } SoloLevelingSaveDocument soloLevelingSaveDocument = new SoloLevelingSaveDocument { SourceSchemaVersion = @int }; foreach (KeyValuePair<string, SoloLevelingSaveProfile> profile in legacyDocument.Profiles) { if (!IsHash(profile.Key)) { throw new InvalidDataException("Legacy account key is invalid."); } SoloLevelingSaveProfile value = profile.Value; if (value == null) { throw new InvalidDataException("Legacy profile is null."); } if (@int == 1) { value.AccountKey = profile.Key; value.ProfileId = Guid.NewGuid().ToString("D"); value.Name = "Legacy Profile"; value.IsLegacy = true; value.RetiredInvestments = new Dictionary<string, long>(StringComparer.Ordinal); ValidateProfile(value, legacyDexterity: true); if (value.Investments.Remove("Dexterity", out var value2) && value2 > 0) { value.FreePoints += value2; value.RetiredInvestments["Dexterity"] = value2; } } else { value.AccountKey = profile.Key; value.ProfileId = Guid.NewGuid().ToString("D"); value.Name = "Legacy Profile"; value.IsLegacy = true; ValidateProfile(value, legacyDexterity: false); } soloLevelingSaveDocument.Profiles.Add(ProfileKey(profile.Key, value.ProfileId), value); } Validate(soloLevelingSaveDocument); return soloLevelingSaveDocument; } } private static bool IsHash(string value) { if (value.Length == 64) { return value.All(Uri.IsHexDigit); } return false; } private static void ExactProperties(JsonElement element, params string[] expected) { if (element.ValueKind != JsonValueKind.Object) { throw new InvalidDataException("Expected object."); } HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); foreach (JsonProperty item in element.EnumerateObject()) { if (!hashSet.Add(item.Name) || !expected.Contains<string>(item.Name, StringComparer.Ordinal)) { throw new InvalidDataException("Duplicate or unknown field."); } } if (hashSet.Count != expected.Length) { throw new InvalidDataException("Missing field."); } } } internal sealed class SoloLevelingSaveRepository : IDisposable { private readonly string primary; private string target; private byte[]? expectedDigest; private byte[]? legacyBytes; private readonly FileStream lease; private readonly Action<string> warn; internal SoloLevelingSaveDocument Document { get; private set; } = new SoloLevelingSaveDocument(); internal bool RecoveryMode { get; private set; } internal SoloLevelingSaveRepository(string path, Action<string> warn) { primary = Path.GetFullPath(path); target = primary; this.warn = warn; Directory.CreateDirectory(Path.GetDirectoryName(primary)); lease = new FileStream(primary + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); try { Load(); } catch { lease.Dispose(); throw; } } private static byte[] ReadBounded(string path) { using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length > 1048576) { throw new InvalidDataException("Save too large."); } using MemoryStream memoryStream = new MemoryStream(); byte[] array = new byte[4096]; int num; while ((num = fileStream.Read(array, 0, array.Length)) > 0) { if (memoryStream.Length + num > 1048576) { throw new InvalidDataException("Save too large."); } memoryStream.Write(array, 0, num); } return memoryStream.ToArray(); } internal static SoloLevelingSaveDocument ReadOnlySnapshot(string path) { string[] array = new string[3] { path, path + ".recovered.json", path + ".bak" }; foreach (string path2 in array) { try { return SoloLevelingSaveCodec.Decode(ReadBounded(path2)); } catch { } } return new SoloLevelingSaveDocument(); } private bool TryRead(string path, out SoloLevelingSaveDocument document, out byte[]? digest) { document = new SoloLevelingSaveDocument(); digest = null; try { byte[] array = ReadBounded(path); document = SoloLevelingSaveCodec.Decode(array); if (document.SourceSchemaVersion < 3) { legacyBytes = array; } digest = SHA256.HashData(array); return true; } catch (FileNotFoundException) { return false; } catch (Exception ex2) { warn("Save indisponível/inválido; conteúdo preservado. Tipo=" + ex2.GetType().Name); return false; } } private void Load() { bool flag; try { File.GetAttributes(primary); flag = true; } catch (FileNotFoundException) { flag = false; } if (flag && TryRead(primary, out SoloLevelingSaveDocument document, out byte[] digest)) { Document = document; expectedDigest = digest; return; } byte[] digest2; if (!flag) { if (TryRead(primary + ".bak", out SoloLevelingSaveDocument document2, out digest2)) { Document = document2; } return; } RecoveryMode = true; target = primary + ".recovered.json"; if (TryRead(target, out SoloLevelingSaveDocument document3, out byte[] digest3)) { Document = document3; expectedDigest = digest3; } else { if (File.Exists(target)) { throw new InvalidDataException("Recovery target invalid; persistence disabled."); } if (TryRead(primary + ".bak", out SoloLevelingSaveDocument document4, out digest2)) { Document = document4; } } warn("Modo de recuperação: original preservado; novas gravações usam SoloLeveling.json.recovered.json."); } internal void Save() { byte[] array = SoloLevelingSaveCodec.Encode(Document); string text = target + ".tmp-" + Guid.NewGuid().ToString("N"); try { using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { fileStream.Write(array, 0, array.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(target)) { byte[] array2 = ReadBounded(target); if (expectedDigest == null || !SHA256.HashData(array2).SequenceEqual(expectedDigest)) { throw new IOException("Save changed externally; refusing overwrite."); } SoloLevelingSaveCodec.Decode(array2); PreserveLegacyBackup(); File.Replace(text, target, target + ".bak"); } else { if (expectedDigest != null) { throw new IOException("Save removed externally; refusing recreation."); } PreserveLegacyBackup(); File.Move(text, target); } expectedDigest = SHA256.HashData(array); Document.SourceSchemaVersion = 3; legacyBytes = null; } finally { try { if (File.Exists(text)) { File.Delete(text); } } catch { } } } internal string CreateVerifiedProfileDeletionBackup() { byte[] array = SoloLevelingSaveCodec.Encode(Document); string text = Convert.ToHexString(SHA256.HashData(array)).Substring(0, 16); string text2 = target + ".pre-profile-delete-" + text + ".bak"; if (File.Exists(text2)) { if (!ReadBounded(text2).SequenceEqual(array)) { throw new IOException("Existing profile-deletion backup does not match the current save."); } } else { string text3 = text2 + ".tmp-" + Guid.NewGuid().ToString("N"); try { using (FileStream fileStream = new FileStream(text3, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { fileStream.Write(array, 0, array.Length); fileStream.Flush(flushToDisk: true); } File.Move(text3, text2); } finally { try { if (File.Exists(text3)) { File.Delete(text3); } } catch { } } } byte[] array2 = ReadBounded(text2); if (!array2.SequenceEqual(array)) { throw new IOException("Profile-deletion backup verification failed."); } SoloLevelingSaveCodec.Decode(array2); return text2; } internal void RefreshRecoveryBackupFromCommittedState() { byte[] array = ReadBounded(target); SoloLevelingSaveCodec.Decode(array); string text = target + ".bak"; string text2 = text + ".tmp-" + Guid.NewGuid().ToString("N"); try { using (FileStream fileStream = new FileStream(text2, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { fileStream.Write(array, 0, array.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(text)) { File.Replace(text2, text, null); } else { File.Move(text2, text); } byte[] array2 = ReadBounded(text); if (!array2.SequenceEqual(array)) { throw new IOException("Committed recovery backup verification failed."); } SoloLevelingSaveCodec.Decode(array2); } finally { try { if (File.Exists(text2)) { File.Delete(text2); } } catch { } } } private void PreserveLegacyBackup() { if (legacyBytes == null) { return; } string path = primary + ".schema-legacy-" + Convert.ToHexString(SHA256.HashData(legacyBytes)).Substring(0, 16) + ".bak"; if (File.Exists(path)) { if (!ReadBounded(path).SequenceEqual(legacyBytes)) { throw new IOException("Legacy backup mismatch; migration stopped."); } return; } using FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough); fileStream.Write(legacyBytes, 0, legacyBytes.Length); fileStream.Flush(flushToDisk: true); } public void Dispose() { lease.Dispose(); } } internal sealed class SoloLevelingSaveSchedule { private double firstDirty; private double lastChange; private double retryAt; internal bool Dirty { get; private set; } internal void Reset() { Dirty = false; firstDirty = (lastChange = (retryAt = 0.0)); } internal void Mark(double now) { if (!Dirty) { firstDirty = now; } Dirty = true; lastChange = now; } internal bool Flush(double now, Action save, bool immediate = false, bool shutdown = false) { if (!Dirty || (!shutdown && now < retryAt) || (!immediate && now - lastChange < 1.0 && now - firstDirty < 3.0)) { return false; } try { save(); Dirty = false; retryAt = 0.0; return true; } catch { retryAt = now + 15.0; throw; } } } internal sealed record SoloLevelingProfileInfo(string Id, string Name, bool IsLegacy, int Level); internal static class SoloLevelingPersistence { private static readonly object Gate = new object(); private static readonly SoloLevelingSaveSchedule Schedule = new SoloLevelingSaveSchedule(); private static readonly HashSet<string> Warnings = new HashSet<string>(); private static SoloLevelingSaveRepository? repository; private static ManualLogSource? log; private static SoloLevelingSaveDocument readOnlyDocument = new SoloLevelingSaveDocument(); private static string? accountKey; private static string? activeProfileKey; private static ProgressionSnapshot lastObserved; private static IntPtr savedRecordPointer; private static bool initialized; private static bool stopped; private static bool localPlayerReady; private static bool profileSafetyBlocked; private static bool lifecycleHooksReady; internal static bool StorageReady { get; private set; } internal static bool ProfileSelected => activeProfileKey != null; internal static bool ProgressionReady { get { if (StorageReady && lifecycleHooksReady && ProfileSelected && localPlayerReady && !stopped) { return !profileSafetyBlocked; } return false; } } internal static bool Ready => ProgressionReady; internal static bool NeedsProfileSelection { get { if ((localPlayerReady && !ProgressionReady) || profileSafetyBlocked) { return !stopped; } return false; } } internal static bool SafetyBlocked => profileSafetyBlocked; internal static bool CanSelectProfile { get { if (StorageReady && lifecycleHooksReady) { return !profileSafetyBlocked; } return false; } } private static double Now => (double)Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency; private static SoloLevelingSaveDocument Document => repository?.Document ?? readOnlyDocument; internal static string? ActiveProfileName { get { lock (Gate) { SoloLevelingSaveProfile value; return (activeProfileKey != null && Document.Profiles.TryGetValue(activeProfileKey, out value)) ? value.Name : null; } } } internal static string? ActiveProfileId { get { lock (Gate) { SoloLevelingSaveProfile value; return (activeProfileKey != null && Document.Profiles.TryGetValue(activeProfileKey, out value)) ? value.ProfileId : null; } } } internal static void Initialize(ManualLogSource logger) { lock (Gate) { if (initialized) { return; } initialized = true; log = logger; string path = Path.Combine(Paths.ConfigPath, "CaveCrawlersTweaks", "SoloLeveling.json"); try { repository = new SoloLevelingSaveRepository(path, Warn); if (repository.Document.SourceSchemaVersion < 3) { log.LogInfo((object)"[Cave Crawlers Leveling][Profiles] Legacy account progress is preserved as an unselected Legacy Profile. Migration commits only after an explicit profile action; no character ownership is inferred."); } log.LogInfo((object)"[Cave Crawlers Leveling][Profiles] Storage initialized; an explicit profile choice is required for each character session."); } catch (Exception ex) { readOnlyDocument = SoloLevelingSaveRepository.ReadOnlySnapshot(path); Warn("Storage unavailable; a validated copy may be used in memory, but changes cannot be guaranteed on disk. Type=" + ex.GetType().Name); } } } internal static void SetLifecycleHooksReady(bool ready) { lifecycleHooksReady = ready; if (!ready) { Warn("Automatic character-session hooks are incomplete; profile selection and progression remain locked to prevent profile reuse."); return; } ManualLogSource? obj = log; if (obj != null) { obj.LogInfo((object)"[Cave Crawlers Leveling][Profiles] Character selection and removal hooks are active; profiles will not be reused across observed character entries."); } } internal static bool EnsureForData(MainPlayerData? data) { return SoloLevelingXpObserver.Progression.Read(delegate { EnsureStorageForData(data); return ProgressionReady && AttributeBonusSession.HasReadyLocalPlayer(); }); } private static bool EnsureStorageForData(MainPlayerData? data) { lock (Gate) { if (!initialized || stopped) { return false; } try { MainPlayerData instance = MainPlayerData.Instance; if (data == null || ((Il2CppObjectBase)data).Pointer == IntPtr.Zero || instance == null || ((Il2CppObjectBase)instance).Pointer == IntPtr.Zero || ((Il2CppObjectBase)data).Pointer != ((Il2CppObjectBase)instance).Pointer || instance.SteamId == 0L) { return false; } string text = SoloLevelingSaveCodec.ProfileKey(instance.SteamId); if (accountKey != null && accountKey != text) { EndProfileLocked("local account changed", removeBonuses: true); accountKey = null; StorageReady = false; localPlayerReady = false; savedRecordPointer = IntPtr.Zero; Warn("Local account changed; explicit profile selection will be required again."); } if (accountKey == null) { accountKey = text; StorageReady = repository != null; SoloLevelingProfileMenu.ResetForNewCharacter(); } return ProgressionReady; } catch (Exception ex) { Warn("Storage/account validation failed; progression remains gated. Type=" + ex.GetType().Name); return false; } } } internal static void ObserveLocalPlayer(PlayerIdentity identity, IntPtr currentSavedRecord) { WithStateLock(delegate { lock (Gate) { if (!(currentSavedRecord == IntPtr.Zero)) { savedRecordPointer = currentSavedRecord; localPlayerReady = true; } } }); } internal static void MarkLocalPlayerPending() { lock (Gate) { localPlayerReady = false; } } internal static void EndCharacterSession(string reason) { WithStateLock(delegate { lock (Gate) { if (StorageReady && (activeProfileKey != null || localPlayerReady || !(savedRecordPointer == IntPtr.Zero))) { EndProfileLocked(reason, removeBonuses: true); savedRecordPointer = IntPtr.Zero; localPlayerReady = false; SoloLevelingProfileMenu.ResetForNewCharacter(); } } }); } internal static void BeforeLocalCharacterSelected(Player? player) { try { if (!((Object)(object)player == (Object)null) && !(((Il2CppObjectBase)player).Pointer == IntPtr.Zero) && !((Object)(object)((Entity)player).view == (Object)null) && ((Entity)player).view.IsMine) { EndCharacterSession("local character selection"); } } catch (Exception ex) { Warn("Character-selection lifecycle could not be inspected; profile remains gated on the next local record. Type=" + ex.GetType().Name); } } internal static void BeforeCharacterRecordDeleted(PlayerSaved? record) { try { if (record != null && !(((Il2CppObjectBase)record).Pointer == IntPtr.Zero)) { bool flag; lock (Gate) { flag = savedRecordPointer == ((Il2CppObjectBase)record).Pointer; } if (flag) { EndCharacterSession("active character death/deletion"); } } } catch (Exception ex) { Warn("Character-removal lifecycle could not be inspected. Type=" + ex.GetType().Name); } } private static void EndProfileLocked(string reason, bool removeBonuses) { if (activeProfileKey == null) { localPlayerReady = false; return; } Observe(); FlushLocked(immediate: true, shutdown: true); string reason2 = "No removal requested."; if (removeBonuses && !AttributeBonusSession.RemoveActivePersistentBonuses(out reason2)) { Warn("Could not remove the outgoing profile's persistent bonuses before " + reason + "; outstanding receipts are retained and those native identities are quarantined. " + reason2); } else if (removeBonuses) { ManualLogSource? obj = log; if (obj != null) { obj.LogInfo((object)("[Cave Crawlers Leveling][Profiles] Outgoing profile detached; " + reason2)); } } activeProfileKey = null; localPlayerReady = false; SoloLevelingXpObserver.Progression.Restore(new ProgressionSnapshot(1, 0.0, 100.0, 0L)); SoloLevelingStatusMenu.RestoreInvestments(new Dictionary<StatType, long>()); AttributeBonusSession.ResetPersistentLedger(); Schedule.Reset(); lastObserved = SoloLevelingXpObserver.Progression.Snapshot; ManualLogSource? obj2 = log; if (obj2 != null) { obj2.LogInfo((object)("[Cave Crawlers Leveling][Profiles] Profile association ended: " + reason + ". No profile was selected automatically.")); } } internal static IReadOnlyList<SoloLevelingProfileInfo> GetProfiles() { lock (Gate) { if (!StorageReady || accountKey == null) { return Array.Empty<SoloLevelingProfileInfo>(); } return (from p in (from p in Document.Profiles.Values where p.AccountKey == accountKey orderby (!p.IsLegacy) ? 1 : 0 select p).ThenBy<SoloLevelingSaveProfile, string>((SoloLevelingSaveProfile p) => p.Name, StringComparer.OrdinalIgnoreCase) select new SoloLevelingProfileInfo(p.ProfileId, p.Name, p.IsLegacy, p.Level)).ToArray(); } } internal static bool SelectProfile(string id, out string reason) { string result = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (!CanSelectProfile || !localPlayerReady || accountKey == null || activeProfileKey != null) { result = "A valid local character session is required, and no profile may already be active."; return false; } if (!TryGetProfile(id, out SoloLevelingSaveProfile profile, out string key)) { result = "Profile was not found for this account."; return false; } if (!LoadProfile(profile, key, out result)) { return false; } if (CommitMutation(out result)) { return true; } activeProfileKey = null; ResetProgressionState(); return false; } }); reason = result; return result2; } internal static bool CreateAndSelectProfile(string name, out string reason) { string result = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (!CanSelectProfile || !localPlayerReady || accountKey == null || activeProfileKey != null) { result = "A valid local character session is required before creating a profile."; return false; } if (!ValidName(name)) { result = "Profile name must be 1–32 printable characters."; return false; } SoloLevelingSaveProfile soloLevelingSaveProfile = new SoloLevelingSaveProfile { AccountKey = accountKey, ProfileId = Guid.NewGuid().ToString("D"), Name = name.Trim() }; string key = SoloLevelingSaveCodec.ProfileKey(accountKey, soloLevelingSaveProfile.ProfileId); Document.Profiles.Add(key, soloLevelingSaveProfile); if (!LoadProfile(soloLevelingSaveProfile, key, out result)) { Document.Profiles.Remove(key); return false; } if (!CommitMutation(out result)) { Document.Profiles.Remove(key); activeProfileKey = null; ResetProgressionState(); return false; } return true; } }); reason = result; return result2; } internal static bool CreateProfileForSwitch(string name, out string id, out string reason) { string result = ""; string createdId = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (profileSafetyBlocked || !ProgressionReady || accountKey == null || !ValidName(name)) { result = "A valid active session and profile name are required."; return false; } Observe(); FlushLocked(immediate: true, shutdown: true); if (Schedule.Dirty) { result = "Current profile could not be saved; profile creation cancelled."; return false; } SoloLevelingSaveProfile soloLevelingSaveProfile = new SoloLevelingSaveProfile { AccountKey = accountKey, ProfileId = Guid.NewGuid().ToString("D"), Name = name.Trim() }; string key = SoloLevelingSaveCodec.ProfileKey(accountKey, soloLevelingSaveProfile.ProfileId); Document.Profiles.Add(key, soloLevelingSaveProfile); if (!CommitMutation(out result)) { Document.Profiles.Remove(key); return false; } createdId = soloLevelingSaveProfile.ProfileId; return true; } }); id = createdId; reason = result; return result2; } internal static bool PrepareProfileSwitch(string id, out string profileName, out string reason) { string result = ""; string selectedName = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (!ProgressionReady || profileSafetyBlocked || activeProfileKey == null || !TryGetProfile(id, out SoloLevelingSaveProfile profile, out string key)) { result = "Profile switch is not available for the current session."; return false; } if (key == activeProfileKey) { result = "That profile is already active."; return false; } Observe(); FlushLocked(immediate: true, shutdown: true); if (Schedule.Dirty) { result = "Current profile could not be saved; switch confirmation was not opened."; return false; } selectedName = profile.Name; result = "Current profile saved. Confirm or cancel the switch."; return true; } }); profileName = selectedName; reason = result; return result2; } internal static bool RenameProfile(string id, string name, out string reason) { string result = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (!StorageReady || !ValidName(name) || !TryGetProfile(id, out SoloLevelingSaveProfile profile, out string _)) { result = "Profile could not be renamed; check selection and name."; return false; } if (ProgressionReady) { Observe(); FlushLocked(immediate: true, shutdown: true); if (Schedule.Dirty) { result = "Current profile could not be saved; rename cancelled."; return false; } } string name2 = profile.Name; profile.Name = name.Trim(); if (!CommitMutation(out result)) { profile.Name = name2; return false; } return true; } }); reason = result; return result2; } internal static bool DeleteProfile(string id, out string reason) { string result = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (!StorageReady || repository == null || !TryGetProfile(id, out SoloLevelingSaveProfile profile, out string key)) { result = "Profile could not be deleted; storage or profile is unavailable."; return false; } bool flag = key == activeProfileKey; if (flag && (!ProgressionReady || !AttributeBonusSession.TryReadyPlayer(out Player _, out PlayerIdentity _, out result))) { result = "Active profile deletion cancelled because the local player is not in a safe ready state. " + result; return false; } if (ProfileSelected) { Observe(); FlushLocked(immediate: true, shutdown: true); if (Schedule.Dirty) { result = "Profile deletion cancelled because the current progression could not be saved."; return false; } } if (!Document.Profiles.TryGetValue(key, out SoloLevelingSaveProfile value)) { result = "Profile disappeared before deletion could be committed."; return false; } profile = value; try { repository.CreateVerifiedProfileDeletionBackup(); } catch (Exception ex) { result = "Profile deletion cancelled because a verified recovery backup could not be created. Type=" + ex.GetType().Name; Warn(result); return false; } if (flag && !AttributeBonusSession.RemoveActivePersistentBonuses(out result)) { if (result.Contains("could not be fully confirmed", StringComparison.OrdinalIgnoreCase)) { profileSafetyBlocked = true; localPlayerReady = false; Warn("Profile deletion safety-locked after an unconfirmed persistent-bonus rollback; restart required."); } result = "Profile deletion cancelled: " + result; return false; } Document.Profiles.Remove(key); try { repository.Save(); } catch (Exception ex2) { Document.Profiles[key] = profile; result = "Profile deletion was not committed; the profile was retained. Type=" + ex2.GetType().Name; if (flag && !AttributeBonusSession.RestoreActivePersistentBonuses(out string reason2)) { profileSafetyBlocked = true; localPlayerReady = false; result = result + "; persistent bonus recovery could not be confirmed, progression locked. " + reason2; } Warn(result); return false; } try { repository.RefreshRecoveryBackupFromCommittedState(); } catch (Exception ex3) { Document.Profiles[key] = profile; try { repository.Save(); repository.RefreshRecoveryBackupFromCommittedState(); result = "Profile deletion cancelled; the profile and verified recovery state were restored. Type=" + ex3.GetType().Name; if (flag && !AttributeBonusSession.RestoreActivePersistentBonuses(out string reason3)) { profileSafetyBlocked = true; localPlayerReady = false; result = result + "; persistent bonus recovery could not be confirmed, progression locked. " + reason3; } Warn(result); } catch (Exception ex4) { profileSafetyBlocked = true; localPlayerReady = false; result = "Profile deletion recovery could not be fully committed. Progression is locked; the verified pre-deletion archive was retained. SaveError=" + ex3.GetType().Name + "; RecoveryError=" + ex4.GetType().Name; Warn(result); } return false; } if (flag) { activeProfileKey = null; ResetProgressionState(); SoloLevelingProfileMenu.ResetForNewCharacter(); } result = (flag ? "Profile permanently deleted from the Cave Crawlers Leveling profile list. Persistent profile bonuses were removed; choose a profile to continue." : "Profile permanently deleted from the Cave Crawlers Leveling profile list."); ManualLogSource? obj = log; if (obj != null) { obj.LogInfo((object)"[Cave Crawlers Leveling][Profiles] Explicit profile deletion committed after a verified recovery backup."); } return true; } }); reason = result; return result2; } internal static bool ConfirmSwitchProfile(string id, out string reason) { string result = ""; bool result2 = WithStateLock(delegate { lock (Gate) { if (profileSafetyBlocked || !ProgressionReady || activeProfileKey == null || !TryGetProfile(id, out SoloLevelingSaveProfile profile, out string key)) { result = "Profile switch is not available for the current session."; return false; } if (key == activeProfileKey) { result = "That profile is already active."; return true; } Observe(); FlushLocked(immediate: true, shutdown: true); if (Schedule.Dirty) { result = "Current profile could not be saved; switch cancelled."; return false; } if (!AttributeBonusSession.RemoveActivePersistentBonuses(out result)) { if (result.Contains("could not be fully confirmed", StringComparison.OrdinalIgnoreCase)) { profileSafetyBlocked = true; localPlayerReady = false; Warn("Profile progression locked for safety after an unconfirmed bonus rollback; restart required."); } result = "Profile switch blocked: " + result; return false; } activeProfileKey = null; ResetProgressionState(); if (!LoadProfile(profile, key, out result)) { return false; } ManualLogSource? obj = log; if (obj != null) { obj.LogInfo((object)"[Cave Crawlers Leveling][Profiles] Explicit profile switch confirmed; prior profile saved and its persistent bonuses removed."); } return true; } }); reason = result; return result2; } private static bool LoadProfile(SoloLevelingSaveProfile profile, string key, out string reason) { //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown try { SoloLevelingSaveCodec.Validate(profile); Dictionary<StatType, long> dictionary = profile.Investments.Where<KeyValuePair<string, long>>((KeyValuePair<string, long> p) => p.Value > 0).ToDictionary((KeyValuePair<string, long> p) => Enum.Parse<StatType>(p.Key), (KeyValuePair<string, long> p) => p.Value); SoloLevelingStatusMenu.RestoreInvestments(dictionary); AttributeBonusSession.RestoreInvestments(dictionary); SoloLevelingXpObserver.Progression.Restore(profile.Snapshot); activeProfileKey = key; lastObserved = profile.Snapshot; Schedule.Reset(); reason = "Profile selected; XP, level, points and investments restored."; ManualLogSource val = log; if (val != null) { bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(88, 4, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[Cave Crawlers Leveling][Profiles] Explicitly selected profile '"); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(profile.Name); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("'; level "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(profile.Level); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; XP "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<double>(profile.Xp, "0.##"); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; points "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<long>(profile.FreePoints); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("."); } val.LogInfo(val2); } return true; } catch (Exception ex) { reason = "Profile could not be loaded safely: " + ex.GetType().Name; return false; } } private static void ResetProgressionState() { SoloLevelingXpObserver.Progression.Restore(new ProgressionSnapshot(1, 0.0, 100.0, 0L)); SoloLevelingStatusMenu.RestoreInvestments(new Dictionary<StatType, long>()); AttributeBonusSession.ResetPersistentLedger(); Schedule.Reset(); lastObserved = SoloLevelingXpObserver.Progression.Snapshot; } private static bool TryGetProfile(string id, out SoloLevelingSaveProfile profile, out string key) { key = ((accountKey == null) ? "" : SoloLevelingSaveCodec.ProfileKey(accountKey, id)); if (accountKey != null && Guid.TryParseExact(id, "D", out var _) && Document.Profiles.TryGetValue(key, out SoloLevelingSaveProfile value)) { profile = value; return true; } profile = null; return false; } internal static void Tick() { WithStateLock(TickCore); } private static void TickCore() { if (!initialized || stopped) { return; } try { EnsureStorageForData(MainPlayerData.Instance); } catch (Exception ex) { Warn("Local account unavailable. Type=" + ex.GetType().Name); } lock (Gate) { if (ProgressionReady) { Observe(); FlushLocked(); } } } private static void Observe() { ProgressionSnapshot snapshot = SoloLevelingXpObserver.Progression.Snapshot; if (snapshot != lastObserved) { lastObserved = snapshot; Schedule.Mark(Now); } } internal static void InvestmentConfirmed() { WithStateLock(delegate { lock (Gate) { if (ProgressionReady && !stopped) { Observe(); FlushLocked(immediate: true); } } }); } internal static void Flush() { WithStateLock(delegate { lock (Gate) { if (ProfileSelected) { Observe(); FlushLocked(immediate: true, shutdown: true); } } }); } internal static void Shutdown() { WithStateLock(delegate { lock (Gate) { if (!stopped) { if (ProfileSelected) { Observe(); FlushLocked(immediate: true, shutdown: true); } stopped = true; repository?.Dispose(); } } }); } private static bool CommitMutation(out string reason) { if (repository == null) { reason = "Profile exists in memory only because storage is unavailable."; Warn(reason); return false; } try { repository.Save(); reason = "Saved."; return true; } catch (Exception ex) { reason = "Save failed; original/backup retained: " + ex.GetType().Name; Warn(reason); return false; } } private static void FlushLocked(bool immediate = false, bool shutdown = false) { if (repository == null || activeProfileKey == null || !Document.Profiles.TryGetValue(activeProfileKey, out SoloLevelingSaveProfile target)) { return; } try { Schedule.Flush(Now, delegate { SoloLevelingSaveProfile soloLevelingSaveProfile = SoloLevelingXpObserver.Progression.Read(delegate(ProgressionSnapshot snapshot) { SoloLevelingSaveProfile soloLevelingSaveProfile2 = target.Copy(); soloLevelingSaveProfile2.Level = snapshot.Level; soloLevelingSaveProfile2.Xp = snapshot.Xp; soloLevelingSaveProfile2.FreePoints = snapshot.FreePoints; soloLevelingSaveProfile2.Investments = SoloLevelingStatusMenu.ExportInvestments(); return soloLevelingSaveProfile2; }); SoloLevelingSaveCodec.Validate(soloLevelingSaveProfile); Document.Profiles[activeProfileKey] = soloLevelingSaveProfile; repository.Save(); }, immediate, shutdown); } catch (Exception ex) { Warn("Save not completed; progress remains in memory for retry. Type=" + ex.GetType().Name); } } private static bool ValidName(string value) { if (!string.IsNullOrWhiteSpace(value) && value.Trim().Length <= 32) { return !value.Any(char.IsControl); } return false; } private static T WithStateLock<T>(Func<T> action) { return SoloLevelingXpObserver.Progression.Read((ProgressionSnapshot _) => action()); } private static void WithStateLock(Action action) { SoloLevelingXpObserver.Progression.Read(delegate { action(); return 0; }); } private static void Warn(string text) { lock (Warnings) { if (!Warnings.Add(text)) { return; } try { ManualLogSource? obj = log; if (obj != null) { obj.LogWarning((object)("[Cave Crawlers Leveling][Profiles] " + text)); } } catch { } } } } internal static class SoloLevelingXpHud { private static readonly HashSet<string> loggedFailures = new HashSet<string>(); private static PlayerIdentity? suspendedPlayer; private static int suspendedWidth; private static int suspendedHeight; internal static void Draw(int controllerId) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Invalid comparison between Unknown and I4 //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) if (!AttributeBonusSession.IsPrimaryController(controllerId) || SoloLevelingProfileMenu.IsBlocking || SoloLevelingStatusMenu.IsOpen) { return; } string stage = "Event.current / Event.type"; PlayerIdentity? playerIdentity = null; int num = 0; int num2 = 0; try { if (Event.current == null || (int)Event.current.type != 7) { return; } stage = "GameManagerCC.Instance / validação de partida"; GameManagerCC instance = Singleton<GameManagerCC>.Instance; if (instance == null || ((Il2CppObjectBase)instance).Pointer == IntPtr.Zero || !Object.op_Implicit((Object)(object)instance) || instance.GameOver || instance.LeavingGame || !GameManagerCC.IsGenerationComplete) { return; } stage = "GUIManager.expertiseTree.Panel.IsOpen"; GUIManager instance2 = Singleton<GUIManager>.Instance; if (instance2 != null && ((Il2CppObjectBase)instance2).Pointer != IntPtr.Zero && Object.op_Implicit((Object)(object)instance2)) { TalentTree expertiseTree = instance2.expertiseTree; if (expertiseTree != null && ((Il2CppObjectBase)expertiseTree).Pointer != IntPtr.Zero && Object.op_Implicit((Object)(object)expertiseTree)) { Panel panel = expertiseTree.Panel; if (panel != null && ((Il2CppObjectBase)panel).Pointer != IntPtr.Zero && Object.op_Implicit((Object)(object)panel) && panel.IsOpen) { return; } } } stage = "TryReadyPlayer: identidade local viva e pronta"; if (!AttributeBonusSession.TryReadyPlayer(out Player _, out PlayerIdentity identity, out string _)) { return; } playerIdentity = identity; stage = "Screen.width / Screen.height / Progression.Snapshot"; num = Screen.width; num2 = Screen.height; PlayerIdentity? playerIdentity2 = suspendedPlayer; PlayerIdentity playerIdentity3 = identity; if (playerIdentity2.HasValue && (!playerIdentity2.HasValue || playerIdentity2.GetValueOrDefault() == playerIdentity3) && suspendedWidth == num && suspendedHeight == num2) { return; } ProgressionSnapshot snapshot = SoloLevelingXpObserver.Progression.Snapshot; SoloLevelingHudObstacle? obstacle = SoloLevelingHudObstacles.HealthBar(instance2, num2); if (!SoloLevelingHudLayout.TryCreate(num, num2, snapshot, out var layout, obstacle)) { return; } using (SoloLevelingTheme.Paint()) { stage = "Theme.Panel HUD"; SoloLevelingTheme.Panel(new Rect(layout.X, layout.Y, layout.Width, layout.Height)); SoloLevelingTheme.Small(new Rect(layout.X + 8f, layout.Y + 3f, layout.Width - 156f, 20f), $"SYSTEM / Lv. {snapshot.Level}"); SoloLevelingTheme.Points(new Rect(layout.X + layout.Width - 146f, layout.Y + 3f, 138f, 20f), $"Points: {snapshot.FreePoints}"); SoloLevelingTheme.Label(new Rect(layout.X + 8f, layout.Y + 23f, layout.Width - 16f, 20f), "XP " + SoloLevelingUiText.Number(snapshot.Xp) + " / " + SoloLevelingUiText.Number(snapshot.RequiredXp)); SoloLevelingTheme.Progress(new Rect(layout.X + 8f, layout.Y + 46f, layout.Width - 16f, 8f), snapshot.Xp, snapshot.RequiredXp); } } catch (Exception error) { LogFailure(stage, error); if (playerIdentity.HasValue) { suspendedPlayer = playerIdentity; suspendedWidth = num; suspendedHeight = num2; } } } private static void LogFailure(string stage, Exception error) { string text = error.ToString(); if (loggedFailures.Count < 16 && loggedFailures.Add(stage + "\n" + text)) { AttributeBonusSession.LogHudException(stage, text); } } } internal readonly record struct SoloLevelingHudObstacle(float X, float Y, float Width, float Height); internal readonly record struct SoloLevelingHudLayout(float X, float Y, float Width, float Height, float FillWidth) { internal static bool TryCreate(int screenWidth, int screenHeight, ProgressionSnapshot xp, out SoloLevelingHudLayout layout, SoloLevelingHudObstacle? obstacle = null) { layout = default(SoloLevelingHudLayout); if (screenWidth < 120 || screenHeight < 120) { return false; } float num = Math.Min(420, screenWidth - 24); double num2 = ((double.IsFinite(xp.Xp) && double.IsFinite(xp.RequiredXp) && xp.RequiredXp > 0.0) ? Math.Clamp(xp.Xp / xp.RequiredXp, 0.0, 1.0) : 0.0); float num3 = screenHeight - 80; if (obstacle.HasValue) { SoloLevelingHudObstacle valueOrDefault = obstacle.GetValueOrDefault(); if (float.IsFinite(valueOrDefault.X) && float.IsFinite(valueOrDefault.Y) && float.IsFinite(valueOrDefault.Width) && float.IsFinite(valueOrDefault.Height) && valueOrDefault.Width > 0f && valueOrDefault.Height > 0f && valueOrDefault.X < 12f + num && valueOrDefault.X + valueOrDefault.Width > 12f && valueOrDefault.Y < num3 + 60f && valueOrDefault.Y + valueOrDefault.Height > num3) { num3 = valueOrDefault.Y - 68f; if (num3 < 12f) { return false; } } } layout = new SoloLevelingHudLayout(12f, num3, num, 60f, (num - 16f) * (float)num2); return true; } } internal static class SoloLevelingStatusMenu { private readonly record struct StatOption(StatType Stat, float Step, string Unit) { [CompilerGenerated] public void Deconstruct(out StatType Stat, out float Step, out string Unit) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected I4, but got Unknown Stat = (StatType)(int)this.Stat; Step = this.Step; Unit = this.Unit; } } private static readonly StatOption[] Options = new StatOption[13] { new StatOption((StatType)3, SoloLevelingStatRules.Steps["ExtraDamage"], "flat damage (fractional storage)"), new StatOption((StatType)14, SoloLevelingStatRules.Steps["DamageMultiplier"], "pp; value/100"), new StatOption((StatType)12, SoloLevelingStatRules.Steps["CriticalChance"], "chance percentage points"), new StatOption((StatType)13, SoloLevelingStatRules.Steps["CriticalDamage"], "pp; value/100"), new StatOption((StatType)6, SoloLevelingStatRules.Steps["AttackSpeed"], "rating; +1.5% to speed factor"), new StatOption((StatType)9, SoloLevelingStatRules.Steps["WeaponRange"], "absolute distance"), new StatOption((StatType)7, SoloLevelingStatRules.Steps["Knockback"], "knockback magnitude; consumer x0.65"), new StatOption((StatType)26, SoloLevelingStatRules.Steps["DodgeChance"], "dodge percentage points"), new StatOption((StatType)4, SoloLevelingStatRules.Steps["BlockChance"], "block percentage points"), new StatOption((StatType)5, SoloLevelingStatRules.Steps["MoveSpeed"], "pp; 1+value/100"), new StatOption((StatType)19, SoloLevelingStatRules.Steps["SpellHaste"], "cooldown reduction percentage points"), new StatOption((StatType)10, SoloLevelingStatRules.Steps["MaxTorchDuration"], "absolute duration units"), new StatOption((StatType)25, SoloLevelingStatRules.Steps["Dexterity"], "pp; movement while attacking/reloading; native range -100 to +100") }; private static AttributeInvestment<StatType> Investments = new AttributeInvestment<StatType>(); private static bool open; private static readonly HashSet<string> loggedFailures = new HashSet<string>(); private static int lastFrame = -1; private static int lastPurchaseFrame = -1; private static int page; private static string message = "Account-wide progression. All XP sources; investments autosave."; internal static bool IsOpen { get { if (open && SoloLevelingPersistence.ProgressionReady) { return !SoloLevelingProfileMenu.IsBlocking; } return false; } } private static int PageSize => SoloLevelingMenuLayout.Status(Screen.width, Screen.height).Rows; private static int PageCount => (Options.Length + PageSize - 1) / PageSize; internal static void NotifyLegacyRefund(long points) { message = $"Legacy Dexterity removed. Refunded points: {points}. Other investment counts are unchanged."; } internal static Dictionary<string, long> ExportInvestments() { return Investments.Export().ToDictionary<KeyValuePair<StatType, long>, string, long>((KeyValuePair<StatType, long> p) => ((object)p.Key/*cast due to .constrained prefix*/).ToString(), (KeyValuePair<StatType, long> p) => p.Value, StringComparer.Ordinal); } internal static void RestoreInvestments(IReadOnlyDictionary<StatType, long> saved) { Investments = new AttributeInvestment<StatType>(); Investments.Restore(saved); } internal static void Tick(int id) { if (AttributeBonusSession.IsPrimaryController(id) && lastFrame != Time.frameCount) { lastFrame = Time.frameCount; if (Input.GetKeyDown((KeyCode)290) && SoloLevelingPersistence.ProgressionReady && !SoloLevelingProfileMenu.IsBlocking) { SetOpen(!open); } SoloLevelingMenuInput.Refresh(id); } } private static void SetOpen(bool value) { if (open != value) { open = value; if (open) { loggedFailures.Clear(); } } } internal static void Detach(int id) { if (AttributeBonusSession.IsPrimaryController(id)) { SetOpen(value: false); } } private static bool CanInvest(StatOption option, out float current, out string detail, out string reason) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Invalid comparison between Unknown and I4 //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Invalid comparison between Unknown and I4 //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Invalid comparison between Unknown and I4 //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Invalid comparison between Unknown and I4 //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Invalid comparison between Unknown and I4 //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Invalid comparison between Unknown and I4 //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Invalid comparison between Unknown and I4 //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Invalid comparison between Unknown and I4 current = float.NaN; detail = option.Unit; if (!AttributeBonusSession.TryReadyPlayer(out Player player, out PlayerIdentity _, out reason)) { detail = "waiting for a ready local player"; return false; } current = ((Entity)player).GetStat(option.Stat, true); StatTypeInfo val = default(StatTypeInfo); if (!StatInfo.TryGetStatInfo(option.Stat, ref val) || val == null) { reason = (detail = "Stat configuration is unavailable."); return false; } detail = option.Unit + "; base " + SoloLevelingUiText.Number(val.BaseAmount) + (val.UseMax ? ("; max. " + SoloLevelingUiText.Number(val.maxValue)) : "") + (val.UseMin ? ("; min. " + SoloLevelingUiText.Number(val.minValue)) : ""); if (option.Step <= 0f) { reason = "Investment disabled: scale not confirmed."; return false; } if ((int)option.Stat == 25 && Investments.Points(option.Stat) >= 100) { reason = "Permanent Dexterity is limited to +100."; return false; } if ((int)option.Stat == 9 && val.isInteger) { reason = "The 0.1 step is incompatible with integer rounding; purchase blocked."; return false; } float num = ((Entity)player).GetStat(option.Stat, false); if ((int)option.Stat == 3) { float num2 = default(float); if (!((Entity)player).entityStats.stats.TryGetValue(option.Stat, ref num2)) { reason = "Extra Damage is unavailable in raw storage."; return false; } num = num2 + val.BaseAmount; } if (!AttributeInvestment<StatType>.WithinLimits(num, option.Step, val.UseMin, val.minValue, val.UseMax, val.maxValue)) { reason = $"Stat limit or invalid value: unclamped={num}; step={option.Step}; UseMin={val.UseMin}; min={val.minValue}; UseMax={val.UseMax}; max={val.maxValue}."; return false; } if ((int)option.Stat == 12 && num + option.Step > 100f) { reason = "Critical Chance would exceed 100%."; return false; } if (((int)option.Stat == 26 || (int)option.Stat == 4 || (int)option.Stat == 19 || (int)option.Stat == 25) && num + option.Step > 100f) { reason = "The next step would exceed 100 percentage points; purchase blocked."; return false; } if (SoloLevelingXpObserver.Progression.Snapshot.FreePoints <= 0) { reason = "No attribute points available (requires 1)."; return false; } reason = $"Available; {reason}; unclamped={num}; step={option.Step}."; return true; } internal static void Draw(int id) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_03fc: Unknown result type (might be due to invalid IL or missing references) //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_0464: Unknown result type (might be due to invalid IL or missing references) //IL_04ce: Unknown result type (might be due to invalid IL or missing references) //IL_04f6: Unknown result type (might be due to invalid IL or missing references) //IL_0502: Unknown result type (might be due to invalid IL or missing references) //IL_0507: Unknown result type (might be due to invalid IL or missing references) //IL_091d: Unknown result type (might be due to invalid IL or missing references) //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_0597: Unknown result type (might be due to invalid IL or missing references) //IL_05c8: Unknown result type (might be due to invalid IL or missing references) //IL_05cd: Unknown result type (might be due to invalid IL or missing references) //IL_0976: Unknown result type (might be due to invalid IL or missing references) //IL_09c0: Unknown result type (might be due to invalid IL or missing references) //IL_0a37: Unknown result type (might be due to invalid IL or missing references) //IL_063c: Unknown result type (might be due to invalid IL or missing references) //IL_066c: Unknown result type (might be due to invalid IL or missing references) //IL_0a62: Unknown result type (might be due to invalid IL or missing references) //IL_068a: Unknown result type (might be due to invalid IL or missing references) //IL_068f: Unknown result type (might be due to invalid IL or missing references) //IL_06b5: Unknown result type (might be due to invalid IL or missing references) //IL_06ba: Unknown result type (might be due to invalid IL or missing references) //IL_0a70: Unknown result type (might be due to invalid IL or missing references) //IL_072d: Unknown result type (might be due to invalid IL or missing references) //IL_0a79: Unknown result type (might be due to invalid IL or missing references) //IL_0a7f: Invalid comparison between Unknown and I4 //IL_0a83: Unknown result type (might be due to invalid IL or missing references) //IL_0a89: Invalid comparison between Unknown and I4 //IL_0798: Unknown result type (might be due to invalid IL or missing references) //IL_0a8d: Unknown result type (might be due to invalid IL or missing references) //IL_0a93: Invalid comparison between Unknown and I4 //IL_07e9: Unknown result type (might be due to invalid IL or missing references) //IL_07fa: Unknown result type (might be due to invalid IL or missing references) //IL_0868: Unknown result type (might be due to invalid IL or missing references) //IL_086d: Unknown result type (might be due to invalid IL or missing references) //IL_0829: Unknown result type (might be due to invalid IL or missing references) //IL_082e: Unknown result type (might be due to invalid IL or missing references) SoloLevelingMenuInput.Refresh(id); if (!IsOpen || !AttributeBonusSession.IsPrimaryController(id)) { return; } bool flag = true; bool flag2 = false; string stage = "Event.current / Event.type"; string eventType = "not obtained"; try { Event current = Event.current; eventType = ((current == null) ? "null" : ((object)current.type/*cast due to .constrained prefix*/).ToString()); stage = "GUI.enabled.get"; flag = GUI.enabled; flag2 = true; using (SoloLevelingTheme.Paint()) { SoloLevelingMenuLayout soloLevelingMenuLayout = SoloLevelingMenuLayout.Status(Screen.width, Screen.height); Rect panel = soloLevelingMenuLayout.Panel; float width = ((Rect)(ref panel)).width; float height = ((Rect)(ref panel)).height; stage = "Theme.Panel status"; SoloLevelingTheme.Panel(panel); ProgressionSnapshot snapshot = SoloLevelingXpObserver.Progression.Snapshot; string text = SoloLevelingPersistence.ActiveProfileName ?? "No profile"; SoloLevelingTheme.Title(new Rect(26f, ((Rect)(ref panel)).y + 10f, width