using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Splatform; using TMPro; using TameMate.Lineages; using TameMate.OceanHorn; using TameMate.Survival; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.8.0.0")] namespace TameMate.Lineages { internal static class AscensionModalInput { private static bool s_captured; private static int s_closedFrame = -10; internal static bool ConfirmSelected { get; private set; } private static bool BlocksInput { get { if (!EvolutionAscensionEngine.IsModalOpen) { return Time.frameCount <= s_closedFrame; } return true; } } internal static void Install(Harmony harmony) { Patch(harmony, typeof(PlayerController), "TakeInput", new Type[1] { typeof(bool) }, "TakeInputPostfix", prefix: false); Patch(harmony, typeof(Player), "TakeInput", Type.EmptyTypes, "PlayerInputPostfix", prefix: false); Patch(harmony, typeof(PlayerController), "InInventoryEtc", Type.EmptyTypes, "InventoryPostfix", prefix: false); Patch(harmony, typeof(GameCamera), "UpdateMouseCapture", Type.EmptyTypes, "MouseCapturePostfix", prefix: false); Patch(harmony, typeof(GameCamera), "UpdateCamera", new Type[1] { typeof(float) }, "CameraPrefix", prefix: true); Patch(harmony, typeof(Menu), "Update", Type.EmptyTypes, "MenuPrefix", prefix: true); } private static void Patch(Harmony harmony, Type type, string name, Type[] parameters, string handler, bool prefix) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(type, name, parameters, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.FullName, name); } HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(AscensionModalInput), handler, (Type[])null, (Type[])null)); val.priority = 0; harmony.Patch((MethodBase)methodInfo, prefix ? val : null, prefix ? null : val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } internal static void Acquire(Player player) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) s_captured = true; ConfirmSelected = false; player.m_autoRun = false; player.SetControls(Vector3.zero, false, false, false, false, false, false, false, false, false, false, false); ShowCursor(); } internal static void ShowCursor() { Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; ZCursor.LockState = (CursorLockMode)0; ZCursor.Show(); } internal static void Release() { if (s_captured) { s_captured = false; s_closedFrame = Time.frameCount; PlayerController.SetTakeInputDelay(0.2f); if ((Object)(object)GameCamera.instance != (Object)null) { GameCamera.instance.UpdateMouseCapture(); } } } internal static bool HandleKey(KeyCode key) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Invalid comparison between Unknown and I4 //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 if (!EvolutionAscensionEngine.IsModalOpen) { return false; } if ((int)key == 9) { ConfirmSelected = !ConfirmSelected; } else if ((int)key == 276) { ConfirmSelected = true; } else if ((int)key == 275) { ConfirmSelected = false; } else if ((int)key == 27) { EvolutionAscensionEngine.CloseModal(); } else { if ((int)key != 13 && (int)key != 271) { return false; } if (ConfirmSelected) { EvolutionAscensionEngine.ConfirmAscension(); } else { EvolutionAscensionEngine.CloseModal(); } } return true; } private static void TakeInputPostfix(ref bool __result) { if (BlocksInput) { __result = false; } } private static void PlayerInputPostfix(Player __instance, ref bool __result) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && BlocksInput) { __result = false; } } private static void InventoryPostfix(ref bool __result) { if (BlocksInput) { __result = true; } } private static void MouseCapturePostfix() { if (EvolutionAscensionEngine.IsModalOpen) { ShowCursor(); } } private static bool CameraPrefix() { return !BlocksInput; } private static bool MenuPrefix() { if (!EvolutionAscensionEngine.IsModalOpen) { return Time.frameCount > s_closedFrame; } return false; } } public static class AutonomousDifficultyBalance { private static bool s_isInstalled; private static ManualLogSource s_logger; private static Harmony s_harmonyInstance; private static volatile bool s_isScalingActive; public static bool IsScalingActive => s_isScalingActive; public static void Install(Harmony harmony, ManualLogSource logger) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown if (s_isInstalled) { return; } s_logger = logger; s_harmonyInstance = harmony; try { MethodInfo methodInfo = AccessTools.Method(typeof(Character), "GetMaxHealth", (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException("Character", "GetMaxHealth"); } MethodInfo methodInfo2 = AccessTools.Method(typeof(AutonomousDifficultyBalance), "GetMaxHealthPostfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo3 = AccessTools.Method(typeof(ZNet), "Awake", (Type[])null, (Type[])null); if (methodInfo3 != null) { MethodInfo methodInfo4 = AccessTools.Method(typeof(AutonomousDifficultyBalance), "OnWorldEnterPostfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo5 = AccessTools.Method(typeof(ZNet), "OnDestroy", (Type[])null, (Type[])null); if (methodInfo5 != null) { MethodInfo methodInfo6 = AccessTools.Method(typeof(AutonomousDifficultyBalance), "OnWorldExitPrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } s_isInstalled = true; InvalidateCache(); if (s_logger != null) { s_logger.LogInfo((object)"[AutonomousDifficultyBalance] Autonomous +25% wild health balance installed with zero-overhead cached execution."); } } catch (Exception ex) { if (harmony != null) { try { harmony.UnpatchSelf(); } catch { } } s_isInstalled = false; s_isScalingActive = false; if (s_logger != null) { s_logger.LogError((object)("[AutonomousDifficultyBalance] Installation failed (rolled back atomically): " + ex.Message)); } throw; } } public static void Uninstall() { if (s_harmonyInstance != null) { try { s_harmonyInstance.UnpatchSelf(); } catch { } } s_isInstalled = false; s_isScalingActive = false; } public static void OnWorldEnterPostfix() { InvalidateCache(); } public static void OnWorldExitPrefix() { ResetCache(); } public static void InvalidateCache() { bool flag = s_isScalingActive; s_isScalingActive = ComputeScalingActive(); if (s_logger != null && flag != s_isScalingActive) { s_logger.LogInfo((object)$"[AutonomousDifficultyBalance] Cached scaling state updated: {s_isScalingActive} (Preset: {DifficultyCoordinator.GetActivePreset()}, ExternalScaling: {IsExternalHealthScalingActive()})"); } } public static void ResetCache() { s_isScalingActive = false; if (s_logger != null) { s_logger.LogInfo((object)"[AutonomousDifficultyBalance] Cached scaling state reset (world exit / clean state)."); } } private static bool ComputeScalingActive() { try { if (DifficultyCoordinator.GetActivePreset() != DifficultyPreset.Dificil) { return false; } if (IsExternalHealthScalingActive()) { return false; } return true; } catch (Exception ex) { if (s_logger != null) { s_logger.LogWarning((object)("[AutonomousDifficultyBalance] Error computing scaling state: " + ex.Message)); } return false; } } public static bool IsExternalHealthScalingActive() { try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("MidnightsFX.StarLevelSystem")) { return true; } if (AccessTools.TypeByName("StarLevelSystem.LevelSystem") != null || AccessTools.TypeByName("StarLevelSystem.StarLevelSystem") != null) { return true; } } catch { } try { if (StarLevelSystemAdapter.IsConfigFileAvailable) { return true; } } catch { } try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.creaturelevelcontrol")) { return true; } if (AccessTools.TypeByName("CreatureLevelControl.CreatureLevelControl") != null) { return true; } } catch { } return false; } public static void GetMaxHealthPostfix(Character __instance, ref float __result) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (s_isScalingActive && !((Object)(object)__instance == (Object)null) && !__instance.IsPlayer() && !__instance.IsBoss() && !__instance.IsTamed() && (int)__instance.m_faction != 0) { __result *= 1.25f; } } } public struct BossAddSnapshot { public bool IsAvailable; public float BonemassHealthMultiplier; public float BonemassMoveSpeedMultiplier; public float BonemassAttackSpeedMultiplier; public bool SummonMechanicEnabled; public string ConfigPath; public static BossAddSnapshot CreateDefault() { return new BossAddSnapshot { IsAvailable = false, BonemassHealthMultiplier = 1f, BonemassMoveSpeedMultiplier = 1f, BonemassAttackSpeedMultiplier = 1f, SummonMechanicEnabled = true, ConfigPath = string.Empty }; } } public static class BossAddAdapter { public const string BossAddPluginGuid = "bossadd"; private const string ConfigFileName = "bossadd.cfg"; public const string AuthorizedPrefabName = "vfx_corpse_destruction_large"; public const int AuthorizedPrefabHash = 1848449852; public const int RequiredConsecutiveSamples = 3; private static bool? s_isPluginLoadedCached = null; private static string s_customConfigPath = null; private static ManualLogSource s_logger = null; private static bool s_isInstalled = false; private static readonly Dictionary s_stagnantObservations = new Dictionary(); private static readonly Dictionary s_firstObservedTime = new Dictionary(); public static bool IsInstalled => s_isInstalled; public static bool IsAvailable { get { if (!IsPluginLoaded) { return IsConfigFileAvailable; } return true; } } public static bool IsPluginLoaded { get { if (s_isPluginLoadedCached.HasValue) { return s_isPluginLoadedCached.Value; } try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.TryGetValue("bossadd", out var value)) { if (value != null && value.Metadata != null && value.Metadata.Version != null) { if (value.Metadata.Version.Major == 1 && value.Metadata.Version.Minor == 2 && value.Metadata.Version.Build == 4) { s_isPluginLoadedCached = true; return true; } if (s_logger != null) { s_logger.LogWarning((object)$"[TameMate BossAddAdapter] BossAdd versión {value.Metadata.Version} detectada. Compatibilidad validada exclusivamente para versión 1.2.4; adaptador inactivo."); } s_isPluginLoadedCached = false; return false; } s_isPluginLoadedCached = false; return false; } } catch { } try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { string name = assemblies[i].GetName().Name; if (string.Equals(name, "bossadd", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "bossadd.merged", StringComparison.OrdinalIgnoreCase)) { Version version = assemblies[i].GetName().Version; if (version == null || (version.Major == 1 && version.Minor == 2)) { s_isPluginLoadedCached = true; return true; } } } } catch { } s_isPluginLoadedCached = false; return false; } } public static bool IsConfigFileAvailable { get { string text = ResolveConfigFilePath(); if (!string.IsNullOrEmpty(text)) { return File.Exists(text); } return false; } } public static void SetCustomConfigPathForTesting(string path) { s_customConfigPath = path; } public static void SetPluginLoadedForTesting(bool? loaded) { s_isPluginLoadedCached = loaded; } public static string ResolveConfigFilePath() { if (!string.IsNullOrEmpty(s_customConfigPath)) { return s_customConfigPath; } try { string configPath = Paths.ConfigPath; if (!string.IsNullOrEmpty(configPath)) { string text = Path.Combine(configPath, "bossadd.cfg"); if (File.Exists(text)) { return text; } } } catch { } string text2 = "C:\\Users\\Mitsu\\AppData\\Roaming\\Thunderstore Mod Manager\\DataFolder\\Valheim\\profiles\\Valheim Supreme\\BepInEx\\config"; if (Directory.Exists(text2)) { string text3 = Path.Combine(text2, "bossadd.cfg"); if (File.Exists(text3)) { return text3; } } return string.Empty; } public static BossAddSnapshot CaptureCurrentState() { BossAddSnapshot result = BossAddSnapshot.CreateDefault(); string text = (result.ConfigPath = ResolveConfigFilePath()); if (string.IsNullOrEmpty(text) || !File.Exists(text)) { result.IsAvailable = IsPluginLoaded; return result; } result.IsAvailable = true; try { string[] array = File.ReadAllLines(text); string a = string.Empty; for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (string.IsNullOrEmpty(text2) || text2.StartsWith("#")) { continue; } if (text2.StartsWith("[") && text2.EndsWith("]")) { a = text2.Substring(1, text2.Length - 2).Trim(); continue; } int num = text2.IndexOf('='); if (num <= 0) { continue; } string a2 = text2.Substring(0, num).Trim(); string text3 = text2.Substring(num + 1).Trim(); if (!string.Equals(a, "Bonemass", StringComparison.OrdinalIgnoreCase)) { continue; } if (string.Equals(a2, "(Boss Stat) HealthMultiplier", StringComparison.OrdinalIgnoreCase)) { if (float.TryParse(text3, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { result.BonemassHealthMultiplier = result2; } } else if (string.Equals(a2, "(Boss Stat) MoveSpeedMultiplier", StringComparison.OrdinalIgnoreCase)) { if (float.TryParse(text3, NumberStyles.Float, CultureInfo.InvariantCulture, out var result3)) { result.BonemassMoveSpeedMultiplier = result3; } } else if (string.Equals(a2, "(Boss Stat) AttackSpeedMultiplier", StringComparison.OrdinalIgnoreCase)) { if (float.TryParse(text3, NumberStyles.Float, CultureInfo.InvariantCulture, out var result4)) { result.BonemassAttackSpeedMultiplier = result4; } } else if (string.Equals(a2, "(Summon) Enabled", StringComparison.OrdinalIgnoreCase)) { result.SummonMechanicEnabled = string.Equals(text3, "true", StringComparison.OrdinalIgnoreCase); } } } catch { } return result; } public static void ResetCache() { s_isPluginLoadedCached = null; } public static void Install(Harmony harmony, ManualLogSource logger) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown if (s_isInstalled || harmony == null) { return; } s_logger = logger; try { MethodInfo method = typeof(ZNetScene).GetMethod("RemoveObjects", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method != null) { MethodInfo method2 = typeof(BossAddAdapter).GetMethod("RemoveObjectsPrefix", BindingFlags.Static | BindingFlags.NonPublic); harmony.Patch((MethodBase)method, new HarmonyMethod(method2, 800, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo method3 = typeof(Player).GetMethod("UpdateTeleport", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method3 != null) { MethodInfo method4 = typeof(BossAddAdapter).GetMethod("UpdateTeleportPostfix", BindingFlags.Static | BindingFlags.NonPublic); harmony.Patch((MethodBase)method3, (HarmonyMethod)null, new HarmonyMethod(method4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo method5 = typeof(Game).GetMethod("UpdateRespawn", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method5 != null) { MethodInfo method6 = typeof(BossAddAdapter).GetMethod("UpdateRespawnPostfix", BindingFlags.Static | BindingFlags.NonPublic); harmony.Patch((MethodBase)method5, (HarmonyMethod)null, new HarmonyMethod(method6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } s_isInstalled = true; if (s_logger != null) { s_logger.LogInfo((object)"BossAddAdapter: salvaguardas de limpieza de escena y recuperación de VFX instaladas con éxito."); } } catch (Exception ex) { if (s_logger != null) { s_logger.LogError((object)("Fallo al instalar BossAddAdapter: " + ex)); } } } public static void Uninstall() { s_isInstalled = false; s_logger = null; s_stagnantObservations.Clear(); s_firstObservedTime.Clear(); } private static void RemoveObjectsPrefix(ZNetScene __instance) { if (!IsPluginLoaded || (Object)(object)__instance == (Object)null) { return; } FieldInfo field = typeof(ZNetScene).GetField("m_instances", BindingFlags.Instance | BindingFlags.NonPublic); if (field == null || !(field.GetValue(__instance) is Dictionary { Count: not 0 } dictionary)) { return; } List list = null; foreach (KeyValuePair item in dictionary) { if (!Object.op_Implicit((Object)(object)item.Value) || item.Value.GetZDO() == null) { if (list == null) { list = new List(); } list.Add(item.Key); } } if (list == null || list.Count <= 0) { return; } bool flag = (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer(); int num = 0; for (int i = 0; i < list.Count; i++) { ZDO val = list[i]; dictionary.Remove(val); int prefab = val.GetPrefab(); if (prefab == 1848449852) { if (flag && ZDOMan.instance != null) { val.SetOwner(ZDOMan.GetSessionID()); ZDOMan.instance.DestroyZDO(val); num++; } else { val.Created = false; } } else { val.Created = false; } } if (num > 0 && s_logger != null) { s_logger.LogInfo((object)$"[TameMate BossAddAdapter] Prevenido fallo en RemoveObjects: {num} ZDO(s) de efectos efímeros purgados limpiamente."); } } private static void UpdateTeleportPostfix(Player __instance, float dt) { //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) if (!IsPluginLoaded || (Object)(object)__instance == (Object)null) { return; } FieldInfo field = typeof(Player).GetField("m_teleporting", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = typeof(Player).GetField("m_teleportTimer", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field3 = typeof(Player).GetField("m_teleportTargetPos", BindingFlags.Instance | BindingFlags.NonPublic); if (!(field == null) && !(field2 == null) && !(field3 == null) && (bool)field.GetValue(__instance)) { float num = (float)field2.GetValue(__instance); if (!(num < 3f)) { Vector3 targetPos = (Vector3)field3.GetValue(__instance); RecoverOrphanedVFXInTargetArea(targetPos); } } } private static void UpdateRespawnPostfix(Game __instance, float dt) { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: 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_00c7: Unknown result type (might be due to invalid IL or missing references) if (!IsPluginLoaded || (Object)(object)__instance == (Object)null) { return; } FieldInfo field = typeof(Game).GetField("m_requestRespawn", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = typeof(Game).GetField("m_respawnWait", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field3 = typeof(Game).GetField("m_playerProfile", BindingFlags.Instance | BindingFlags.NonPublic); if (field == null || field2 == null || !(bool)field.GetValue(__instance)) { return; } float num = (float)field2.GetValue(__instance); if (!(num < 3f)) { Vector3 targetPos = Vector3.zero; PlayerProfile val = (PlayerProfile)((field3 != null) ? /*isinst with value type is only supported in some contexts*/: null); if (val != null && val.HaveCustomSpawnPoint()) { targetPos = val.GetCustomSpawnPoint(); } else if ((Object)(object)ZoneSystem.instance != (Object)null && !string.IsNullOrEmpty(__instance.m_StartLocation)) { ZoneSystem.instance.GetLocationIcon(__instance.m_StartLocation, ref targetPos); } RecoverOrphanedVFXInTargetArea(targetPos); } } [MethodImpl(MethodImplOptions.NoInlining)] public static int RecoverOrphanedVFXInTargetArea(Vector3 targetPos) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (!IsPluginLoaded) { return 0; } return RecoverOrphanedVFXInTargetAreaInternal(targetPos); } [MethodImpl(MethodImplOptions.NoInlining)] private static int RecoverOrphanedVFXInTargetAreaInternal(Vector3 targetPos) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0161: 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_0140: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) if (ZoneSystem.instance == null || ZNetScene.instance == null || ZDOMan.instance == null) { return 0; } if (ZNetScene.instance.IsAreaReady(targetPos)) { if (s_stagnantObservations.Count > 0) { s_stagnantObservations.Clear(); s_firstObservedTime.Clear(); } return 0; } if (ZNet.instance == null || !ZNet.instance.IsServer()) { return 0; } Vector2s zone = ZoneSystem.GetZone(targetPos); List list = new List(); SimulationDistance val = default(SimulationDistance); ((SimulationDistance)(ref val))..ctor(1, 0, false); ZDOMan.instance.FindSectorObjects(zone, val, list, (List)null); int num = 0; HashSet hashSet = new HashSet(); for (int i = 0; i < list.Count; i++) { ZDO val2 = list[i]; if (val2 == null || val2.GetPrefab() != 1848449852) { continue; } hashSet.Add(val2.m_uid); if ((Object)(object)ZNetScene.instance.FindInstance(val2) != (Object)null) { s_stagnantObservations.Remove(val2.m_uid); s_firstObservedTime.Remove(val2.m_uid); } else { if (!val2.Created) { continue; } if (!s_stagnantObservations.TryGetValue(val2.m_uid, out var value)) { s_stagnantObservations[val2.m_uid] = 1; s_firstObservedTime[val2.m_uid] = Time.realtimeSinceStartup; continue; } value++; s_stagnantObservations[val2.m_uid] = value; if (value >= 3) { GameObject prefab = ZNetScene.instance.GetPrefab(1848449852); if ((Object)(object)prefab != (Object)null && string.Equals(((Object)prefab).name, "vfx_corpse_destruction_large", StringComparison.Ordinal) && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null && (Object)(object)prefab.GetComponent() == (Object)null) { val2.SetOwner(ZDOMan.GetSessionID()); ZDOMan.instance.DestroyZDO(val2); s_stagnantObservations.Remove(val2.m_uid); s_firstObservedTime.Remove(val2.m_uid); num++; } } } } List list2 = null; foreach (KeyValuePair s_stagnantObservation in s_stagnantObservations) { if (!hashSet.Contains(s_stagnantObservation.Key)) { if (list2 == null) { list2 = new List(); } list2.Add(s_stagnantObservation.Key); } } if (list2 != null) { for (int j = 0; j < list2.Count; j++) { s_stagnantObservations.Remove(list2[j]); s_firstObservedTime.Remove(list2[j]); } } if (num > 0 && s_logger != null) { s_logger.LogWarning((object)$"[TameMate BossAddAdapter] Recuperado sector ({zone.x}, {zone.y}): purgados {num} ZDO(s) huérfanos estancados de vfx_corpse_destruction_large. Transición de carga desbloqueada."); } return num; } } public static class CataclysmicCombatPipeline { private static bool s_installed = false; private static readonly HashSet s_processedOutgoingHits = new HashSet(); public static void Install(Harmony harmony, Assembly coreAssembly) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown if (s_installed) { return; } s_installed = true; try { MethodInfo methodInfo = AccessTools.Method(typeof(Character), "Damage", new Type[1] { typeof(HitData) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(CataclysmicCombatPipeline), "CombatDamagePrefix", (Type[])null, (Type[])null); if (methodInfo != null && methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2, 600, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate Lineages] CataclysmicCombatPipeline.Install warning: " + ex.Message)); } } [HarmonyPriority(600)] public static void CombatDamagePrefix(Character __instance, HitData hit) { if (!((Object)(object)__instance == (Object)null) && hit != null) { Character attacker = hit.GetAttacker(); if ((Object)(object)attacker != (Object)null && attacker.IsTamed() && !attacker.IsPlayer()) { CataclysmicHudFormatter.EnsureLiveStateSynchronized(attacker); ApplyOutgoingCataclysmicAttack(attacker, hit); } if (__instance.IsTamed() && !__instance.IsPlayer()) { CataclysmicHudFormatter.EnsureLiveStateSynchronized(__instance); ApplyIncomingCataclysmicEffects(__instance, hit); } } } public static void ApplyOutgoingCataclysmicAttack(Character attacker, HitData hit) { if ((Object)(object)attacker == (Object)null || hit == null || !s_processedOutgoingHits.Add(hit)) { return; } if (s_processedOutgoingHits.Count > 256) { s_processedOutgoingHits.Clear(); } ZNetView component = ((Component)attacker).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && !object.ReferenceEquals(component, null)) ? SafeGetZDO(component) : null); if (val == null) { return; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(val); if (cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic) { float num = hit.m_damage.m_blunt + hit.m_damage.m_slash + hit.m_damage.m_pierce; if (!(num <= 0.001f)) { string eventName = val.GetString(CataclysmicStateReader.SavedEventKey, ""); float fraction = (CataclysmicStateReader.IsUndead(val) ? 0.15f : 0.2f); ApplyElementalEventDamage(hit, eventName, num, fraction); } } } public static void ApplyIncomingCataclysmicEffects(Character target, HitData hit) { if ((Object)(object)target == (Object)null || hit == null) { return; } ZNetView component = ((Component)target).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && !object.ReferenceEquals(component, null)) ? SafeGetZDO(component) : null); if (val != null && CataclysmicStateReader.IsCataclysmic(val)) { string eventName = val.GetString(CataclysmicStateReader.SavedEventKey, ""); ApplyElementalEventResistance(hit, eventName); CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(val); if (cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic) { int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(val); bool flag = CataclysmicStateReader.IsUndead(val); float baseTierReduction = GetBaseTierReduction(effectiveBaseTier); float num = baseTierReduction + (flag ? 0.08f : 0f); float num2 = Mathf.Clamp01(num + 0.08f); float num3 = (1f - num2) / Mathf.Max(0.001f, 1f - num); hit.ApplyModifier(num3); } } } public static float GetBaseTierReduction(int tier) { return tier switch { 1 => 0.08f, 2 => 0.12f, 3 => 0.16f, 4 => 0.33f, 5 => 0.38f, 6 => 0.44f, 7 => 0.5f, 8 => 0.55f, 9 => 0.28f, 10 => 0.6f, _ => 0.08f, }; } private static ZDO SafeGetZDO(ZNetView view) { try { return view.IsValid() ? view.GetZDO() : null; } catch { return null; } } public static void ApplyElementalEventDamage(HitData hit, string eventName, float physDmg, float fraction = 0.15f) { if (hit != null && !(physDmg <= 0.001f)) { float num = physDmg * fraction; if (string.Equals(eventName, "Blizzard", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage = ref hit.m_damage; damage.m_frost += num; } else if (string.Equals(eventName, "Thunderstorm", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage2 = ref hit.m_damage; damage2.m_lightning += num; } else if (string.Equals(eventName, "ToxicFog", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage3 = ref hit.m_damage; damage3.m_poison += num; } else if (string.Equals(eventName, "MagicalAurora", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage4 = ref hit.m_damage; damage4.m_spirit += physDmg * 0.1f; } else { ref DamageTypes damage5 = ref hit.m_damage; damage5.m_fire += num; } } } public static void ApplyElementalEventResistance(HitData hit, string eventName) { if (hit != null) { if (string.Equals(eventName, "Blizzard", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage = ref hit.m_damage; damage.m_frost *= 0.5f; } else if (string.Equals(eventName, "Thunderstorm", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage2 = ref hit.m_damage; damage2.m_lightning *= 0.5f; } else if (string.Equals(eventName, "ToxicFog", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage3 = ref hit.m_damage; damage3.m_poison *= 0.5f; } else if (string.Equals(eventName, "MagicalAurora", StringComparison.OrdinalIgnoreCase)) { ref DamageTypes damage4 = ref hit.m_damage; damage4.m_spirit *= 0.5f; } else { ref DamageTypes damage5 = ref hit.m_damage; damage5.m_fire *= 0.5f; } } } public static float ComputeEffectiveDamageReduction(int baseTier, bool isCataclysmic, bool isUndead, bool isTamed) { float num = 0.08f; num = baseTier switch { 1 => 0.08f, 2 => 0.12f, 3 => 0.16f, 4 => 0.33f, 5 => 0.38f, 6 => 0.44f, 7 => 0.5f, 8 => 0.55f, 9 => 0.28f, 10 => 0.6f, _ => 0.08f, }; if (baseTier == 9) { float num2 = num; if (isUndead) { num2 += (isTamed ? 0.08f : 0.1f); } return Mathf.Clamp01(num2); } float num3 = num; if (isCataclysmic) { num3 += 0.08f; } if (isUndead) { num3 += (isTamed ? 0.08f : 0.1f); } return Mathf.Clamp01(num3); } public static float ComputeCombinedMultiplier(float tierRed, float compMitigation) { float num = Mathf.Clamp01(1f - tierRed); float num2 = Mathf.Clamp01(1f - compMitigation); return num * num2; } public static float ComputePhysicalCorrectionFactor(float combinedTierRed, int defPoints, float mmoBonus, float equippedArmor, bool isUndead, bool isTamed) { return UndeadMitigationCap.ComputePhysicalCorrectionFactor(combinedTierRed, defPoints, mmoBonus, equippedArmor, isTamed, isUndead); } } public sealed class HarmonizationSimulationReport { public bool IsValid { get; set; } public string ErrorMessage { get; set; } public CataclysmicClassification OriginalClassification { get; set; } public bool IsUndead { get; set; } public string EventName { get; set; } public string EventDisplayName { get; set; } public int CurrentLegacyTier { get; set; } public int TargetBiologicalTier { get; set; } public string TargetTierName { get; set; } public float NativeBaseHealth { get; set; } public int WildLevel { get; set; } public int RpgHealthPoints { get; set; } public float CurrentHealthMult { get; set; } public float CurrentDamageMult { get; set; } public float CurrentTierReduction { get; set; } public float CurrentSpeedMult { get; set; } public float CurrentEstimatedMaxHp { get; set; } public float ProjectedHealthMult { get; set; } public float ProjectedDamageMult { get; set; } public float ProjectedTierReduction { get; set; } public float ProjectedSpeedMult { get; set; } public float ProjectedEstimatedMaxHp { get; set; } public float DeltaHealthMult => ProjectedHealthMult - CurrentHealthMult; public float DeltaDamageMult => ProjectedDamageMult - CurrentDamageMult; public float DeltaTierReduction => ProjectedTierReduction - CurrentTierReduction; public float DeltaSpeedMult => ProjectedSpeedMult - CurrentSpeedMult; public float DeltaEstimatedMaxHp => ProjectedEstimatedMaxHp - CurrentEstimatedMaxHp; public bool TriggersP05CapNoArmor { get; set; } public bool TriggersP05CapWithArmor { get; set; } public float EffectivePhysicalMitigationNoArmor { get; set; } public float EffectivePhysicalMitigationWithArmor { get; set; } public string EpistemicNotice { get; set; } public bool StarsPreserved { get; set; } public bool ExperiencePreserved { get; set; } public bool RpgStatsPreserved { get; set; } public bool SaddlebagsPreserved { get; set; } public bool CustomNamePreserved { get; set; } public bool MasteriesPreserved { get; set; } public bool CurrentHealthRatioPreserved { get; set; } public bool IsSimulationMode { get; set; } public bool LiveWriteExecuted { get; set; } public bool GuidPersistedDuringSimulation { get; set; } public bool HasAuthority { get; set; } public string FormatUserReadableReport() { if (!IsValid) { return "[ERROR EN RITUAL] " + (ErrorMessage ?? "Entrada inválida."); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("=== REPORTE DE SIMULACIÓN DE ARMONIZACIÓN CATACLÍSMICA ==="); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Estado Actual: {0} (Tier Legado {1})", OriginalClassification, CurrentLegacyTier)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Tier Base a Armonizar: {0} (Tier {1})", TargetTierName, TargetBiologicalTier)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Afinidad Elemental: {0} ({1})", EventDisplayName, EventName)); if (IsUndead) { stringBuilder.AppendLine("Estado No-Muerto: COEXISTE (Híbrido Cataclysmic + Undead)"); } stringBuilder.AppendLine(); stringBuilder.AppendLine("--- COMPARATIVA DE MULTIPLICADORES Y SALUD REAL ---"); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Salud Mult: x{0:F3} -> x{1:F3} (Delta: {2:+0.000;-0.000})", CurrentHealthMult, ProjectedHealthMult, DeltaHealthMult)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Salud Máx: {0:F0} HP -> {1:F0} HP (Delta: {2:+0;-0} HP)", CurrentEstimatedMaxHp, ProjectedEstimatedMaxHp, DeltaEstimatedMaxHp)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Daño: x{0:F2} -> x{1:F2} (Delta: {2:+0.00;-0.00})", CurrentDamageMult, ProjectedDamageMult, DeltaDamageMult)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Mitigación: {0:P0} -> {1:P0} (Delta: {2:+0.0%;-0.0%})", CurrentTierReduction, ProjectedTierReduction, DeltaTierReduction)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Velocidad: x{0:F3} -> x{1:F3} (Delta: {2:+0.000;-0.000})", CurrentSpeedMult, ProjectedSpeedMult, DeltaSpeedMult)); stringBuilder.AppendLine(); if (IsUndead) { stringBuilder.AppendLine("--- CONTROL DE TOPE FÍSICO P-05 (UNDEAD) ---"); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Mitigación Física Sin Alforjas: {0:P0} (Tope Máx: 75%) [Cap Activo: {1}]", EffectivePhysicalMitigationNoArmor, TriggersP05CapNoArmor ? "SÍ" : "NO")); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "Mitigación Física Con Alforjas: {0:P0} (Tope Máx: 80%) [Cap Activo: {1}]", EffectivePhysicalMitigationWithArmor, TriggersP05CapWithArmor ? "SÍ" : "NO")); stringBuilder.AppendLine(); } stringBuilder.AppendLine("--- GARANTÍAS DE PRESERVACIÓN 1:1 ---"); stringBuilder.AppendLine(string.Format("- Estrellas (Nivel salvaje): {0}", StarsPreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(string.Format("- Nivel y XP de Compañero: {0}", ExperiencePreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(string.Format("- Atributos RPG Asignados: {0}", RpgStatsPreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(string.Format("- Alforjas e Inventario: {0}", SaddlebagsPreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(string.Format("- Nombre y Vínculo: {0}", CustomNamePreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(string.Format("- Maestrías y Pasivas: {0}", MasteriesPreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(string.Format("- Ratio de Salud Actual (%): {0}", CurrentHealthRatioPreserved ? "PRESERVADO 100%" : "ALERTA")); stringBuilder.AppendLine(); stringBuilder.AppendLine("--- ADVERTENCIA EPISTÉMICA ---"); stringBuilder.AppendLine(EpistemicNotice); stringBuilder.AppendLine(); stringBuilder.AppendLine(string.Format("MODO: {0} | ESCRITURA EN ZDO: {1}", IsSimulationMode ? "SIMULACIÓN ESTRICTA (DRY-RUN)" : "EN VIVO", LiveWriteExecuted ? "EJECUTADA" : "BLOQUEADA (0 ESCRITURAS)")); stringBuilder.AppendLine("=========================================================="); return stringBuilder.ToString(); } } public sealed class PendingRitualTicket { public string TicketId { get; set; } public long WorldUid { get; set; } public string CompanionGuid { get; set; } public int PrefabHash { get; set; } public int TargetBiologicalTier { get; set; } public string PreStateSha256 { get; set; } public string RequestingPlayerId { get; set; } public DateTime CreatedAtUtc { get; set; } public DateTime ExpiresAtUtc { get; set; } public bool IsConsumed { get; set; } public HarmonizationSimulationReport SimulationReport { get; set; } public bool IsValidAndActive(DateTime nowUtc) { if (!IsConsumed) { return nowUtc <= ExpiresAtUtc; } return false; } } public static class CataclysmicHarmonizationRitual { public const string StandardEpistemicDisclaimer = "Aviso de Linaje: Esta armonización representa una elección de invocación del jugador, no la reconstrucción de un registro histórico demostrado. Los guardados legados 0.7.52/0.7.53 consolidaban a la criatura en Tier 9 sin conservar el tier biológico previo a la tormenta."; private static bool s_reflectionInitialized = false; private static MethodInfo s_coreHealthMultMethod; private static MethodInfo s_coreDamageMultMethod; private static MethodInfo s_coreReductionMethod; private static MethodInfo s_coreSpeedMultMethod; private static Type s_creatureTierEnumType; public static bool StrictSimulationOnly { get { return true; } set { } } private static void EnsureCoreEngineBindings() { if (s_reflectionInitialized) { return; } s_reflectionInitialized = true; try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (assembly == null) { continue; } string name = assembly.GetName().Name; if (string.Equals(name, "TameMate", StringComparison.OrdinalIgnoreCase)) { Type type = assembly.GetType("TameMate.SupremeTierEngine", throwOnError: false); s_creatureTierEnumType = assembly.GetType("TameMate.CreatureTier", throwOnError: false); if (type != null && s_creatureTierEnumType != null) { s_coreHealthMultMethod = type.GetMethod("GetTierHealthMultiplier", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { s_creatureTierEnumType }, null); s_coreDamageMultMethod = type.GetMethod("GetTierDamageMultiplier", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { s_creatureTierEnumType }, null); s_coreReductionMethod = type.GetMethod("GetTierDamageReduction", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { s_creatureTierEnumType }, null); s_coreSpeedMultMethod = type.GetMethod("GetTierSpeedMultiplier", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { s_creatureTierEnumType }, null); } break; } } } catch { } } public static HarmonizationSimulationReport SimulateHarmonization(IZdoPropertyReader reader, int targetBaseTier, bool hasWriteAuthority = true, float nativeBaseHealth = 1000f) { HarmonizationSimulationReport harmonizationSimulationReport = new HarmonizationSimulationReport(); harmonizationSimulationReport.IsSimulationMode = true; harmonizationSimulationReport.LiveWriteExecuted = false; harmonizationSimulationReport.GuidPersistedDuringSimulation = false; harmonizationSimulationReport.HasAuthority = hasWriteAuthority; harmonizationSimulationReport.EpistemicNotice = "Aviso de Linaje: Esta armonización representa una elección de invocación del jugador, no la reconstrucción de un registro histórico demostrado. Los guardados legados 0.7.52/0.7.53 consolidaban a la criatura en Tier 9 sin conservar el tier biológico previo a la tormenta."; HarmonizationSimulationReport harmonizationSimulationReport2 = harmonizationSimulationReport; if (reader == null) { harmonizationSimulationReport2.IsValid = false; harmonizationSimulationReport2.ErrorMessage = "ZDO nulo o inválido."; return harmonizationSimulationReport2; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(reader); if (cataclysmicClassification != CataclysmicClassification.LegacyAmbiguous && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguousUndead) { harmonizationSimulationReport2.IsValid = false; harmonizationSimulationReport2.ErrorMessage = $"La criatura no es un Cataclysmic legado apto para armonización (Clasificación: {cataclysmicClassification})."; return harmonizationSimulationReport2; } if (targetBaseTier < 1 || targetBaseTier > 10 || targetBaseTier == 9) { harmonizationSimulationReport2.IsValid = false; harmonizationSimulationReport2.ErrorMessage = $"El tier destino {targetBaseTier} no es un tier biológico válido para armonización."; return harmonizationSimulationReport2; } bool flag = CataclysmicStateReader.IsUndead(reader); string eventName = reader.GetString(CataclysmicStateReader.SavedEventKey); int num = Math.Max(1, reader.GetInt(CataclysmicStateReader.WildLevelKey, 3)); int num2 = Math.Max(0, reader.GetInt(CataclysmicStateReader.StatHealthKey)); float num3 = ((nativeBaseHealth > 0f) ? nativeBaseHealth : 1000f); harmonizationSimulationReport2.IsValid = true; harmonizationSimulationReport2.OriginalClassification = cataclysmicClassification; harmonizationSimulationReport2.IsUndead = flag; harmonizationSimulationReport2.EventName = eventName; harmonizationSimulationReport2.EventDisplayName = CataclysmicHudFormatter.GetEventDisplayName(eventName); harmonizationSimulationReport2.CurrentLegacyTier = 9; harmonizationSimulationReport2.TargetBiologicalTier = targetBaseTier; harmonizationSimulationReport2.TargetTierName = CataclysmicHudFormatter.GetTierName(targetBaseTier); harmonizationSimulationReport2.NativeBaseHealth = num3; harmonizationSimulationReport2.WildLevel = num; harmonizationSimulationReport2.RpgHealthPoints = num2; float num4 = ComputeTamedSpecialTierStat(2f, 9, flag, 0); float currentDamageMult = ComputeTamedSpecialTierStat(1.85f, 9, flag, 1); float currentTierReduction = ComputeTamedSpecialTierStat(0.25f, 9, flag, 2); float currentSpeedMult = ComputeTamedSpecialTierStat(1.2f, 9, flag, 3); harmonizationSimulationReport2.CurrentHealthMult = num4; harmonizationSimulationReport2.CurrentDamageMult = currentDamageMult; harmonizationSimulationReport2.CurrentTierReduction = currentTierReduction; harmonizationSimulationReport2.CurrentSpeedMult = currentSpeedMult; harmonizationSimulationReport2.CurrentEstimatedMaxHp = num3 * (float)num * num4 * (1f + (float)num2 * 0.05f); float biologicalTierHealthMultiplier = GetBiologicalTierHealthMultiplier(targetBaseTier); float biologicalTierDamageMultiplier = GetBiologicalTierDamageMultiplier(targetBaseTier); float biologicalTierReduction = GetBiologicalTierReduction(targetBaseTier); float biologicalTierSpeedMultiplier = GetBiologicalTierSpeedMultiplier(targetBaseTier); float num5 = ComputeTamedSpecialTierStat(biologicalTierHealthMultiplier, targetBaseTier, flag, 0); float projectedDamageMult = ComputeTamedSpecialTierStat(biologicalTierDamageMultiplier, targetBaseTier, flag, 1); float num6 = ComputeTamedSpecialTierStat(biologicalTierReduction, targetBaseTier, flag, 2); float projectedSpeedMult = ComputeTamedSpecialTierStat(biologicalTierSpeedMultiplier, targetBaseTier, flag, 3); float projectedTierReduction = Mathf.Clamp01(num6 + 0.08f); harmonizationSimulationReport2.ProjectedHealthMult = num5; harmonizationSimulationReport2.ProjectedDamageMult = projectedDamageMult; harmonizationSimulationReport2.ProjectedTierReduction = projectedTierReduction; harmonizationSimulationReport2.ProjectedSpeedMult = projectedSpeedMult; harmonizationSimulationReport2.ProjectedEstimatedMaxHp = num3 * (float)num * num5 * (1f + (float)num2 * 0.05f); if (flag) { harmonizationSimulationReport2.TriggersP05CapNoArmor = harmonizationSimulationReport2.ProjectedTierReduction > 0.75f; harmonizationSimulationReport2.EffectivePhysicalMitigationNoArmor = Mathf.Min(0.75f, harmonizationSimulationReport2.ProjectedTierReduction); float num7 = 1f - (1f - harmonizationSimulationReport2.ProjectedTierReduction) * 0.9f; harmonizationSimulationReport2.TriggersP05CapWithArmor = num7 > 0.8f; harmonizationSimulationReport2.EffectivePhysicalMitigationWithArmor = Mathf.Min(0.8f, num7); } else { harmonizationSimulationReport2.TriggersP05CapNoArmor = false; harmonizationSimulationReport2.TriggersP05CapWithArmor = false; harmonizationSimulationReport2.EffectivePhysicalMitigationNoArmor = harmonizationSimulationReport2.ProjectedTierReduction; harmonizationSimulationReport2.EffectivePhysicalMitigationWithArmor = harmonizationSimulationReport2.ProjectedTierReduction; } harmonizationSimulationReport2.StarsPreserved = true; harmonizationSimulationReport2.ExperiencePreserved = true; harmonizationSimulationReport2.RpgStatsPreserved = true; harmonizationSimulationReport2.SaddlebagsPreserved = true; harmonizationSimulationReport2.CustomNamePreserved = true; harmonizationSimulationReport2.MasteriesPreserved = true; harmonizationSimulationReport2.CurrentHealthRatioPreserved = true; return harmonizationSimulationReport2; } public static float ComputeTamedSpecialTierStat(float original, int tier, bool undead, int kind) { if (tier != 9 && !undead) { return original; } float num = original; if (tier == 9) { num = kind switch { 2 => 0.28f, 1 => 1.92f, 0 => 2.4f, _ => 1.2f, }; } if (undead) { num = kind switch { 2 => Math.Min(0.7f, num + 0.08f), 1 => num * 1.25f, 0 => num * 1.35f, _ => num * 1.06f, }; } return num; } public static PendingRitualTicket PrepareHarmonizationTicket(IZdoPropertyReader reader, int targetBaseTier, string requestingPlayerId, long worldUid, int prefabHash, float nativeBaseHealth = 1000f, bool hasWriteAuthority = true) { if (reader == null) { return null; } HarmonizationSimulationReport harmonizationSimulationReport = SimulateHarmonization(reader, targetBaseTier, hasWriteAuthority, nativeBaseHealth); ISyntheticZdoPropertyWriter syntheticZdoPropertyWriter = reader as ISyntheticZdoPropertyWriter; if (syntheticZdoPropertyWriter != null && syntheticZdoPropertyWriter.IsBoss) { harmonizationSimulationReport.IsValid = false; harmonizationSimulationReport.ErrorMessage = "Operación bloqueada en criaturas tipo jefe (Boss)."; } else if ((syntheticZdoPropertyWriter != null && !syntheticZdoPropertyWriter.IsTamed) || reader.GetInt(CataclysmicStateReader.TamedBoolKey, 1) == 0) { harmonizationSimulationReport.IsValid = false; harmonizationSimulationReport.ErrorMessage = "Operación bloqueada en criaturas salvajes (no domesticadas)."; } else { string text = reader.GetString(CataclysmicStateReader.OwnerIdKey, string.Empty); if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(requestingPlayerId) && !string.Equals(text, requestingPlayerId, StringComparison.OrdinalIgnoreCase)) { harmonizationSimulationReport.IsValid = false; harmonizationSimulationReport.ErrorMessage = "El jugador solicitante no tiene permisos de propietario sobre el compañero."; } } CompanionZdoSnapshot companionZdoSnapshot = CompanionZdoSnapshot.CreateFromReader(reader, worldUid, 0L, 0u, prefabHash); string preStateSha = ((companionZdoSnapshot != null) ? companionZdoSnapshot.ComputeSessionIndependentContentSha256() : string.Empty); string text2 = reader.GetString(CataclysmicStateReader.CompanionGuidKey, string.Empty); if (!CataclysmicStateReader.IsValidCompanionGuid(text2)) { text2 = CataclysmicStateReader.GenerateCompanionGuid(); } DateTime utcNow = DateTime.UtcNow; PendingRitualTicket pendingRitualTicket = new PendingRitualTicket(); pendingRitualTicket.TicketId = "TKT_" + Guid.NewGuid().ToString("N").Substring(0, 16); pendingRitualTicket.WorldUid = worldUid; pendingRitualTicket.CompanionGuid = text2; pendingRitualTicket.PrefabHash = prefabHash; pendingRitualTicket.TargetBiologicalTier = targetBaseTier; pendingRitualTicket.PreStateSha256 = preStateSha; pendingRitualTicket.RequestingPlayerId = requestingPlayerId ?? string.Empty; pendingRitualTicket.CreatedAtUtc = utcNow; pendingRitualTicket.ExpiresAtUtc = utcNow.AddSeconds(60.0); pendingRitualTicket.IsConsumed = false; pendingRitualTicket.SimulationReport = harmonizationSimulationReport; return pendingRitualTicket; } public static bool TryExecuteHarmonization(IZdoPropertyReader reader, int targetBaseTier, out HarmonizationSimulationReport report, out string statusMessage) { return TryExecuteHarmonization(reader, targetBaseTier, hasWriteAuthority: true, 1000f, out report, out statusMessage); } public static bool TryExecuteHarmonization(IZdoPropertyReader reader, int targetBaseTier, bool hasWriteAuthority, float nativeBaseHealth, out HarmonizationSimulationReport report, out string statusMessage) { report = SimulateHarmonization(reader, targetBaseTier, hasWriteAuthority, nativeBaseHealth); if (!report.IsValid) { statusMessage = report.ErrorMessage; return false; } statusMessage = "[SIMULACIÓN ACTIVA] El ritual operó en modo simulación dry-run (Etapa 4B-2B.1). No se realizaron escrituras en ZDO ni en disco."; return true; } public static bool TryConfirmHarmonization(IZdoPropertyReader reader, int targetBaseTier, out string statusMessage) { statusMessage = "[BLOQUEADO EN 4B-2B.1] Confirm sobre ZDO real de Valheim deshabilitado hasta la Etapa 4B-2B.2 (0 escrituras realizadas)."; return false; } public static bool TryCommitHarmonization(ZDO liveZdo, int targetBaseTier, out string statusMessage) { statusMessage = "[BLOQUEADO EN 4B-2B.1] Commit sobre ZDO real de Valheim deshabilitado hasta la Etapa 4B-2B.2 (0 escrituras realizadas)."; return false; } public static bool TryRollbackHarmonization(ZDO liveZdo, out string statusMessage) { statusMessage = "[BLOQUEADO EN 4B-2B.1] Rollback sobre ZDO real de Valheim deshabilitado hasta la Etapa 4B-2B.2 (0 escrituras realizadas)."; return false; } public static bool ConfirmAndExecuteSyntheticHarmonization(ISyntheticZdoPropertyWriter writer, PendingRitualTicket ticket, int confirmedTargetTier, string confirmingPlayerId, IEnumerable worldZdos, ZdoInspectionScope scope, bool hasWriteAuthority, out string statusMessage) { statusMessage = null; if (writer == null || !writer.IsSyntheticTestFixture) { statusMessage = "[BLOQUEADO EN 4B-2A] Solo se admiten fixtures de prueba sintéticos en 4B-2A. Operaciones sobre criaturas reales de Valheim deshabilitadas."; return false; } return BackupAndCommit(writer, ticket, confirmedTargetTier, confirmingPlayerId, worldZdos, scope, hasWriteAuthority, out statusMessage); } internal static bool BackupAndCommit(IRitualTransactionWriter writer, PendingRitualTicket ticket, int confirmedTargetTier, string confirmingPlayerId, IEnumerable worldZdos, ZdoInspectionScope scope, bool hasWriteAuthority, out string statusMessage) { statusMessage = null; RitualGuardedWriter ritualGuardedWriter = writer as RitualGuardedWriter; ISyntheticZdoPropertyWriter syntheticZdoPropertyWriter = writer as ISyntheticZdoPropertyWriter; if (ritualGuardedWriter == null && (syntheticZdoPropertyWriter == null || !syntheticZdoPropertyWriter.IsSyntheticTestFixture)) { statusMessage = "Transaction writer is not authorized."; return false; } ritualGuardedWriter?.Checkpoint(); if (ticket == null) { statusMessage = "Fallo de confirmación: ticket de ritual nulo o no preparado previamente."; return false; } if (ticket.IsConsumed) { statusMessage = "Fallo de confirmación: el ticket de ritual ya fue consumido o invalidado previamente (uso único)."; return false; } ticket.IsConsumed = true; if (DateTime.UtcNow > ticket.ExpiresAtUtc) { statusMessage = string.Format(CultureInfo.InvariantCulture, "Fallo de confirmación: el ticket de ritual ha expirado (expiró en {0:o}, actual {1:o}).", ticket.ExpiresAtUtc, DateTime.UtcNow); return false; } if (confirmedTargetTier != ticket.TargetBiologicalTier) { statusMessage = string.Format(CultureInfo.InvariantCulture, "Discrepancia de tier: el tier confirmado ({0}) difiere del tier preparado en el ticket ({1}).", confirmedTargetTier, ticket.TargetBiologicalTier); return false; } if (!string.Equals(confirmingPlayerId, ticket.RequestingPlayerId, StringComparison.OrdinalIgnoreCase)) { statusMessage = string.Format(CultureInfo.InvariantCulture, "Discrepancia de jugador: el confirmante '{0}' no coincide con el solicitante '{1}'.", confirmingPlayerId, ticket.RequestingPlayerId); return false; } if (!hasWriteAuthority) { statusMessage = "Fallo de confirmación: pérdida de autoridad de red (hasWriteAuthority == false)."; return false; } if (writer.IsBoss) { statusMessage = "Operación bloqueada en criaturas tipo jefe."; return false; } if (!writer.IsTamed || writer.GetInt(CataclysmicStateReader.TamedBoolKey, 1) == 0) { statusMessage = "Operación bloqueada en criaturas no domesticadas (salvajes)."; return false; } string text = writer.GetString(CataclysmicStateReader.OwnerIdKey, string.Empty); if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(confirmingPlayerId) && !string.Equals(text, confirmingPlayerId, StringComparison.OrdinalIgnoreCase)) { statusMessage = "Operación bloqueada: el jugador confirmante no tiene permisos de propietario sobre el compañero."; return false; } long num = writer.GetLong(CataclysmicStateReader.CompanionWorldUidKey, 0L); if (num != 0 && num != ticket.WorldUid) { statusMessage = string.Format(CultureInfo.InvariantCulture, "Discrepancia de WorldUid: el ZDO registra {0}, pero el ticket corresponde a {1}.", num, ticket.WorldUid); return false; } CompanionZdoSnapshot companionZdoSnapshot = CompanionZdoSnapshot.CreateFromReader(writer, ticket.WorldUid, 0L, 0u, ticket.PrefabHash); string text2 = companionZdoSnapshot.ComputeSessionIndependentContentSha256(); if (!string.Equals(text2, ticket.PreStateSha256, StringComparison.OrdinalIgnoreCase)) { statusMessage = string.Format(CultureInfo.InvariantCulture, "Discrepancia de estado pre-ritual: el hash actual ({0}) difiere del hash preparado ({1}). El estado fue modificado antes de confirmar.", text2, ticket.PreStateSha256); return false; } string text3 = writer.GetString(CataclysmicStateReader.CompanionGuidKey, string.Empty); if (!CataclysmicStateReader.IsValidCompanionGuid(text3)) { text3 = ticket.CompanionGuid; if (!CataclysmicStateReader.IsValidCompanionGuid(text3)) { text3 = CataclysmicStateReader.GenerateCompanionGuid(); } writer.SetString(CataclysmicStateReader.CompanionGuidKey, text3); writer.SetLong(CataclysmicStateReader.CompanionWorldUidKey, ticket.WorldUid); writer.SetInt(CataclysmicStateReader.CompanionPrefabHashKey, ticket.PrefabHash); } CompanionIdentityResolution companionIdentityResolution = CataclysmicStateReader.ResolveCompanionIdentity(text3, ticket.WorldUid, ticket.PrefabHash, worldZdos, scope); if (!companionIdentityResolution.IsUnambiguousAndSafe || !companionIdentityResolution.IsGlobalUniquenessProven) { statusMessage = "Fallo de validación de identidad y alcance: " + (companionIdentityResolution.FailureReason ?? "Identidad ambigua o alcance no verificado."); return false; } CompanionZdoSnapshot companionZdoSnapshot2 = CompanionZdoSnapshot.CreateFromReader(writer, ticket.WorldUid, 0L, 0u, ticket.PrefabHash); string outPath; string statusMessage2; WriteOnceBackupStatus writeOnceBackupStatus = CompanionPersistentBackup.SaveLegacyOriginBackupWriteOnce(companionZdoSnapshot2, "RitualHarmonization_4B2A", out outPath, out statusMessage2); if (writeOnceBackupStatus != WriteOnceBackupStatus.CreatedNewVerified && writeOnceBackupStatus != WriteOnceBackupStatus.AlreadyExistsVerified) { statusMessage = "Fallo crítico al crear/verificar el respaldo Write-Once legacy_origin: " + statusMessage2; return false; } string legacyOriginSha = companionZdoSnapshot2.ComputeSessionIndependentContentSha256(); if (ritualGuardedWriter != null) { string error; CompanionZdoSnapshot companionZdoSnapshot3 = CompanionPersistentBackup.LoadLegacyOriginBackup(ticket.WorldUid, text3, ticket.PrefabHash, out error); if (companionZdoSnapshot3 == null) { statusMessage = error; return false; } legacyOriginSha = companionZdoSnapshot3.ComputeSessionIndependentContentSha256(); } RitualTransactionJournal ritualTransactionJournal = new RitualTransactionJournal(); ritualTransactionJournal.TransactionId = ticket.TicketId; ritualTransactionJournal.WorldUid = ticket.WorldUid; ritualTransactionJournal.CompanionGuid = text3; ritualTransactionJournal.PrefabHash = ticket.PrefabHash; ritualTransactionJournal.TargetBaseTier = confirmedTargetTier; ritualTransactionJournal.State = RitualJournalState.BackupVerified; ritualTransactionJournal.LegacyOriginSha256 = legacyOriginSha; ritualTransactionJournal.PreStateSha256 = ticket.PreStateSha256; ritualTransactionJournal.TimestampUtc = DateTime.UtcNow.ToString("o"); RitualTransactionJournal ritualTransactionJournal2 = ritualTransactionJournal; ritualGuardedWriter?.Checkpoint(); if (!CompanionPersistentBackup.SaveJournal(ritualTransactionJournal2, out var outPath2, out var error2)) { statusMessage = "Fallo al guardar journal BackupVerified: " + error2; return false; } if (writer.MidWriteFaultInjector != null) { writer.MidWriteFaultInjector(1, "PreMutationFault"); } ritualTransactionJournal2.State = RitualJournalState.ZdoMutating; ritualGuardedWriter?.Checkpoint(); if (!CompanionPersistentBackup.SaveJournal(ritualTransactionJournal2, out outPath2, out error2)) { statusMessage = "Fallo al actualizar journal a ZdoMutating: " + error2; return false; } writer.SetInt(CataclysmicStateReader.RitualTxStateKey, 1); if (writer.MidWriteFaultInjector != null) { writer.MidWriteFaultInjector(2, "MidMutationFault"); } writer.SetInt(CataclysmicStateReader.SavedTierKey, confirmedTargetTier); writer.SetInt(CataclysmicStateReader.TierOverrideKey, confirmedTargetTier); writer.SetInt(CataclysmicStateReader.IsCataclysmicKey, 1); writer.SetString(CataclysmicStateReader.RitualTxIdKey, ticket.TicketId); writer.SetInt(CataclysmicStateReader.HarmonizedFromLegacyKey, 1); writer.SetInt(CataclysmicStateReader.HarmonizedTargetTierKey, confirmedTargetTier); writer.SetString(CataclysmicStateReader.HarmonizedTimestampKey, DateTime.UtcNow.ToString("o")); writer.SetInt(CataclysmicStateReader.RitualTxStateKey, 2); float num2; if (ritualGuardedWriter != null) { ritualGuardedWriter.RefreshDerivedState(); num2 = ritualGuardedWriter.EffectiveMaxHealth; if (float.IsNaN(num2) || float.IsInfinity(num2) || Math.Abs(num2 - ticket.SimulationReport.ProjectedEstimatedMaxHp) > 0.5f) { statusMessage = "El recálculo nativo no coincide con la proyección; cuarentena."; return false; } } else { writer.SetInt(CataclysmicStateReader.TierHpInitKey, 1); bool flag = CataclysmicStateReader.IsUndead((IZdoPropertyReader)writer); int value = ((flag || confirmedTargetTier == 9) ? (10100 + confirmedTargetTier + (flag ? 1000 : 0)) : 0); writer.SetInt(CataclysmicStateReader.SpecialProfileKey, value); float num3 = ((writer.NativeBaseHealth > 0f) ? writer.NativeBaseHealth : 1000f); int num4 = Math.Max(1, writer.GetInt(CataclysmicStateReader.WildLevelKey, 3)); int num5 = Math.Max(0, writer.GetInt(CataclysmicStateReader.StatHealthKey)); float num6 = writer.GetFloat(CataclysmicStateReader.MaxHealthKey); float num7 = writer.GetFloat(CataclysmicStateReader.HealthKey, num6); float num8 = ((num6 > 0f) ? Mathf.Clamp01(num7 / num6) : 1f); float num9 = ComputeTamedSpecialTierStat(GetBiologicalTierHealthMultiplier(confirmedTargetTier), confirmedTargetTier, flag, 0); num2 = num3 * (float)num4 * num9 * (1f + (float)num5 * 0.05f); writer.SetFloat(CataclysmicStateReader.MaxHealthKey, num2); writer.SetFloat(CataclysmicStateReader.HealthKey, Mathf.Clamp(num2 * num8, 1f, num2)); } CompanionZdoSnapshot companionZdoSnapshot4 = CompanionZdoSnapshot.CreateFromReader(writer, ticket.WorldUid, 0L, 0u, ticket.PrefabHash); if (!CataclysmicStateReader.VerifySubsetCUnchanged(companionZdoSnapshot2, companionZdoSnapshot4, out var diffReason)) { statusMessage = "Violación de integridad: Subconjunto C modificado durante la armonización: " + diffReason; return false; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify((IZdoPropertyReader)writer); int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier((IZdoPropertyReader)writer); if (cataclysmicClassification != CataclysmicClassification.DecoupledCataclysmic || effectiveBaseTier != confirmedTargetTier) { statusMessage = string.Format(CultureInfo.InvariantCulture, "Fallo de post-verificación: estado esperado DecoupledCataclysmic Tier {0}, pero se obtuvo {1} Tier {2}.", confirmedTargetTier, cataclysmicClassification, effectiveBaseTier); return false; } ritualTransactionJournal2.State = ((ritualGuardedWriter != null) ? RitualJournalState.CommittedInMemory : RitualJournalState.Committed); ritualTransactionJournal2.PostStateSha256 = companionZdoSnapshot4.ComputeSessionIndependentContentSha256(); ritualGuardedWriter?.Checkpoint(); if (!CompanionPersistentBackup.SaveJournal(ritualTransactionJournal2, out outPath2, out error2)) { statusMessage = "Fallo al finalizar journal a Committed: " + error2; return false; } statusMessage = string.Format(CultureInfo.InvariantCulture, "Armonización sintética exitosa: compañero GUID={0} armonizado a DecoupledCataclysmic Tier {1} ({2:F0} HP). Subconjunto C 100% preservado.", text3, confirmedTargetTier, num2); return true; } public static bool RollbackLineageOnlySynthetic(ISyntheticZdoPropertyWriter writer, long worldUid, int prefabHash, IEnumerable worldZdos, ZdoInspectionScope scope, string requestingPlayerId, bool hasWriteAuthority, out string statusMessage) { statusMessage = null; if (writer == null || !writer.IsSyntheticTestFixture) { statusMessage = "[BLOQUEADO EN 4B-2A] Solo se admiten fixtures sintéticos en 4B-2A."; return false; } return RollbackLineageOnly(writer, worldUid, prefabHash, worldZdos, scope, requestingPlayerId, hasWriteAuthority, out statusMessage); } internal static bool RollbackLineageOnly(IRitualTransactionWriter writer, long worldUid, int prefabHash, IEnumerable worldZdos, ZdoInspectionScope scope, string requestingPlayerId, bool hasWriteAuthority, out string statusMessage) { statusMessage = null; RitualGuardedWriter ritualGuardedWriter = writer as RitualGuardedWriter; ISyntheticZdoPropertyWriter syntheticZdoPropertyWriter = writer as ISyntheticZdoPropertyWriter; if (ritualGuardedWriter == null && (syntheticZdoPropertyWriter == null || !syntheticZdoPropertyWriter.IsSyntheticTestFixture)) { statusMessage = "Transaction writer is not authorized."; return false; } ritualGuardedWriter?.Checkpoint(); if (!hasWriteAuthority) { statusMessage = "Rollback abortado: falta de autoridad de red (hasWriteAuthority == false)."; return false; } string text = writer.GetString(CataclysmicStateReader.OwnerIdKey, string.Empty); if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(requestingPlayerId) && !string.Equals(text, requestingPlayerId, StringComparison.OrdinalIgnoreCase)) { statusMessage = "Rollback abortado: el jugador no es el propietario del compañero."; return false; } string text2 = writer.GetString(CataclysmicStateReader.CompanionGuidKey, string.Empty); CompanionIdentityResolution companionIdentityResolution = CataclysmicStateReader.ResolveCompanionIdentity(text2, worldUid, prefabHash, worldZdos, scope); if (!companionIdentityResolution.IsUnambiguousAndSafe || !companionIdentityResolution.IsGlobalUniquenessProven) { statusMessage = "Rollback bloqueado por validación de identidad/alcance: " + (companionIdentityResolution.FailureReason ?? "Identidad no probada."); return false; } string error; CompanionZdoSnapshot companionZdoSnapshot = CompanionPersistentBackup.LoadLegacyOriginBackup(worldUid, text2, prefabHash, out error); if (companionZdoSnapshot == null || !companionZdoSnapshot.VerifyIntegrity()) { statusMessage = "Rollback bloqueado: no se encontró respaldo legacy_origin íntegro: " + error; return false; } CompanionZdoSnapshot companionZdoSnapshot2 = CompanionZdoSnapshot.CreateFromReader(writer, worldUid, 0L, 0u, prefabHash); string error2; RitualTransactionJournal ritualTransactionJournal = CompanionPersistentBackup.LoadJournal(worldUid, text2, out error2); if (ritualTransactionJournal == null) { RitualTransactionJournal ritualTransactionJournal2 = new RitualTransactionJournal(); ritualTransactionJournal2.TransactionId = "RBK_" + Guid.NewGuid().ToString("N").Substring(0, 16); ritualTransactionJournal2.WorldUid = worldUid; ritualTransactionJournal2.CompanionGuid = text2; ritualTransactionJournal2.PrefabHash = prefabHash; ritualTransactionJournal = ritualTransactionJournal2; } RitualTransactionJournal ritualTransactionJournal3 = ritualTransactionJournal; ritualTransactionJournal3.State = RitualJournalState.RecoveringLineage; if (ritualGuardedWriter != null) { ritualTransactionJournal3.TransactionId = ritualGuardedWriter.TransactionId; ritualTransactionJournal3.TargetBaseTier = 9; ritualTransactionJournal3.PreStateSha256 = companionZdoSnapshot2.ComputeSessionIndependentContentSha256(); ritualTransactionJournal3.LegacyOriginSha256 = companionZdoSnapshot.ComputeSessionIndependentContentSha256(); ritualTransactionJournal3.PostStateSha256 = string.Empty; } ritualGuardedWriter?.Checkpoint(); if (!CompanionPersistentBackup.SaveJournal(ritualTransactionJournal3, out var outPath, out error2)) { statusMessage = error2; return false; } writer.SetInt(CataclysmicStateReader.RitualTxStateKey, 3); float num; if (ritualGuardedWriter != null) { ritualGuardedWriter.RestoreOriginalLineage(companionZdoSnapshot); ritualGuardedWriter.RefreshDerivedState(); num = ritualGuardedWriter.EffectiveMaxHealth; } else { writer.SetInt(CataclysmicStateReader.SavedTierKey, 9); writer.SetInt(CataclysmicStateReader.TierOverrideKey, 9); writer.SetInt(CataclysmicStateReader.IsCataclysmicKey, 0); writer.SetInt(CataclysmicStateReader.RitualTxStateKey, 0); writer.SetInt(CataclysmicStateReader.HarmonizedFromLegacyKey, 0); writer.SetInt(CataclysmicStateReader.HarmonizedTargetTierKey, 0); writer.SetString(CataclysmicStateReader.HarmonizedTimestampKey, string.Empty); bool flag = CataclysmicStateReader.IsUndead((IZdoPropertyReader)writer); int value = 10109 + (flag ? 1000 : 0); writer.SetInt(CataclysmicStateReader.SpecialProfileKey, value); float num2 = ((writer.NativeBaseHealth > 0f) ? writer.NativeBaseHealth : 1000f); int num3 = Math.Max(1, writer.GetInt(CataclysmicStateReader.WildLevelKey, 3)); int num4 = Math.Max(0, writer.GetInt(CataclysmicStateReader.StatHealthKey)); float num5 = writer.GetFloat(CataclysmicStateReader.MaxHealthKey); float num6 = writer.GetFloat(CataclysmicStateReader.HealthKey, num5); float num7 = ((num5 > 0f) ? Mathf.Clamp01(num6 / num5) : 1f); float num8 = ComputeTamedSpecialTierStat(2f, 9, flag, 0); num = num2 * (float)num3 * num8 * (1f + (float)num4 * 0.05f); writer.SetFloat(CataclysmicStateReader.MaxHealthKey, num); writer.SetFloat(CataclysmicStateReader.HealthKey, Mathf.Clamp(num * num7, 1f, num)); } CompanionZdoSnapshot companionZdoSnapshot3 = CompanionZdoSnapshot.CreateFromReader(writer, worldUid, 0L, 0u, prefabHash); if (!CataclysmicStateReader.VerifySubsetCUnchanged(companionZdoSnapshot2, companionZdoSnapshot3, out var diffReason)) { statusMessage = "Violación de integridad durante rollback de linaje: Subconjunto C afectado: " + diffReason; return false; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify((IZdoPropertyReader)writer); if (cataclysmicClassification != CataclysmicClassification.LegacyAmbiguous && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguousUndead) { statusMessage = "Fallo post-rollback: clasificación no volvió a LegacyAmbiguous: " + cataclysmicClassification; return false; } ritualTransactionJournal3.State = ((ritualGuardedWriter != null) ? RitualJournalState.RolledBackInMemory : RitualJournalState.RecoveredToLegacy); if (ritualGuardedWriter != null) { ritualTransactionJournal3.PostStateSha256 = companionZdoSnapshot3.ComputeSessionIndependentContentSha256(); } ritualGuardedWriter?.Checkpoint(); if (!CompanionPersistentBackup.SaveJournal(ritualTransactionJournal3, out outPath, out error2)) { statusMessage = error2; return false; } statusMessage = string.Format(CultureInfo.InvariantCulture, "Rollback sintético de linaje completado exitosamente: criatura restaurada a Tier 9 Legado ({0:F0} HP). Alforjas (items byte[]) e historial preservados.", num); return true; } public static bool RecoverInterruptedSynthetic(ISyntheticZdoPropertyWriter writer, long worldUid, int prefabHash, IEnumerable worldZdos, ZdoInspectionScope scope, out string statusMessage) { statusMessage = null; if (writer == null || !writer.IsSyntheticTestFixture) { statusMessage = "[BLOQUEADO EN 4B-2A] Solo se admiten fixtures sintéticos en 4B-2A."; return false; } InterruptionDiagnosis interruptionDiagnosis = CompanionPersistentBackup.InspectInterruptedTransaction(writer, worldUid, prefabHash); if (!interruptionDiagnosis.IsInterrupted) { statusMessage = "No se detectó ninguna interrupción que requiera recuperación."; return true; } if (interruptionDiagnosis.ScenarioType == InterruptionScenarioType.InterruptedAfterCommitBeforeWorldSave) { statusMessage = "[RECUPERACIÓN NO REQUERIDA] La criatura ya está intacta en estado Legado en el guardado del mundo. Cero escrituras destructivas ejecutadas."; return true; } if (interruptionDiagnosis.ScenarioType == InterruptionScenarioType.InterruptedBeforeCommit) { statusMessage = "[RECUPERACIÓN NO REQUERIDA] La criatura no fue mutada en el ZDO. Permanece intacta en estado Legado."; return true; } if (interruptionDiagnosis.ScenarioType == InterruptionScenarioType.InterruptedDuringWrite || interruptionDiagnosis.ScenarioType == InterruptionScenarioType.InterruptedDuringRecovery) { if (!interruptionDiagnosis.CanSafelyRecoverLineage) { statusMessage = "Recuperación bloqueada: no se cuenta con un respaldo Write-Once legacy_origin íntegro y verificado."; return false; } return RollbackLineageOnlySynthetic(writer, worldUid, prefabHash, worldZdos, scope, string.Empty, hasWriteAuthority: true, out statusMessage); } statusMessage = "Escenario de interrupción no accionable: " + interruptionDiagnosis.ScenarioType; return false; } public static float GetBiologicalTierHealthMultiplier(int tier) { EnsureCoreEngineBindings(); if (s_coreHealthMultMethod != null && s_creatureTierEnumType != null) { try { object obj = Enum.ToObject(s_creatureTierEnumType, tier); return (float)s_coreHealthMultMethod.Invoke(null, new object[1] { obj }); } catch { } } return tier switch { 1 => 1f, 2 => 1.35f, 3 => 1.7f, 4 => 2.1f, 5 => 2.6f, 6 => 3.2f, 7 => 3.9f, 8 => 4.8f, 10 => 5.5f, _ => 1f, }; } public static float GetBiologicalTierDamageMultiplier(int tier) { EnsureCoreEngineBindings(); if (s_coreDamageMultMethod != null && s_creatureTierEnumType != null) { try { object obj = Enum.ToObject(s_creatureTierEnumType, tier); return (float)s_coreDamageMultMethod.Invoke(null, new object[1] { obj }); } catch { } } return tier switch { 1 => 1f, 2 => 1.25f, 3 => 1.5f, 4 => 1.75f, 5 => 2.1f, 6 => 2.5f, 7 => 3f, 8 => 3.6f, 10 => 4.5f, _ => 1f, }; } public static float GetBiologicalTierReduction(int tier) { EnsureCoreEngineBindings(); if (s_coreReductionMethod != null && s_creatureTierEnumType != null) { try { object obj = Enum.ToObject(s_creatureTierEnumType, tier); return (float)s_coreReductionMethod.Invoke(null, new object[1] { obj }); } catch { } } return tier switch { 1 => 0f, 2 => 0.1f, 3 => 0.18f, 4 => 0.25f, 5 => 0.32f, 6 => 0.38f, 7 => 0.44f, 8 => 0.5f, 10 => 0.6f, _ => 0f, }; } public static float GetBiologicalTierSpeedMultiplier(int tier) { EnsureCoreEngineBindings(); if (s_coreSpeedMultMethod != null && s_creatureTierEnumType != null) { try { object obj = Enum.ToObject(s_creatureTierEnumType, tier); return (float)s_coreSpeedMultMethod.Invoke(null, new object[1] { obj }); } catch { } } return tier switch { 1 => 1f, 2 => 1.1f, 3 => 1.18f, 4 => 1.25f, 5 => 1.32f, 6 => 1.38f, 7 => 1.45f, 8 => 1.5f, 10 => 1.4f, _ => 1f, }; } } public static class CataclysmicHudFormatter { private static bool s_installed = false; private static readonly string s_heartGlyph = "❤"; private static readonly string s_lightningGlyph = "⚡"; private static readonly string s_starGlyph = "★"; private static readonly string s_snowflakeGlyph = "❄"; private static readonly string s_linkGlyph = "\ud83d\udd17"; private static FieldInfo s_enemyHudsField; private static FieldInfo s_hudDataGuiField; private static Func s_isCommandWheelOpen; private static Action s_invalidateTier; private static Func s_getHealthMult; private static Func s_getDamageMult; private static Func s_getReductionMult; private static Func s_getSpeedMult; private static Action s_applyUndeadVisuals; private static MethodInfo s_ensureAuraMethod; private static MethodInfo s_refreshAuraMethod; private static Func s_getCurrentSeason; private static Func s_getMmoInstalled; private static Func s_getMmoPlayerLevel; private static Func s_getMmoDmgBonus; private static Func s_externalMountSupports; private static FieldInfo s_lastHoveredIdField; private static FieldInfo s_nextHoverComputeTimeField; private static FieldInfo s_lastUntamedHoveredIdField; private static FieldInfo s_nextUntamedHoverComputeTimeField; private static FieldInfo s_cachedHoverNameIdField; private static FieldInfo s_hoverNameCacheExpiryField; private static FieldInfo s_playerHoveringField; private static readonly int s_hpInitKey = StringExtensionMethods.GetStableHashCode("tm_tier_hp_init"); private static readonly int s_specialProfileKey = StringExtensionMethods.GetStableHashCode("TM_070_SpecialProfile"); private static readonly int s_eqChestKey = StringExtensionMethods.GetStableHashCode("tm_eq_chest"); private static readonly int s_statHealthKey = StringExtensionMethods.GetStableHashCode("tm_stat_health"); private static readonly int s_levelKey = StringExtensionMethods.GetStableHashCode("tm_level"); private static readonly int s_xpKey = StringExtensionMethods.GetStableHashCode("tm_xp"); private static readonly int s_pointsKey = StringExtensionMethods.GetStableHashCode("tm_points"); private static readonly int s_orderKey = StringExtensionMethods.GetStableHashCode("tm_order"); private static readonly int s_stanceKey = StringExtensionMethods.GetStableHashCode("tm_stance"); private static readonly int s_groupKey = StringExtensionMethods.GetStableHashCode("tm_group"); private static readonly int s_recoverUntilKey = StringExtensionMethods.GetStableHashCode("tm_recover_until"); private static readonly int s_necroFuryKey = StringExtensionMethods.GetStableHashCode("tm_buff_necro_fury"); private static readonly int s_spectralVeilKey = StringExtensionMethods.GetStableHashCode("tm_buff_spectral_veil"); private static readonly Dictionary s_liveStateSignatures = new Dictionary(); private static readonly Dictionary s_lastKnownCharacterLevels = new Dictionary(); private static bool s_isRefreshing = false; private static int s_lastObservedHoverId = 0; private static int s_lastObservedHoverCreatureId = 0; private static int s_cachedTargetCharacterId = 0; private static int s_cachedTargetZdoSig = 0; private static int s_cachedTargetHp = -1; private static int s_cachedTargetMaxHp = -1; private static int s_cachedTargetStamina = -1; private static bool s_cachedTargetAttached = false; private static float s_cachedTargetNextRefresh = 0f; private static string s_cachedTargetHoverText = null; public static void Install(Harmony harmony, Assembly coreAssembly) { //IL_0864: Unknown result type (might be due to invalid IL or missing references) //IL_0871: Expected O, but got Unknown //IL_079e: Unknown result type (might be due to invalid IL or missing references) //IL_07ab: Expected O, but got Unknown //IL_08cc: Unknown result type (might be due to invalid IL or missing references) //IL_08da: Expected O, but got Unknown //IL_07fb: Unknown result type (might be due to invalid IL or missing references) //IL_0808: Expected O, but got Unknown //IL_091a: Unknown result type (might be due to invalid IL or missing references) //IL_0927: Expected O, but got Unknown //IL_03e7: Unknown result type (might be due to invalid IL or missing references) //IL_03f4: Expected O, but got Unknown //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Expected O, but got Unknown //IL_097f: Unknown result type (might be due to invalid IL or missing references) //IL_098c: Expected O, but got Unknown //IL_09e4: Unknown result type (might be due to invalid IL or missing references) //IL_09f1: Expected O, but got Unknown //IL_0a80: Unknown result type (might be due to invalid IL or missing references) //IL_0a8d: Expected O, but got Unknown //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Expected O, but got Unknown //IL_0aef: Unknown result type (might be due to invalid IL or missing references) //IL_0afc: Expected O, but got Unknown //IL_0280: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Expected O, but got Unknown //IL_0b4b: Unknown result type (might be due to invalid IL or missing references) //IL_0b58: Expected O, but got Unknown //IL_0bc8: Unknown result type (might be due to invalid IL or missing references) //IL_0bd5: Expected O, but got Unknown //IL_0c2e: Unknown result type (might be due to invalid IL or missing references) //IL_0c3b: Expected O, but got Unknown if (s_installed) { return; } s_installed = true; try { if (coreAssembly != null) { Type type = coreAssembly.GetType("TameMate.SupremeTierEngine"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "InvalidateTier", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo != null) { s_invalidateTier = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo); } MethodInfo methodInfo2 = AccessTools.Method(type, "GetTierHealthMultiplier", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo2 != null) { s_getHealthMult = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo2); } MethodInfo methodInfo3 = AccessTools.Method(type, "GetTierDamageMultiplier", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo3 != null) { s_getDamageMult = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo3); } MethodInfo methodInfo4 = AccessTools.Method(type, "GetTierDamageReduction", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo4 != null) { s_getReductionMult = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo4); } MethodInfo methodInfo5 = AccessTools.Method(type, "GetTierSpeedMultiplier", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo5 != null) { s_getSpeedMult = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo5); } MethodInfo methodInfo6 = AccessTools.Method(type, "GetTierBadge", new Type[1] { typeof(Character) }, (Type[])null); MethodInfo methodInfo7 = AccessTools.Method(typeof(CataclysmicHudFormatter), "GetTierBadge_Postfix", (Type[])null, (Type[])null); if (methodInfo6 != null && methodInfo7 != null) { harmony.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(methodInfo7, 200, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo8 = AccessTools.Method(type, "GetTierAttributesSummary", new Type[1] { typeof(Character) }, (Type[])null); MethodInfo methodInfo9 = AccessTools.Method(typeof(CataclysmicHudFormatter), "GetTierAttributesSummary_Postfix", (Type[])null, (Type[])null); if (methodInfo8 != null && methodInfo9 != null) { harmony.Patch((MethodBase)methodInfo8, (HarmonyMethod)null, new HarmonyMethod(methodInfo9, 200, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } Type type2 = coreAssembly.GetType("TameMate.UndeadSystem"); if (type2 != null) { MethodInfo methodInfo10 = AccessTools.Method(type2, "ApplyUndeadVisuals", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo10 != null) { s_applyUndeadVisuals = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo10); } MethodInfo methodInfo11 = AccessTools.Method(type2, "SetUndead", new Type[2] { typeof(Character), typeof(bool) }, (Type[])null); MethodInfo methodInfo12 = AccessTools.Method(typeof(CataclysmicHudFormatter), "OnCompanionStateChanged_Postfix", (Type[])null, (Type[])null); if (methodInfo11 != null && methodInfo12 != null) { harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } Type type3 = coreAssembly.GetType("TameMate.CompanionState"); if (type3 != null) { MethodInfo methodInfo13 = AccessTools.Method(type3, "SetTierOverride", new Type[2] { typeof(Character), typeof(int) }, (Type[])null); MethodInfo methodInfo14 = AccessTools.Method(typeof(CataclysmicHudFormatter), "OnCompanionStateChanged_Postfix", (Type[])null, (Type[])null); if (methodInfo13 != null && methodInfo14 != null) { harmony.Patch((MethodBase)methodInfo13, (HarmonyMethod)null, new HarmonyMethod(methodInfo14), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } Type type4 = coreAssembly.GetType("TameMate.TierVisualAura"); if (type4 != null) { s_ensureAuraMethod = AccessTools.Method(type4, "Ensure", new Type[1] { typeof(Character) }, (Type[])null); s_refreshAuraMethod = AccessTools.Method(type4, "RefreshVisuals", Type.EmptyTypes, (Type[])null); } Type type5 = coreAssembly.GetType("TameMate.TameHoverPatch"); if (type5 != null) { s_lastHoveredIdField = AccessTools.Field(type5, "s_lastHoveredId"); s_nextHoverComputeTimeField = AccessTools.Field(type5, "s_nextHoverComputeTime"); s_lastUntamedHoveredIdField = AccessTools.Field(type5, "s_lastUntamedHoveredId"); s_nextUntamedHoverComputeTimeField = AccessTools.Field(type5, "s_nextUntamedHoverComputeTime"); } Type type6 = coreAssembly.GetType("TameMate.ProgressionPatches"); if (type6 != null) { s_cachedHoverNameIdField = AccessTools.Field(type6, "s_cachedHoverNameId"); s_hoverNameCacheExpiryField = AccessTools.Field(type6, "s_hoverNameCacheExpiry"); } Type type7 = coreAssembly.GetType("TameMate.SeasonBridge"); if (type7 != null) { PropertyInfo property = type7.GetProperty("CurrentSeason", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { MethodInfo getMethod = property.GetGetMethod(nonPublic: true); if (getMethod != null) { s_getCurrentSeason = () => (int)getMethod.Invoke(null, null); } } } Type type8 = coreAssembly.GetType("TameMate.EpicMMOBridge"); if (type8 != null) { PropertyInfo property2 = type8.GetProperty("IsInstalled", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property2 != null) { MethodInfo getM = property2.GetGetMethod(nonPublic: true); if (getM != null) { s_getMmoInstalled = () => (bool)getM.Invoke(null, null); } } PropertyInfo property3 = type8.GetProperty("PlayerLevel", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property3 != null) { MethodInfo getM2 = property3.GetGetMethod(nonPublic: true); if (getM2 != null) { s_getMmoPlayerLevel = () => (int)getM2.Invoke(null, null); } } PropertyInfo property4 = type8.GetProperty("CompanionPhysicalDamageBonus", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property4 != null) { MethodInfo getM3 = property4.GetGetMethod(nonPublic: true); if (getM3 != null) { s_getMmoDmgBonus = () => (float)getM3.Invoke(null, null); } } } Type type9 = coreAssembly.GetType("TameMate.ExternalMountBridge"); if (type9 != null) { MethodInfo methodInfo15 = AccessTools.Method(type9, "Supports", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo15 != null) { s_externalMountSupports = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo15); } } Type type10 = coreAssembly.GetType("TameMate.CommandWheel"); if (type10 != null) { PropertyInfo property5 = type10.GetProperty("IsOpen", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property5 != null) { MethodInfo gm = property5.GetGetMethod(nonPublic: true); if (gm != null) { s_isCommandWheelOpen = () => (bool)gm.Invoke(null, null); } } } } Type type11 = AccessTools.TypeByName("TameMate.OceanHorn.SpecialTiers"); if (type11 != null) { MethodInfo methodInfo16 = AccessTools.Method(type11, "NormalizeHealth", new Type[1] { typeof(Character) }, (Type[])null); MethodInfo methodInfo17 = AccessTools.Method(typeof(CataclysmicHudFormatter), "OnCompanionStateChanged_Postfix", (Type[])null, (Type[])null); if (methodInfo16 != null && methodInfo17 != null) { harmony.Patch((MethodBase)methodInfo16, (HarmonyMethod)null, new HarmonyMethod(methodInfo17), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo18 = AccessTools.Method(type11, "AfterTame", new Type[2] { typeof(Character), typeof(bool) }, (Type[])null); if (methodInfo18 != null && methodInfo17 != null) { harmony.Patch((MethodBase)methodInfo18, (HarmonyMethod)null, new HarmonyMethod(methodInfo17), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } MethodInfo methodInfo19 = AccessTools.Method(typeof(Character), "GetHoverName", (Type[])null, (Type[])null); MethodInfo methodInfo20 = AccessTools.Method(typeof(CataclysmicHudFormatter), "GetHoverNamePostfix", (Type[])null, (Type[])null); if (methodInfo19 != null && methodInfo20 != null) { harmony.Patch((MethodBase)methodInfo19, (HarmonyMethod)null, new HarmonyMethod(methodInfo20, 200, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo21 = AccessTools.Method(typeof(Tameable), "GetHoverText", (Type[])null, (Type[])null); MethodInfo methodInfo22 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Tameable_GetHoverText_Prefix", (Type[])null, (Type[])null); if (methodInfo21 != null && methodInfo22 != null) { harmony.Patch((MethodBase)methodInfo21, new HarmonyMethod(methodInfo22, 600, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo23 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Tameable_GetHoverText_Postfix", (Type[])null, (Type[])null); if (methodInfo21 != null && methodInfo23 != null) { harmony.Patch((MethodBase)methodInfo21, (HarmonyMethod)null, new HarmonyMethod(methodInfo23, 0, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo24 = AccessTools.Method(typeof(Player), "UpdateHover", (Type[])null, (Type[])null); MethodInfo methodInfo25 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Player_UpdateHover_Postfix", (Type[])null, (Type[])null); if (methodInfo24 != null && methodInfo25 != null) { harmony.Patch((MethodBase)methodInfo24, (HarmonyMethod)null, new HarmonyMethod(methodInfo25, 0, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo26 = AccessTools.Method(typeof(Sadle), "GetHoverText", (Type[])null, (Type[])null); MethodInfo methodInfo27 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Sadle_GetHoverText_Postfix", (Type[])null, (Type[])null); if (methodInfo26 != null && methodInfo27 != null) { harmony.Patch((MethodBase)methodInfo26, (HarmonyMethod)null, new HarmonyMethod(methodInfo27, 0, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Type typeFromHandle = typeof(EnemyHud); MethodInfo methodInfo28 = AccessTools.Method(typeFromHandle, "UpdateHuds", new Type[3] { typeof(Player), typeof(Sadle), typeof(float) }, (Type[])null); MethodInfo methodInfo29 = AccessTools.Method(typeof(CataclysmicHudFormatter), "EnemyHud_UpdateHuds_Postfix", (Type[])null, (Type[])null); if (methodInfo28 != null && methodInfo29 != null) { harmony.Patch((MethodBase)methodInfo28, (HarmonyMethod)null, new HarmonyMethod(methodInfo29, 0, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo30 = AccessTools.Method(typeof(Character), "SetLevel", new Type[1] { typeof(int) }, (Type[])null); MethodInfo methodInfo31 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Character_SetLevel_Postfix", (Type[])null, (Type[])null); if (methodInfo30 != null && methodInfo31 != null) { harmony.Patch((MethodBase)methodInfo30, (HarmonyMethod)null, new HarmonyMethod(methodInfo31), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo32 = AccessTools.Method(typeof(Character), "SetupMaxHealth", Type.EmptyTypes, (Type[])null); MethodInfo methodInfo33 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Character_SetupMaxHealth_Postfix", (Type[])null, (Type[])null); if (methodInfo32 != null && methodInfo33 != null) { harmony.Patch((MethodBase)methodInfo32, (HarmonyMethod)null, new HarmonyMethod(methodInfo33), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Type type12 = AccessTools.TypeByName("StarLevelSystem.modules.UI.UIHudControl"); if (type12 != null) { MethodInfo methodInfo34 = AccessTools.Method(type12, "InvalidateCacheEntry", new Type[1] { typeof(Character) }, (Type[])null); MethodInfo methodInfo35 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Sls_InvalidateCacheEntry_Postfix", (Type[])null, (Type[])null); if (methodInfo34 != null && methodInfo35 != null) { harmony.Patch((MethodBase)methodInfo34, (HarmonyMethod)null, new HarmonyMethod(methodInfo35), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } Type type13 = AccessTools.TypeByName("StarLevelSystem.modules.CreatureSetup.CreatureSetupControl"); if (type13 != null) { MethodInfo methodInfo36 = AccessTools.Method(type13, "RunCharacterSetup", (Type[])null, (Type[])null); MethodInfo methodInfo37 = AccessTools.Method(typeof(CataclysmicHudFormatter), "Sls_RunCharacterSetup_Postfix", (Type[])null, (Type[])null); if (methodInfo36 != null && methodInfo37 != null) { harmony.Patch((MethodBase)methodInfo36, (HarmonyMethod)null, new HarmonyMethod(methodInfo37), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate Lineages] CataclysmicHudFormatter.Install warning: " + ex.Message)); } } public static void OnCompanionStateChanged_Postfix(Character __0) { if (!((Object)(object)__0 == (Object)null) && !__0.IsPlayer() && __0.IsTamed()) { RefreshCompanionLiveState(__0); } } [HarmonyPriority(600)] public static void Tameable_GetHoverText_Prefix(Tameable __instance) { if ((Object)(object)__instance == (Object)null) { return; } Character component = ((Component)__instance).GetComponent(); if ((Object)(object)component != (Object)null && !component.IsPlayer()) { if (component.IsTamed()) { EnsureLiveStateSynchronized(component); } else { CheckCharacterLevelChange(component); } } } public static void InvalidateCreatureTierAndPresentation(Character c) { if ((Object)(object)c == (Object)null) { return; } if (s_invalidateTier != null) { try { s_invalidateTier(c); } catch { } } InvalidateHoverCaches(); } public static void CheckCharacterLevelChange(Character c) { if ((Object)(object)c == (Object)null || c.IsPlayer() || c.IsDead()) { return; } int instanceID = ((Object)c).GetInstanceID(); int level = c.GetLevel(); if (s_lastKnownCharacterLevels.TryGetValue(instanceID, out var value)) { if (value != level) { s_lastKnownCharacterLevels[instanceID] = level; InvalidateCreatureTierAndPresentation(c); } } else { if (s_lastKnownCharacterLevels.Count >= 1024) { s_lastKnownCharacterLevels.Clear(); } s_lastKnownCharacterLevels[instanceID] = level; } } public static void Sls_InvalidateCacheEntry_Postfix(Character chara) { if (!((Object)(object)chara == (Object)null) && !chara.IsPlayer()) { int instanceID = ((Object)chara).GetInstanceID(); int level = chara.GetLevel(); s_lastKnownCharacterLevels[instanceID] = level; InvalidateCreatureTierAndPresentation(chara); } } public static void Sls_RunCharacterSetup_Postfix(Character __instance) { if (!((Object)(object)__instance == (Object)null) && !__instance.IsPlayer()) { int instanceID = ((Object)__instance).GetInstanceID(); int level = __instance.GetLevel(); s_lastKnownCharacterLevels[instanceID] = level; InvalidateCreatureTierAndPresentation(__instance); } } public static void Character_SetLevel_Postfix(Character __instance, int level) { if (!((Object)(object)__instance == (Object)null) && !__instance.IsPlayer()) { int instanceID = ((Object)__instance).GetInstanceID(); s_lastKnownCharacterLevels[instanceID] = level; InvalidateCreatureTierAndPresentation(__instance); } } public static void Character_SetupMaxHealth_Postfix(Character __instance) { if (!((Object)(object)__instance == (Object)null) && !__instance.IsPlayer()) { int instanceID = ((Object)__instance).GetInstanceID(); int level = __instance.GetLevel(); if (!s_lastKnownCharacterLevels.TryGetValue(instanceID, out var value) || value != level) { s_lastKnownCharacterLevels[instanceID] = level; InvalidateCreatureTierAndPresentation(__instance); } } } public static void EnsureLiveStateSynchronized(Character c) { if (s_isRefreshing || (Object)(object)c == (Object)null || c.IsPlayer() || c.IsDead() || !c.IsTamed()) { return; } ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null) { return; } int instanceID = ((Object)c).GetInstanceID(); int num = ComputeLiveStateSignature(c, zDO); int value; bool flag = !s_liveStateSignatures.TryGetValue(instanceID, out value) || value != num; if (!flag && c.IsTamed() && s_getHealthMult != null) { float tierHealthMultiplier = s_getHealthMult(c); int healthStatPoints = Mathf.Max(0, zDO.GetInt(s_statHealthKey, 0)); bool isMutated = zDO.GetInt(PriorityFixesIntegration.MutatedHash, 0) != 0; PriorityFixesIntegration.ComputeIdempotentCompanionHealth(c.GetMaxHealthBase(), c.GetLevel(), tierHealthMultiplier, isMutated, healthStatPoints, out var _, out var expectedEffectiveMaxHealth); if (c.GetMaxHealth() + 1.5f < expectedEffectiveMaxHealth) { flag = true; } } if (flag) { RefreshCompanionLiveState(c); } } private static int ComputeLiveStateSignature(Character c, ZDO zdo) { int num = 17; num = num * 31 + zdo.GetInt(CataclysmicStateReader.SavedTierKey, 0); num = num * 31 + zdo.GetInt(CataclysmicStateReader.TierOverrideKey, 0); num = num * 31 + zdo.GetInt(PriorityFixesIntegration.NaturalTierHash, 0); num = num * 31 + zdo.GetInt(PriorityFixesIntegration.OriginBiomeHash, 0); num = num * 31 + zdo.GetInt(PriorityFixesIntegration.MutatedHash, 0); num = num * 31 + zdo.GetInt(CataclysmicStateReader.IsCataclysmicKey, 0); num = num * 31 + zdo.GetInt(CataclysmicStateReader.IsUndeadKey, 0); num = num * 31 + (c.IsTamed() ? 1 : 0); num = num * 31 + c.GetLevel(); num = num * 31 + zdo.GetInt(s_statHealthKey, 0); num = num * 31 + (zdo.GetString(CataclysmicStateReader.SavedEventKey, "")?.GetHashCode() ?? 0); return num * 31 + (zdo.GetString(s_eqChestKey, "")?.GetHashCode() ?? 0); } public static void RefreshCompanionLiveState(Character c, bool preserveHealthFraction = true) { if (s_isRefreshing || (Object)(object)c == (Object)null || c.IsPlayer() || c.IsDead() || !c.IsTamed()) { return; } ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null) { return; } int instanceID = ((Object)c).GetInstanceID(); bool flag = s_liveStateSignatures.ContainsKey(instanceID); s_isRefreshing = true; try { if (s_invalidateTier != null) { s_invalidateTier(c); } InvalidateHoverCaches(); if (s_getHealthMult != null && !c.IsBoss()) { float num = Mathf.Max(1f, c.GetMaxHealth()); float health = c.GetHealth(); float num2 = (preserveHealthFraction ? Mathf.Clamp01(health / num) : 1f); if (health <= 0.01f && !c.IsDead()) { num2 = 1f; } float num3 = s_getHealthMult(c); bool flag2 = zDO.GetInt(PriorityFixesIntegration.MutatedHash, 0) != 0; if (num3 > 1.001f || flag2) { int healthStatPoints = (c.IsTamed() ? Mathf.Max(0, zDO.GetInt(s_statHealthKey, 0)) : 0); PriorityFixesIntegration.ComputeIdempotentCompanionHealth(c.GetMaxHealthBase(), c.GetLevel(), num3, flag2, healthStatPoints, out var targetZdoBaseMaxHealth, out var expectedEffectiveMaxHealth); if (component.IsOwner()) { bool flag3 = zDO.GetInt(s_hpInitKey, 0) == 1; int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(zDO); bool flag4 = CataclysmicStateReader.IsUndead(zDO); int num4 = ((flag4 || effectiveBaseTier == 9) ? (10000 + (c.IsTamed() ? 100 : 0) + effectiveBaseTier + (flag4 ? 1000 : 0)) : 0); zDO.Set(s_hpInitKey, 1, false); zDO.Set(s_specialProfileKey, num4, false); if ((flag || !flag3 || !preserveHealthFraction || !(num > expectedEffectiveMaxHealth + 0.5f)) && (Mathf.Abs(num - expectedEffectiveMaxHealth) > 0.5f || !preserveHealthFraction)) { c.SetMaxHealth(targetZdoBaseMaxHealth); float num5 = Mathf.Max(1f, c.GetMaxHealth()); float health2 = (preserveHealthFraction ? Mathf.Clamp(num5 * num2, 1f, num5) : num5); c.SetHealth(health2); } } } } if (s_applyUndeadVisuals != null) { try { s_applyUndeadVisuals(c); } catch { } } if (s_ensureAuraMethod != null && s_refreshAuraMethod != null) { try { object obj2 = s_ensureAuraMethod.Invoke(null, new object[1] { c }); if (obj2 != null) { s_refreshAuraMethod.Invoke(obj2, null); } } catch { } } s_liveStateSignatures[((Object)c).GetInstanceID()] = ComputeLiveStateSignature(c, zDO); InvalidateHoverCaches(); } catch (Exception ex) { Debug.LogWarning((object)("[TameMate Lineages] RefreshCompanionLiveState warning: " + ex.Message)); } finally { s_isRefreshing = false; } } public static void InvalidateHoverCaches() { try { if (s_lastHoveredIdField != null) { s_lastHoveredIdField.SetValue(null, -1); } if (s_nextHoverComputeTimeField != null) { s_nextHoverComputeTimeField.SetValue(null, 0f); } if (s_lastUntamedHoveredIdField != null) { s_lastUntamedHoveredIdField.SetValue(null, -1); } if (s_nextUntamedHoverComputeTimeField != null) { s_nextUntamedHoverComputeTimeField.SetValue(null, 0f); } if (s_cachedHoverNameIdField != null) { s_cachedHoverNameIdField.SetValue(null, -1); } if (s_hoverNameCacheExpiryField != null) { s_hoverNameCacheExpiryField.SetValue(null, 0f); } s_cachedTargetCharacterId = 0; s_cachedTargetZdoSig = 0; s_cachedTargetHp = -1; s_cachedTargetMaxHp = -1; s_cachedTargetStamina = -1; s_cachedTargetAttached = false; s_cachedTargetNextRefresh = 0f; s_cachedTargetHoverText = null; } catch { } } [HarmonyPriority(200)] public static void GetTierBadge_Postfix(Character c, ref string __result) { if ((Object)(object)c == (Object)null || c.IsPlayer() || !c.IsTamed()) { return; } EnsureLiveStateSynchronized(c); ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO != null) { CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(zDO); if (cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic) { int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(zDO); bool flag = CataclysmicStateReader.IsUndead(zDO); string eventName = zDO.GetString(CataclysmicStateReader.SavedEventKey, ""); string eventDisplayName = GetEventDisplayName(eventName); string tierTag = GetTierTag(effectiveBaseTier); string arg = ((string.IsNullOrEmpty(eventDisplayName) || eventDisplayName == "Elemental") ? "[Cataclísmico]" : $"[Cataclísmico - {eventDisplayName}]"); __result = (flag ? $"[Undead] {arg} {tierTag}" : $"{arg} {tierTag}"); } } } [HarmonyPriority(200)] public static void GetTierAttributesSummary_Postfix(Character c, ref string __result) { if ((Object)(object)c == (Object)null || c.IsPlayer() || c.IsBoss()) { return; } if (c.IsTamed()) { __result = ""; return; } ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null) { return; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(zDO); bool flag = CataclysmicStateReader.IsUndead(zDO); bool isCataclysmic = CataclysmicStateReader.IsCataclysmic(zDO); if ((cataclysmicClassification != CataclysmicClassification.DecoupledCataclysmic && !flag && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguous && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguousUndead) || s_getHealthMult == null || s_getDamageMult == null || s_getSpeedMult == null) { return; } int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(zDO); float num = s_getHealthMult(c); float num2 = s_getDamageMult(c); float num3 = s_getSpeedMult(c); float num4 = CataclysmicCombatPipeline.ComputeEffectiveDamageReduction(effectiveBaseTier, isCataclysmic, flag, c.IsTamed()); int num5 = Mathf.RoundToInt(num4 * 100f); string text = num5 + "%"; if (flag && c.IsTamed()) { int num6 = ((!string.IsNullOrEmpty(zDO.GetString(s_eqChestKey, ""))) ? 80 : 75); if (num5 > num6) { text = $"{num5}% (Tope P-05: {num6}%)"; } } string text2 = (c.IsTamed() ? "Compañero" : "Salvaje"); if (flag) { text2 += " No-muerto"; } if (cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic) { text2 += " Cataclísmico"; } string text3 = ""; if (cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic) { string a = zDO.GetString(CataclysmicStateReader.SavedEventKey, ""); int num7 = (string.Equals(a, "MagicalAurora", StringComparison.OrdinalIgnoreCase) ? 10 : (flag ? 15 : 20)); text3 = $" (+{num7}% elem.)"; } __result = $"{text2}: vida x{num:0.00}, daño x{num2:0.00}{text3}, reducción {text}, velocidad x{num3:0.00} (modificadores del tier)."; } [HarmonyPriority(200)] public static void GetHoverNamePostfix(Character __instance, ref string __result) { if ((Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } if (!__instance.IsTamed()) { CheckCharacterLevelChange(__instance); return; } EnsureLiveStateSynchronized(__instance); ZNetView component = ((Component)__instance).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { ZDO zDO = component.GetZDO(); if (zDO != null) { __result = FormatCompanionHoverTag(zDO, __result); } } } public static string FormatCompanionHoverTag(ZDO zdo, string originalName) { if (zdo == null) { return originalName ?? ""; } return FormatCompanionHoverTag((IZdoPropertyReader)new ValheimZdoReader(zdo), originalName); } public static string FormatCompanionHoverTag(IZdoPropertyReader reader, string originalName) { if (reader == null) { return originalName ?? ""; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(reader); if (cataclysmicClassification == CataclysmicClassification.CorruptOrIncomplete) { return originalName ?? ""; } int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(reader); bool flag = CataclysmicStateReader.IsUndead(reader); string eventName = reader.GetString(CataclysmicStateReader.SavedEventKey); string eventDisplayName = GetEventDisplayName(eventName); string text = ""; switch (cataclysmicClassification) { case CataclysmicClassification.LegacyAmbiguous: text = "[Cataclísmico]"; break; case CataclysmicClassification.LegacyAmbiguousUndead: text = "[Undead • Cataclísmico]"; break; case CataclysmicClassification.DecoupledCataclysmic: { string tierTag = GetTierTag(effectiveBaseTier); string arg = ((string.IsNullOrEmpty(eventDisplayName) || eventDisplayName == "Elemental") ? "[Cataclísmico]" : $"[Cataclísmico - {eventDisplayName}]"); text = ((!flag) ? $"{arg} {tierTag}" : $"[Undead] {arg} {tierTag}"); break; } case CataclysmicClassification.NormalValid: text = ((!flag) ? GetTierTag(effectiveBaseTier) : $"[Undead • {GetTierName(effectiveBaseTier)}]"); break; } if (string.IsNullOrEmpty(text)) { return originalName ?? ""; } string text2 = StripExistingTags(originalName); return text + " " + text2; } public static string GetEventDisplayName(string eventName) { if (string.IsNullOrEmpty(eventName)) { return "Elemental"; } if (string.Equals(eventName, "MeteorShower", StringComparison.OrdinalIgnoreCase)) { return "Ígneo"; } if (string.Equals(eventName, "Blizzard", StringComparison.OrdinalIgnoreCase)) { return "Gélido"; } if (string.Equals(eventName, "Thunderstorm", StringComparison.OrdinalIgnoreCase)) { return "Tormenta"; } if (string.Equals(eventName, "ToxicFog", StringComparison.OrdinalIgnoreCase)) { return "Tóxico"; } if (string.Equals(eventName, "MagicalAurora", StringComparison.OrdinalIgnoreCase)) { return "Místico"; } return eventName; } public static string GetTierName(int tier) { return tier switch { 1 => "Feral", 2 => "Alpha", 3 => "Apex", 4 => "Frostborn", 5 => "Primal", 6 => "Astral", 7 => "Infernal", 8 => "Ancestral", 9 => "Cataclísmico", 10 => "Supreme", _ => "Feral", }; } public static string GetTierTag(int tier) { return tier switch { 1 => "[Feral]", 2 => "[Alpha]", 3 => "[Apex]", 4 => "[Frostborn]", 5 => "[Primal]", 6 => "[Astral]", 7 => "[Infernal]", 8 => "[Ancestral]", 9 => "[Cataclísmico]", 10 => "[Supreme]", _ => "[Feral]", }; } public static string StripExistingTags(string name) { if (string.IsNullOrEmpty(name)) { return ""; } string text = name.Trim(); while (text.StartsWith(""); if (num2 >= 0) { num = num2 + 8; } } else if (text.StartsWith("[")) { int num3 = text.IndexOf("]"); if (num3 >= 0) { num = num3 + 1; } } if (num <= 0 || num >= text.Length) { break; } text = text.Substring(num).Trim(); } return text; } public static string GetStatusSummary(IZdoPropertyReader reader) { if (reader == null) { return "Estado no disponible."; } CataclysmicStateReader.Classify(reader); int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(reader); bool flag = CataclysmicStateReader.IsCataclysmic(reader); bool flag2 = CataclysmicStateReader.IsUndead(reader); string eventName = reader.GetString(CataclysmicStateReader.SavedEventKey); float num = CataclysmicCombatPipeline.ComputeEffectiveDamageReduction(effectiveBaseTier, flag, flag2, isTamed: true); string text = $"Tier Base: {GetTierName(effectiveBaseTier)} (Tier {effectiveBaseTier})\n"; if (flag) { text += $"Estado Cataclísmico: Activo (Afinidad: {GetEventDisplayName(eventName)})\n - Daño elemental saliente: +15% / +20%\n - Resistencia elemental: 50%\n - Capa de mitigación: +8%\n"; } if (flag2) { text += "Estado No-Muerto: Activo\n - Mitigación Undead: +8%\n - Robo de vida: 10%\n - Resistencia Veneno/Frío: 75%\n - Límite P-05: 75% máx (80% con alforjas)\n"; } return text + $"Mitigación Base Compuesta: {num:P0}"; } private static string Localize(string text) { if (string.IsNullOrEmpty(text)) { return ""; } try { Type type = Type.GetType("Localization, assembly_guiutils"); if (type != null) { PropertyInfo property = type.GetProperty("instance", BindingFlags.Static | BindingFlags.Public); object obj = ((property != null) ? property.GetValue(null, null) : null); if (obj != null) { MethodInfo method = type.GetMethod("Localize", new Type[1] { typeof(string) }); if (method != null) { return (string)method.Invoke(obj, new object[1] { text }); } } } } catch { } return text; } [HarmonyPriority(0)] public static void EnemyHud_UpdateHuds_Postfix(EnemyHud __instance, Player player) { if ((Object)(object)__instance == (Object)null || (Object)(object)player == (Object)null) { return; } try { if (s_enemyHudsField == null) { s_enemyHudsField = AccessTools.Field(typeof(EnemyHud), "m_huds"); } if (s_enemyHudsField == null || !(s_enemyHudsField.GetValue(__instance) is IDictionary dictionary)) { return; } Character hoverCreature = player.GetHoverCreature(); if ((Object)(object)hoverCreature != (Object)null && hoverCreature.IsTamed() && !hoverCreature.IsPlayer() && !hoverCreature.IsDead() && dictionary.Contains(hoverCreature)) { object obj = dictionary[hoverCreature]; if (obj != null) { if (s_hudDataGuiField == null) { s_hudDataGuiField = AccessTools.Field(obj.GetType(), "m_gui"); } if (s_hudDataGuiField != null) { object? value = s_hudDataGuiField.GetValue(obj); GameObject val = (GameObject)((value is GameObject) ? value : null); if ((Object)(object)val != (Object)null && val.activeSelf) { val.SetActive(false); } } } } Character val2 = ResolveTargetCharacter(((Humanoid)player).GetHoverObject()); if (!((Object)(object)val2 != (Object)null) || !((Object)(object)val2 != (Object)(object)hoverCreature) || !val2.IsTamed() || val2.IsPlayer() || val2.IsDead() || !dictionary.Contains(val2)) { return; } object obj2 = dictionary[val2]; if (obj2 == null) { return; } if (s_hudDataGuiField == null) { s_hudDataGuiField = AccessTools.Field(obj2.GetType(), "m_gui"); } if (s_hudDataGuiField != null) { object? value2 = s_hudDataGuiField.GetValue(obj2); GameObject val3 = (GameObject)((value2 is GameObject) ? value2 : null); if ((Object)(object)val3 != (Object)null && val3.activeSelf) { val3.SetActive(false); } } } catch { } } [HarmonyPriority(0)] public static void Player_UpdateHover_Postfix(Player __instance) { if ((Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || ((Character)__instance).IsAttached()) { return; } GameObject val = ((Humanoid)__instance).GetHoverObject(); Character hoverCreature = __instance.GetHoverCreature(); GameObject val2 = TryDisambiguateOverlappingMount(__instance, val, hoverCreature); if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)val) { if (s_playerHoveringField == null) { s_playerHoveringField = AccessTools.Field(typeof(Player), "m_hovering"); } if (s_playerHoveringField != null) { s_playerHoveringField.SetValue(__instance, val2); val = val2; } } int num = (((Object)(object)val != (Object)null) ? ((Object)val).GetInstanceID() : 0); int num2 = (((Object)(object)hoverCreature != (Object)null) ? ((Object)hoverCreature).GetInstanceID() : 0); if (num == s_lastObservedHoverId && num2 == s_lastObservedHoverCreatureId) { return; } s_lastObservedHoverId = num; s_lastObservedHoverCreatureId = num2; InvalidateHoverCaches(); if ((Object)(object)val != (Object)null) { Character val3 = ResolveTargetCharacter(val); if ((Object)(object)val3 != (Object)null && val3.IsTamed() && !val3.IsPlayer() && !val3.IsDead()) { EnsureLiveStateSynchronized(val3); } } } public static GameObject TryDisambiguateOverlappingMount(Player player, GameObject curHover, Character visualCreature) { //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || (Object)(object)curHover == (Object)null || (Object)(object)visualCreature == (Object)null) { return curHover; } if (visualCreature.IsDead() || visualCreature.IsPlayer() || !visualCreature.IsTamed()) { return curHover; } Character val = ResolveTargetCharacter(curHover); if ((Object)(object)val == (Object)null || val.IsPlayer() || val.IsDead() || !val.IsTamed()) { return curHover; } if ((Object)(object)val == (Object)(object)visualCreature) { return curHover; } Tameable component = ((Component)visualCreature).GetComponent(); if ((Object)(object)component == (Object)null) { return curHover; } Sadle val2 = component.m_saddle; if ((Object)(object)val2 == (Object)null) { val2 = ((Component)visualCreature).GetComponentInChildren(); } if ((Object)(object)val2 == (Object)null || (Object)(object)((Component)val2).gameObject == (Object)null) { return curHover; } if (!((Object)(object)val2.GetCharacter() == (Object)(object)visualCreature) && !((Component)val2).transform.IsChildOf(((Component)visualCreature).transform) && !((Object)(object)component.m_saddle == (Object)(object)val2)) { return curHover; } Transform val3 = (((Object)(object)val2.m_attachPoint != (Object)null) ? val2.m_attachPoint : ((Component)val2).transform); float num = Vector3.Distance(((Component)player).transform.position, val3.position); float num2 = Mathf.Max(2.5f, val2.m_maxUseRange); if (num >= num2) { return curHover; } Interactable componentInParent = ((Component)val2).gameObject.GetComponentInParent(); if (componentInParent == null) { return curHover; } return ((Component)val2).gameObject; } public static Character ResolveTargetCharacter(GameObject go) { if ((Object)(object)go == (Object)null) { return null; } Character componentInParent = go.GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { return componentInParent; } Sadle componentInParent2 = go.GetComponentInParent(); if ((Object)(object)componentInParent2 != (Object)null) { componentInParent = componentInParent2.GetCharacter(); if ((Object)(object)componentInParent != (Object)null) { return componentInParent; } if ((Object)(object)((Component)componentInParent2).transform.parent != (Object)null) { componentInParent = ((Component)((Component)componentInParent2).transform.parent).GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { return componentInParent; } } } Tameable componentInParent3 = go.GetComponentInParent(); if ((Object)(object)componentInParent3 != (Object)null) { componentInParent = ((Component)componentInParent3).GetComponent(); if ((Object)(object)componentInParent != (Object)null) { return componentInParent; } } return null; } public static string GetOrFormatCompactNordicHover(Tameable tameable, Character c, string originalHoverText) { if ((Object)(object)tameable == (Object)null || (Object)(object)c == (Object)null || c.IsDead()) { return originalHoverText ?? ""; } int instanceID = ((Object)c).GetInstanceID(); float time = Time.time; ZNetView component = ((Component)c).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); int num = ((val != null) ? ComputeLiveStateSignature(c, val) : 0); int num2 = Mathf.CeilToInt(c.GetHealth()); int num3 = Mathf.CeilToInt(c.GetMaxHealth()); Sadle val2 = (((Object)(object)tameable.m_saddle != (Object)null) ? tameable.m_saddle : ((Component)c).GetComponentInChildren()); int num4 = (((Object)(object)val2 != (Object)null) ? Mathf.CeilToInt(val2.GetStamina()) : (-1)); Player localPlayer = Player.m_localPlayer; bool flag = (Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsAttached(); if (instanceID == s_cachedTargetCharacterId && s_cachedTargetHoverText != null && num == s_cachedTargetZdoSig && num2 == s_cachedTargetHp && num3 == s_cachedTargetMaxHp && num4 == s_cachedTargetStamina && flag == s_cachedTargetAttached && time < s_cachedTargetNextRefresh) { return s_cachedTargetHoverText; } string result = FormatCompactNordicHover(tameable, c, originalHoverText); s_cachedTargetCharacterId = instanceID; s_cachedTargetZdoSig = num; s_cachedTargetHp = num2; s_cachedTargetMaxHp = num3; s_cachedTargetStamina = num4; s_cachedTargetAttached = flag; s_cachedTargetNextRefresh = time + 0.2f; s_cachedTargetHoverText = result; return result; } [HarmonyPriority(0)] public static void Tameable_GetHoverText_Postfix(Tameable __instance, ref string __result) { try { if (s_isCommandWheelOpen != null && s_isCommandWheelOpen()) { __result = ""; } else if (!((Object)(object)__instance == (Object)null)) { Character component = ((Component)__instance).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsTamed() && !component.IsPlayer() && !component.IsDead()) { __result = GetOrFormatCompactNordicHover(__instance, component, __result); } } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate Lineages] FormatCompactNordicHover warning: " + ex.Message)); } } [HarmonyPriority(0)] public static void Sadle_GetHoverText_Postfix(Sadle __instance, ref string __result) { try { if (s_isCommandWheelOpen != null && s_isCommandWheelOpen()) { __result = ""; } else { if ((Object)(object)__instance == (Object)null) { return; } Character val = __instance.GetCharacter(); if ((Object)(object)val == (Object)null && (Object)(object)((Component)__instance).transform.parent != (Object)null) { val = ((Component)((Component)__instance).transform.parent).GetComponentInParent(); } if (!((Object)(object)val == (Object)null) && val.IsTamed() && !val.IsPlayer() && !val.IsDead()) { Tameable val2 = __instance.GetTameable(); if ((Object)(object)val2 == (Object)null) { val2 = ((Component)val).GetComponent(); } if (!((Object)(object)val2 == (Object)null)) { __result = GetOrFormatCompactNordicHover(val2, val, __result); } } } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate Lineages] Sadle_GetHoverText_Postfix warning: " + ex.Message)); } } public static string GetCompanionCleanName(Character c, ZDO zdo) { if ((Object)(object)c == (Object)null) { return ""; } if (zdo == null) { ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { zdo = component.GetZDO(); } } string text = ""; if (zdo != null) { string text2 = zdo.GetString(ZDOVars.s_tamedName, ""); if (!string.IsNullOrEmpty(text2)) { text = text2; } } if (string.IsNullOrEmpty(text)) { text = ((!string.IsNullOrEmpty(c.m_name)) ? Localize(c.m_name) : c.GetHoverName()); } return StripExistingTags(text); } public static string FormatLineageTags(Character c, ZDO zdo) { if ((Object)(object)c == (Object)null) { return ""; } if (zdo == null) { ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { zdo = component.GetZDO(); } } int num = ((zdo != null) ? CataclysmicStateReader.GetEffectiveBaseTier(zdo) : 0); if (num <= 0) { num = PriorityFixesIntegration.GetDisplayedCompanionBaseTier(c, zdo); } bool flag = zdo != null && CataclysmicStateReader.IsUndead(zdo); bool flag2 = zdo != null && CataclysmicStateReader.IsCataclysmic(zdo); string eventName = ((zdo != null) ? zdo.GetString(CataclysmicStateReader.SavedEventKey, "") : ""); string eventDisplayName = GetEventDisplayName(eventName); List list = new List(); if (flag) { list.Add("[Undead]"); } if (flag2) { string item = ((string.IsNullOrEmpty(eventDisplayName) || eventDisplayName == "Elemental") ? "[Cataclísmico]" : $"[Cataclísmico - {eventDisplayName}]"); list.Add(item); } list.Add(GetTierTag(num)); return string.Join(" ", list.ToArray()); } public static string FormatCompactNordicHover(Tameable tameable, Character c, string originalHoverText) { if ((Object)(object)tameable == (Object)null || (Object)(object)c == (Object)null) { return originalHoverText ?? ""; } EnsureLiveStateSynchronized(c); ZNetView component = ((Component)c).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); string companionCleanName = GetCompanionCleanName(c, val); string arg = FormatLineageTags(c, val); int level = c.GetLevel(); string arg2 = ""; if (level > 1) { arg2 = " " + RepeatString(s_starGlyph, level - 1); } string value = $"{arg} {companionCleanName}{arg2}"; int num = ((val == null) ? 1 : Mathf.Max(1, val.GetInt(s_levelKey, 1))); int num2 = ((val != null) ? Mathf.Max(0, val.GetInt(s_xpKey, 0)) : 0); int xpForLevel = GetXpForLevel(num); float xpProgress = GetXpProgress(num, num2); int num3 = Mathf.Clamp(Mathf.RoundToInt(xpProgress * 100f), 0, 100); string value2 = $"Nv. RPG {num} • {num2:N0} / {xpForLevel:N0} EXP ({num3}%)"; int num4 = ((val != null) ? Mathf.Max(0, val.GetInt(s_pointsKey, 0)) : 0); string value3 = ((num4 > 0) ? $"\n{s_starGlyph} ¡{num4} PUNTOS DISPONIBLES! [Rueda U]" : ""); float health = c.GetHealth(); float maxHealth = c.GetMaxHealth(); string text = $"{s_heartGlyph} {Mathf.CeilToInt(health):N0} / {Mathf.CeilToInt(maxHealth):N0}"; string text2 = text; try { Sadle val2 = (((Object)(object)tameable != (Object)null && (Object)(object)tameable.m_saddle != (Object)null) ? tameable.m_saddle : ((Component)c).GetComponentInChildren()); if ((Object)(object)val2 != (Object)null) { float maxStamina = val2.GetMaxStamina(); float stamina = val2.GetStamina(); if (maxStamina > 1f && !float.IsNaN(maxStamina) && !float.IsNaN(stamina)) { text2 += $" {s_lightningGlyph} {Mathf.CeilToInt(stamina):N0} / {Mathf.CeilToInt(maxStamina):N0}"; } } } catch { } List list = new List(); try { if (s_getCurrentSeason != null && s_getCurrentSeason() == 1) { list.Add($"{s_snowflakeGlyph} Invierno (Vetrbarn)"); } } catch { } try { if (s_getMmoInstalled != null && s_getMmoInstalled() && s_getMmoPlayerLevel != null && s_getMmoDmgBonus != null) { int num5 = s_getMmoPlayerLevel(); if (num5 > 0) { int num6 = Mathf.RoundToInt(s_getMmoDmgBonus() * 100f); list.Add($"{s_linkGlyph} Vínculo MMO (Jugador Nv. {num5} • Daño +{num6}%)"); } } } catch { } try { long num7 = DateTime.UtcNow.Ticks / 10000; long num8 = ((val != null) ? val.GetLong(s_recoverUntilKey, 0L) : 0); if (num8 > num7) { int num9 = Mathf.CeilToInt((float)(num8 - num7) / 1000f); list.Add($"Recuperándose: {num9} s"); } if (val != null && val.GetBool(s_necroFuryKey, false)) { list.Add("Furia Necrótica activa (+25% Daño)"); } if (val != null && val.GetBool(s_spectralVeilKey, false)) { list.Add("Velo Espectral activo (+35% Evasión)"); } } catch { } string value4 = ((list.Count > 0) ? string.Join(" ", list.ToArray()) : ""); int num10 = ((val == null) ? 1 : Mathf.Max(1, val.GetInt(s_groupKey, 1))); int stance = ((val != null) ? Mathf.Clamp(val.GetInt(s_stanceKey, 2), 0, 4) : 2); int order = ((val != null) ? Mathf.Clamp(val.GetInt(s_orderKey, 0), 0, 6) : 0); string arg3 = FormatStanceName(stance); string arg4 = FormatOrderName(order); string value5 = $"Grupo {num10} | {arg3} | Orden: {arg4}"; string value6 = ""; if (!string.IsNullOrEmpty(originalHoverText)) { string text3 = originalHoverText.ToLowerInvariant(); if (text3.Contains("hambrient") || text3.Contains("hungry") || text3.Contains("$hud_tamehungry")) { value6 = "(Hambriento)"; } else if (text3.Contains("embarazad") || text3.Contains("pregnant") || text3.Contains("$hud_tamepregnant")) { value6 = "(Embarazada)"; } } Player localPlayer = Player.m_localPlayer; string text4; if ((Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsAttached()) { text4 = "[$KEY_Use] Desmontar | [U] Alforjas / Órdenes"; } else { bool flag = (Object)(object)tameable != (Object)null && (Object)(object)tameable.m_saddle != (Object)null; bool flag2 = flag || ((Object)(object)tameable != (Object)null && (Object)(object)tameable.m_saddleItem != (Object)null) || (s_externalMountSupports != null && s_externalMountSupports(c)); bool flag3 = val != null && !string.IsNullOrEmpty(val.GetString(s_eqChestKey, "")); text4 = ((!flag2 || !flag) ? (flag3 ? "[$KEY_Use] Acariciar | [Shift+$KEY_Use] Renombrar | [U] Rueda Táctica / Alforjas" : "[$KEY_Use] Acariciar | [Shift+$KEY_Use] Renombrar | [U] Rueda Táctica") : (flag3 ? "[$KEY_Use] Montar | [Shift+$KEY_Use] Renombrar | [U] Rueda Táctica / Alforjas" : "[$KEY_Use] Montar | [Shift+$KEY_Use] Renombrar | [U] Rueda Táctica")); } string text5 = ExtractExternalModLines(originalHoverText); StringBuilder stringBuilder = new StringBuilder(256); stringBuilder.AppendLine(value); stringBuilder.Append(value2); if (!string.IsNullOrEmpty(value3)) { stringBuilder.Append(value3); } stringBuilder.AppendLine(); stringBuilder.AppendLine(text2); if (!string.IsNullOrEmpty(value4)) { stringBuilder.AppendLine(value4); } stringBuilder.AppendLine(value5); if (!string.IsNullOrEmpty(value6)) { stringBuilder.AppendLine(value6); } stringBuilder.Append("\n" + text4); if (!string.IsNullOrEmpty(text5)) { stringBuilder.Append("\n" + text5); } return Localize(stringBuilder.ToString().TrimEnd(new char[0])); } public static int GetXpForLevel(int level) { return Mathf.RoundToInt(75f * (float)level * (float)level + 125f * (float)level); } public static float GetXpProgress(int level, int xp) { int num = ((level > 1) ? GetXpForLevel(level - 1) : 0); int xpForLevel = GetXpForLevel(level); return Mathf.Clamp01((float)(xp - num) / (float)Mathf.Max(1, xpForLevel - num)); } public static string FormatStanceName(int stance) { return stance switch { 0 => "Pasivo", 1 => "Huir", 2 => "Defensivo", 3 => "Neutral", 4 => "Agresivo", _ => "Defensivo", }; } public static string FormatOrderName(int order) { return order switch { 0 => "Seguir", 1 => "Quédate", 2 => "Ir allí", 3 => "Proteger", 4 => "Patrullar", 5 => "A casa", 6 => "Atacar", _ => "Seguir", }; } private static string RepeatString(string s, int count) { if (count <= 0 || string.IsNullOrEmpty(s)) { return ""; } if (count == 1) { return s; } StringBuilder stringBuilder = new StringBuilder(s.Length * count); for (int i = 0; i < count; i++) { stringBuilder.Append(s); } return stringBuilder.ToString(); } private static string ExtractExternalModLines(string original) { if (string.IsNullOrEmpty(original)) { return ""; } string[] array = original.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); List list = new List(); string[] array2 = array; foreach (string text in array2) { string text2 = text.Trim(); if (!string.IsNullOrEmpty(text2)) { string text3 = text2.ToLowerInvariant(); if (!text3.Contains("$hud_") && !text3.Contains("$key_") && !text3.Contains("grupo") && !text3.Contains("conducta") && !text3.Contains("orden") && !text3.Contains("vida") && !text3.Contains("daño") && !text3.Contains("velocidad") && !text3.Contains("alimento") && !text3.Contains("aguante") && !text3.Contains("stamina") && !text3.Contains("monta") && !text3.Contains("riding") && !text3.Contains("silla") && !text3.Contains("saddle") && !text3.Contains("recuperándose") && !text3.Contains("furia necrótica") && !text3.Contains("velo espectral") && !text3.Contains("vínculo mmo") && !text3.Contains("mayús + e") && !text3.Contains("shift") && !text3.Contains("alforjas") && !text3.Contains("nv.") && !text3.Contains("exp:") && !text3.Contains("puntos disponibles") && !text3.Contains("hambrient") && !text3.Contains("hungry") && !text3.Contains("satisfecho") && !text3.Contains("asustad") && !text3.Contains("engaged") && !text3.Contains("modificadores del tier") && !text3.Contains("doma") && !text3.Contains("montar") && !text3.Contains("desmontar") && !text3.Contains("renombrar") && !text3.Contains("acariciar") && !text3.Contains("[feral]") && !text3.Contains("[alpha]") && !text3.Contains("[apex]") && !text3.Contains("[frostborn]") && !text3.Contains("[primal]") && !text3.Contains("[astral]") && !text3.Contains("[infernal]") && !text3.Contains("[ancestral]") && !text3.Contains("[cataclísmico]") && !text3.Contains("[supreme]") && !text3.Contains("[undead]")) { list.Add(text2); } } } if (list.Count <= 0) { return ""; } return string.Join("\n", list.ToArray()); } } public enum CataclysmicClassification { NormalValid, LegacyAmbiguous, LegacyAmbiguousUndead, DecoupledCataclysmic, CorruptOrIncomplete } public enum WorldExecutionMode { Unknown, Singleplayer, LocalHost, DedicatedServer, RemoteClient } public enum ZdoInspectionScope { PartialOrUnverified, CompleteWorldVerified } public sealed class CompanionIdentityResolution { public bool IsUnambiguousAndSafe { get; set; } public bool IsGlobalUniquenessProven { get; set; } public ZdoInspectionScope Scope { get; set; } public int MatchCount { get; set; } public string CompanionGuid { get; set; } public long ExpectedWorldUid { get; set; } public int ExpectedPrefabHash { get; set; } public string FailureReason { get; set; } public IZdoPropertyReader MatchedReader { get; set; } } public interface IZdoPropertyReader { int GetInt(int hash, int defaultValue = 0); string GetString(int hash, string defaultValue = ""); float GetFloat(int hash, float defaultValue = 0f); bool GetBool(int hash, bool defaultValue = false); long GetLong(int hash, long defaultValue = 0L); } public interface IZdoExtendedPropertyReader : IZdoPropertyReader { bool TryGetInt(int hash, out int value); bool TryGetString(int hash, out string value); bool TryGetFloat(int hash, out float value); bool TryGetLong(int hash, out long value); bool TryGetByteArray(int hash, out byte[] value); bool TryGetVec3(int hash, out Vector3 value); } public interface IRitualTransactionWriter : IZdoExtendedPropertyReader, IZdoPropertyReader { bool IsBoss { get; } bool IsTamed { get; } float NativeBaseHealth { get; } Action MidWriteFaultInjector { get; set; } void SetInt(int hash, int value); void SetString(int hash, string value); void SetFloat(int hash, float value); void SetLong(int hash, long value); void SetByteArray(int hash, byte[] value); void SetVec3(int hash, Vector3 value); bool RemoveKey(int hash); } public interface ISyntheticZdoPropertyWriter : IRitualTransactionWriter, IZdoExtendedPropertyReader, IZdoPropertyReader { bool IsSyntheticTestFixture { get; } } public sealed class ValheimZdoReader : IZdoExtendedPropertyReader, IZdoPropertyReader { private readonly ZDO m_zdo; public ZDO UnderlyingZdo => m_zdo; public ValheimZdoReader(ZDO zdo) { m_zdo = zdo; } public int GetInt(int hash, int defaultValue = 0) { if (m_zdo == null) { return defaultValue; } return m_zdo.GetInt(hash, defaultValue); } public string GetString(int hash, string defaultValue = "") { if (m_zdo == null) { return defaultValue; } return m_zdo.GetString(hash, defaultValue); } public float GetFloat(int hash, float defaultValue = 0f) { if (m_zdo == null) { return defaultValue; } return m_zdo.GetFloat(hash, defaultValue); } public bool GetBool(int hash, bool defaultValue = false) { if (m_zdo == null) { return defaultValue; } return m_zdo.GetBool(hash, defaultValue); } public long GetLong(int hash, long defaultValue = 0L) { if (m_zdo == null) { return defaultValue; } return m_zdo.GetLong(hash, defaultValue); } public bool TryGetInt(int hash, out int value) { if (m_zdo == null) { value = 0; return false; } int num = m_zdo.GetInt(hash, int.MinValue); int num2 = m_zdo.GetInt(hash, int.MaxValue); if (num == int.MinValue && num2 == int.MaxValue) { value = 0; return false; } value = num; return true; } public bool TryGetString(int hash, out string value) { if (m_zdo == null) { value = null; return false; } string text = m_zdo.GetString(hash, "\0__TM_ABSENT_A__"); string text2 = m_zdo.GetString(hash, "\0__TM_ABSENT_B__"); if (text == "\0__TM_ABSENT_A__" && text2 == "\0__TM_ABSENT_B__") { value = null; return false; } value = text ?? string.Empty; return true; } public bool TryGetFloat(int hash, out float value) { if (m_zdo == null) { value = 0f; return false; } float num = m_zdo.GetFloat(hash, float.MinValue); float num2 = m_zdo.GetFloat(hash, float.MaxValue); if (num == float.MinValue && num2 == float.MaxValue) { value = 0f; return false; } value = num; return true; } public bool TryGetLong(int hash, out long value) { if (m_zdo == null) { value = 0L; return false; } long num = m_zdo.GetLong(hash, long.MinValue); long num2 = m_zdo.GetLong(hash, long.MaxValue); if (num == long.MinValue && num2 == long.MaxValue) { value = 0L; return false; } value = num; return true; } public bool TryGetByteArray(int hash, out byte[] value) { if (m_zdo == null) { value = null; return false; } byte[] byteArray = m_zdo.GetByteArray(hash, (byte[])null); if (byteArray == null) { value = null; return false; } byte[] array = new byte[byteArray.Length]; Buffer.BlockCopy(byteArray, 0, array, 0, byteArray.Length); value = array; return true; } public bool TryGetVec3(int hash, out Vector3 value) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_0075: Unknown result type (might be due to invalid IL or missing references) if (m_zdo == null) { value = Vector3.zero; return false; } Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(float.MinValue, float.MinValue, float.MinValue); Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(float.MaxValue, float.MaxValue, float.MaxValue); Vector3 vec = m_zdo.GetVec3(hash, val); Vector3 vec2 = m_zdo.GetVec3(hash, val2); if (vec == val && vec2 == val2) { value = Vector3.zero; return false; } value = vec; return true; } } public sealed class CompanionZdoSnapshot { public long WorldUid { get; set; } public string CompanionGuid { get; set; } public long UserID { get; set; } public uint EntityID { get; set; } public int PrefabHash { get; set; } public string TimestampUtc { get; set; } public Dictionary IntValues { get; private set; } public Dictionary StringValues { get; private set; } public Dictionary FloatValues { get; private set; } public Dictionary LongValues { get; private set; } public Dictionary ByteArrayValues { get; private set; } public Dictionary Vec3Values { get; private set; } public SortedSet AbsentKeys { get; private set; } public string IntegritySha256 { get; set; } public CompanionZdoSnapshot() { WorldUid = 0L; CompanionGuid = string.Empty; IntValues = new Dictionary(); StringValues = new Dictionary(); FloatValues = new Dictionary(); LongValues = new Dictionary(); ByteArrayValues = new Dictionary(); Vec3Values = new Dictionary(); AbsentKeys = new SortedSet(StringComparer.Ordinal); } public static string FormatAbsentToken(char typeCode, int keyHash) { return typeCode + ":" + keyHash.ToString(CultureInfo.InvariantCulture); } public string ComputeSha256() { //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Unknown result type (might be due to invalid IL or missing references) //IL_0457: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("V2|W:").Append(WorldUid.ToString(CultureInfo.InvariantCulture)).Append("|G:") .Append(CompanionGuid ?? string.Empty) .Append("|U:") .Append(UserID.ToString(CultureInfo.InvariantCulture)) .Append("|E:") .Append(EntityID.ToString(CultureInfo.InvariantCulture)) .Append("|P:") .Append(PrefabHash.ToString(CultureInfo.InvariantCulture)) .Append(';'); foreach (KeyValuePair item in new SortedDictionary(IntValues)) { stringBuilder.Append("P:I:").Append(item.Key.ToString(CultureInfo.InvariantCulture)).Append('=') .Append(item.Value.ToString(CultureInfo.InvariantCulture)) .Append(';'); } foreach (KeyValuePair item2 in new SortedDictionary(StringValues)) { string text = item2.Value ?? string.Empty; stringBuilder.Append("P:S:").Append(item2.Key.ToString(CultureInfo.InvariantCulture)).Append("=#") .Append(text.Length.ToString(CultureInfo.InvariantCulture)) .Append(':') .Append(text) .Append(';'); } foreach (KeyValuePair item3 in new SortedDictionary(FloatValues)) { stringBuilder.Append("P:F:").Append(item3.Key.ToString(CultureInfo.InvariantCulture)).Append('=') .Append(item3.Value.ToString("R", CultureInfo.InvariantCulture)) .Append(';'); } foreach (KeyValuePair item4 in new SortedDictionary(LongValues)) { stringBuilder.Append("P:L:").Append(item4.Key.ToString(CultureInfo.InvariantCulture)).Append('=') .Append(item4.Value.ToString(CultureInfo.InvariantCulture)) .Append(';'); } foreach (KeyValuePair item5 in new SortedDictionary(ByteArrayValues)) { string value = ((item5.Value != null) ? Convert.ToBase64String(item5.Value) : string.Empty); int num = ((item5.Value != null) ? item5.Value.Length : (-1)); stringBuilder.Append("P:B:").Append(item5.Key.ToString(CultureInfo.InvariantCulture)).Append("=#") .Append(num.ToString(CultureInfo.InvariantCulture)) .Append(':') .Append(value) .Append(';'); } foreach (KeyValuePair item6 in new SortedDictionary(Vec3Values)) { StringBuilder stringBuilder2 = stringBuilder.Append("P:V:").Append(item6.Key.ToString(CultureInfo.InvariantCulture)).Append('='); float x = item6.Value.x; StringBuilder stringBuilder3 = stringBuilder2.Append(x.ToString("R", CultureInfo.InvariantCulture)).Append(','); float y = item6.Value.y; StringBuilder stringBuilder4 = stringBuilder3.Append(y.ToString("R", CultureInfo.InvariantCulture)).Append(','); float z = item6.Value.z; stringBuilder4.Append(z.ToString("R", CultureInfo.InvariantCulture)).Append(';'); } if (AbsentKeys != null) { foreach (string absentKey in AbsentKeys) { if (!string.IsNullOrEmpty(absentKey)) { stringBuilder.Append("A:").Append(absentKey).Append(';'); } } } using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())); StringBuilder stringBuilder5 = new StringBuilder(array.Length * 2); for (int i = 0; i < array.Length; i++) { stringBuilder5.Append(array[i].ToString("X2")); } return stringBuilder5.ToString(); } public string ComputeSessionIndependentContentSha256() { long userID = UserID; uint entityID = EntityID; try { UserID = 0L; EntityID = 0u; return ComputeSha256(); } finally { UserID = userID; EntityID = entityID; } } public bool VerifyIntegrity() { if (string.IsNullOrEmpty(IntegritySha256)) { return false; } return string.Equals(IntegritySha256, ComputeSha256(), StringComparison.OrdinalIgnoreCase); } public static CompanionZdoSnapshot CreateFromReader(IZdoPropertyReader reader, long worldUid = 0L, long userId = 0L, uint entityId = 0u, int prefabHash = 0) { //IL_027f: Unknown result type (might be due to invalid IL or missing references) if (reader == null) { return null; } string text = reader.GetString(CataclysmicStateReader.CompanionGuidKey, string.Empty); long num = reader.GetLong(CataclysmicStateReader.CompanionWorldUidKey, 0L); int num2 = reader.GetInt(CataclysmicStateReader.CompanionPrefabHashKey); CompanionZdoSnapshot companionZdoSnapshot = new CompanionZdoSnapshot(); companionZdoSnapshot.WorldUid = ((worldUid != 0) ? worldUid : num); companionZdoSnapshot.CompanionGuid = text ?? string.Empty; companionZdoSnapshot.UserID = userId; companionZdoSnapshot.EntityID = entityId; companionZdoSnapshot.PrefabHash = ((prefabHash != 0) ? prefabHash : num2); companionZdoSnapshot.TimestampUtc = DateTime.UtcNow.ToString("o"); CompanionZdoSnapshot companionZdoSnapshot2 = companionZdoSnapshot; IZdoExtendedPropertyReader zdoExtendedPropertyReader = reader as IZdoExtendedPropertyReader; int[] allCanonicalIntKeys = CataclysmicStateReader.AllCanonicalIntKeys; foreach (int num3 in allCanonicalIntKeys) { if (TryReadIntCanonical(reader, zdoExtendedPropertyReader, num3, out var value)) { companionZdoSnapshot2.IntValues[num3] = value; } else { companionZdoSnapshot2.AbsentKeys.Add(FormatAbsentToken('I', num3)); } } int[] allCanonicalStringKeys = CataclysmicStateReader.AllCanonicalStringKeys; foreach (int num4 in allCanonicalStringKeys) { if (TryReadStringCanonical(reader, zdoExtendedPropertyReader, num4, out var value2)) { companionZdoSnapshot2.StringValues[num4] = value2 ?? string.Empty; } else { companionZdoSnapshot2.AbsentKeys.Add(FormatAbsentToken('S', num4)); } } int[] allCanonicalFloatKeys = CataclysmicStateReader.AllCanonicalFloatKeys; foreach (int num5 in allCanonicalFloatKeys) { if (TryReadFloatCanonical(reader, zdoExtendedPropertyReader, num5, out var value3)) { companionZdoSnapshot2.FloatValues[num5] = value3; } else { companionZdoSnapshot2.AbsentKeys.Add(FormatAbsentToken('F', num5)); } } int[] allCanonicalLongKeys = CataclysmicStateReader.AllCanonicalLongKeys; foreach (int num6 in allCanonicalLongKeys) { if (TryReadLongCanonical(reader, zdoExtendedPropertyReader, num6, out var value4)) { companionZdoSnapshot2.LongValues[num6] = value4; } else { companionZdoSnapshot2.AbsentKeys.Add(FormatAbsentToken('L', num6)); } } int[] allCanonicalByteArrayKeys = CataclysmicStateReader.AllCanonicalByteArrayKeys; foreach (int num7 in allCanonicalByteArrayKeys) { if (zdoExtendedPropertyReader != null && zdoExtendedPropertyReader.TryGetByteArray(num7, out var value5)) { companionZdoSnapshot2.ByteArrayValues[num7] = value5; } else { companionZdoSnapshot2.AbsentKeys.Add(FormatAbsentToken('B', num7)); } } int[] allCanonicalVec3Keys = CataclysmicStateReader.AllCanonicalVec3Keys; foreach (int num8 in allCanonicalVec3Keys) { if (zdoExtendedPropertyReader != null && zdoExtendedPropertyReader.TryGetVec3(num8, out var value6)) { companionZdoSnapshot2.Vec3Values[num8] = value6; } else { companionZdoSnapshot2.AbsentKeys.Add(FormatAbsentToken('V', num8)); } } companionZdoSnapshot2.IntegritySha256 = companionZdoSnapshot2.ComputeSha256(); return companionZdoSnapshot2; } private static bool TryReadIntCanonical(IZdoPropertyReader r, IZdoExtendedPropertyReader ext, int hash, out int value) { if (ext != null) { return ext.TryGetInt(hash, out value); } int num = r.GetInt(hash, int.MinValue); int num2 = r.GetInt(hash, int.MaxValue); if (num == int.MinValue && num2 == int.MaxValue) { value = 0; return false; } value = num; return true; } private static bool TryReadStringCanonical(IZdoPropertyReader r, IZdoExtendedPropertyReader ext, int hash, out string value) { if (ext != null) { return ext.TryGetString(hash, out value); } string text = r.GetString(hash, "\0__TM_ABSENT_A__"); string text2 = r.GetString(hash, "\0__TM_ABSENT_B__"); if (text == "\0__TM_ABSENT_A__" && text2 == "\0__TM_ABSENT_B__") { value = null; return false; } value = text ?? string.Empty; return true; } private static bool TryReadFloatCanonical(IZdoPropertyReader r, IZdoExtendedPropertyReader ext, int hash, out float value) { if (ext != null) { return ext.TryGetFloat(hash, out value); } float num = r.GetFloat(hash, float.MinValue); float num2 = r.GetFloat(hash, float.MaxValue); if (num == float.MinValue && num2 == float.MaxValue) { value = 0f; return false; } value = num; return true; } private static bool TryReadLongCanonical(IZdoPropertyReader r, IZdoExtendedPropertyReader ext, int hash, out long value) { if (ext != null) { return ext.TryGetLong(hash, out value); } long num = r.GetLong(hash, long.MinValue); long num2 = r.GetLong(hash, long.MaxValue); if (num == long.MinValue && num2 == long.MaxValue) { value = 0L; return false; } value = num; return true; } public static CompanionZdoSnapshot Create(ZDO zdo) { if (zdo == null) { return null; } long worldUid = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetWorldUID() : zdo.GetLong(CataclysmicStateReader.CompanionWorldUidKey, 0L)); return CreateFromReader(new ValheimZdoReader(zdo), worldUid, ((ZDOID)(ref zdo.m_uid)).UserID, ((ZDOID)(ref zdo.m_uid)).ID, zdo.GetPrefab()); } } public static class CataclysmicStateReader { public const int MaxSafetyZdoCeiling = 300000; public static readonly int SavedTierKey = StringExtensionMethods.GetStableHashCode("TM_070_BaseTier"); public static readonly int SavedEventKey = StringExtensionMethods.GetStableHashCode("TM_070_CataclysmEvent"); public static readonly int TierOverrideKey = StringExtensionMethods.GetStableHashCode("tm_tier_override"); public static readonly int IsUndeadKey = StringExtensionMethods.GetStableHashCode("TM_IsUndead"); public static readonly int IsCataclysmicKey = StringExtensionMethods.GetStableHashCode("TM_IsCataclysmic"); public static readonly int CompanionGuidKey = StringExtensionMethods.GetStableHashCode("tm_companion_guid"); public static readonly int CompanionWorldUidKey = StringExtensionMethods.GetStableHashCode("tm_companion_world_uid"); public static readonly int CompanionPrefabHashKey = StringExtensionMethods.GetStableHashCode("tm_companion_prefab_hash"); public static readonly int RitualTxStateKey = StringExtensionMethods.GetStableHashCode("tm_ritual_tx_state"); public static readonly int RitualTxIdKey = StringExtensionMethods.GetStableHashCode("tm_ritual_tx_id"); public static readonly int HarmonizedFromLegacyKey = StringExtensionMethods.GetStableHashCode("tm_harmonized_from_legacy"); public static readonly int HarmonizedTargetTierKey = StringExtensionMethods.GetStableHashCode("tm_harmonized_target_tier"); public static readonly int HarmonizedTimestampKey = StringExtensionMethods.GetStableHashCode("tm_harmonized_timestamp"); public static readonly int SpecialProfileKey = StringExtensionMethods.GetStableHashCode("TM_070_SpecialProfile"); public static readonly int TierHpInitKey = StringExtensionMethods.GetStableHashCode("tm_tier_hp_init"); public static readonly int MaxHealthKey = StringExtensionMethods.GetStableHashCode("max_health"); public static readonly int HealthKey = StringExtensionMethods.GetStableHashCode("health"); public static readonly int ModifiersKey = StringExtensionMethods.GetStableHashCode("modifiers"); public static readonly int WildLevelKey = StringExtensionMethods.GetStableHashCode("level"); public static readonly int CompanionLevelKey = StringExtensionMethods.GetStableHashCode("tm_level"); public static readonly int CompanionXpKey = StringExtensionMethods.GetStableHashCode("tm_xp"); public static readonly int CompanionPointsKey = StringExtensionMethods.GetStableHashCode("tm_points"); public static readonly int StatHealthKey = StringExtensionMethods.GetStableHashCode("tm_stat_health"); public static readonly int StatStaminaKey = StringExtensionMethods.GetStableHashCode("tm_stat_stamina"); public static readonly int StatDamageKey = StringExtensionMethods.GetStableHashCode("tm_stat_damage"); public static readonly int StatDefenseKey = StringExtensionMethods.GetStableHashCode("tm_stat_defense"); public static readonly int StatSpeedKey = StringExtensionMethods.GetStableHashCode("tm_stat_speed"); public static readonly int ItemsByteKey = StringExtensionMethods.GetStableHashCode("items"); public static readonly int BagItemsStringKey = StringExtensionMethods.GetStableHashCode("tm_bag_items"); public static readonly int EquippedChestKey = StringExtensionMethods.GetStableHashCode("tm_eq_chest"); public static readonly int EquippedCollarKey = StringExtensionMethods.GetStableHashCode("tm_eq_collar"); public static readonly int EquippedSaddleKey = StringExtensionMethods.GetStableHashCode("tm_eq_saddle"); public static readonly int TamedNameKey = StringExtensionMethods.GetStableHashCode("TamedName"); public static readonly int CustomNameKey = StringExtensionMethods.GetStableHashCode("tm_custom_name"); public static readonly int OwnerIdKey = StringExtensionMethods.GetStableHashCode("tm_owner"); public static readonly int OwnerNameKey = StringExtensionMethods.GetStableHashCode("tm_owner_name"); public static readonly int TamedBoolKey = StringExtensionMethods.GetStableHashCode("tamed"); public static readonly int HaveSaddleKey = StringExtensionMethods.GetStableHashCode("HaveSaddle"); public static readonly int MasteryBranchKey = StringExtensionMethods.GetStableHashCode("tm_mastery"); public static readonly int ActiveMasteryKey = StringExtensionMethods.GetStableHashCode("tm_active_mastery"); public static readonly int MasteryPointsKey = StringExtensionMethods.GetStableHashCode("tm_mastery_points"); public static readonly int MasteryUnlocksKey = StringExtensionMethods.GetStableHashCode("tm_mastery_unlocks"); public static readonly int LegacyUndeadFlagKey = StringExtensionMethods.GetStableHashCode("tm_undead"); public static readonly int SpectralVeilKey = StringExtensionMethods.GetStableHashCode("tm_buff_spectral_veil"); public static readonly int HomePositionKey = StringExtensionMethods.GetStableHashCode("spawnpoint"); public static readonly int[] AllCanonicalIntKeys = new int[24] { SavedTierKey, TierOverrideKey, IsUndeadKey, IsCataclysmicKey, CompanionPrefabHashKey, RitualTxStateKey, HarmonizedFromLegacyKey, HarmonizedTargetTierKey, SpecialProfileKey, TierHpInitKey, ModifiersKey, WildLevelKey, CompanionLevelKey, CompanionPointsKey, StatHealthKey, StatStaminaKey, StatDamageKey, StatDefenseKey, StatSpeedKey, TamedBoolKey, HaveSaddleKey, MasteryBranchKey, MasteryPointsKey, LegacyUndeadFlagKey }; public static readonly int[] AllCanonicalStringKeys = new int[14] { SavedEventKey, CompanionGuidKey, RitualTxIdKey, HarmonizedTimestampKey, BagItemsStringKey, EquippedChestKey, EquippedCollarKey, EquippedSaddleKey, TamedNameKey, CustomNameKey, OwnerIdKey, OwnerNameKey, ActiveMasteryKey, MasteryUnlocksKey }; public static readonly int[] AllCanonicalFloatKeys = new int[3] { MaxHealthKey, HealthKey, CompanionXpKey }; public static readonly int[] AllCanonicalLongKeys = new int[3] { CompanionWorldUidKey, SpectralVeilKey, OwnerIdKey }; public static readonly int[] AllCanonicalByteArrayKeys = new int[1] { ItemsByteKey }; public static readonly int[] AllCanonicalVec3Keys = new int[1] { HomePositionKey }; internal static Func WorldExecutionModeResolverForTests = null; internal static Func WorldLoadingCompletedResolverForTests = null; internal static Func SaveStateSafeResolverForTests = null; internal static Func ZdoObjectsCountResolverForTests = null; public static string GenerateCompanionGuid() { byte[] array = new byte[16]; using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create()) { randomNumberGenerator.GetBytes(array); } array[6] = (byte)((array[6] & 0xF) | 0x40); array[8] = (byte)((array[8] & 0x3F) | 0x80); return new Guid(array).ToString("N", CultureInfo.InvariantCulture).ToLowerInvariant(); } public static bool IsValidCompanionGuid(string guid) { if (string.IsNullOrEmpty(guid) || guid.Length != 32) { return false; } if (!Guid.TryParseExact(guid, "N", out var result)) { return false; } return result != Guid.Empty; } public static CompanionIdentityResolution ResolveCompanionIdentity(string expectedGuid, long expectedWorldUid, int expectedPrefabHash, IEnumerable worldZdos, ZdoInspectionScope scope) { CompanionIdentityResolution companionIdentityResolution = new CompanionIdentityResolution(); companionIdentityResolution.CompanionGuid = expectedGuid ?? string.Empty; companionIdentityResolution.ExpectedWorldUid = expectedWorldUid; companionIdentityResolution.ExpectedPrefabHash = expectedPrefabHash; companionIdentityResolution.Scope = scope; companionIdentityResolution.IsUnambiguousAndSafe = false; companionIdentityResolution.IsGlobalUniquenessProven = false; companionIdentityResolution.MatchCount = 0; companionIdentityResolution.MatchedReader = null; CompanionIdentityResolution companionIdentityResolution2 = companionIdentityResolution; if (!IsValidCompanionGuid(expectedGuid)) { companionIdentityResolution2.FailureReason = "CompanionGuid inválido, vacío o con formato distinto a 128 bits hex."; return companionIdentityResolution2; } if (expectedWorldUid == 0 || expectedPrefabHash == 0) { companionIdentityResolution2.FailureReason = "WorldUid o PrefabHash esperado no válido (cero)."; return companionIdentityResolution2; } if (worldZdos == null) { companionIdentityResolution2.FailureReason = "Conjunto de ZDOs a inspeccionar es nulo."; return companionIdentityResolution2; } IZdoPropertyReader zdoPropertyReader = null; int num = 0; foreach (IZdoPropertyReader worldZdo in worldZdos) { if (worldZdo == null) { continue; } string a = worldZdo.GetString(CompanionGuidKey, string.Empty); if (string.Equals(a, expectedGuid, StringComparison.OrdinalIgnoreCase)) { num++; if (zdoPropertyReader == null) { zdoPropertyReader = worldZdo; } } } companionIdentityResolution2.MatchCount = num; if (num > 1) { companionIdentityResolution2.FailureReason = $"Ambigüedad crítica: se detectaron {num} entidades con el mismo CompanionGuid '{expectedGuid}'. Operación abortada."; return companionIdentityResolution2; } if (num == 0) { companionIdentityResolution2.FailureReason = $"No se encontró ninguna entidad con CompanionGuid '{expectedGuid}' en el conjunto inspeccionado."; return companionIdentityResolution2; } long num2 = zdoPropertyReader.GetLong(CompanionWorldUidKey, 0L); int num3 = zdoPropertyReader.GetInt(CompanionPrefabHashKey); if (num2 != expectedWorldUid) { companionIdentityResolution2.FailureReason = $"Discrepancia de WorldUid: el ZDO registra {num2}, pero se esperaba {expectedWorldUid}."; return companionIdentityResolution2; } if (num3 != expectedPrefabHash) { companionIdentityResolution2.FailureReason = $"Discrepancia de PrefabHash: el ZDO registra {num3}, pero se esperaba {expectedPrefabHash}."; return companionIdentityResolution2; } companionIdentityResolution2.MatchedReader = zdoPropertyReader; if (scope != ZdoInspectionScope.CompleteWorldVerified) { companionIdentityResolution2.IsGlobalUniquenessProven = false; companionIdentityResolution2.IsUnambiguousAndSafe = false; companionIdentityResolution2.FailureReason = "Inspección parcial del mundo (PartialOrUnverified): no se puede declarar unicidad global del CompanionGuid ni autorizar restauración."; return companionIdentityResolution2; } companionIdentityResolution2.IsGlobalUniquenessProven = true; companionIdentityResolution2.IsUnambiguousAndSafe = true; companionIdentityResolution2.FailureReason = null; return companionIdentityResolution2; } public static CataclysmicClassification Classify(IZdoPropertyReader reader) { if (reader == null) { return CataclysmicClassification.CorruptOrIncomplete; } int num = reader.GetInt(RitualTxStateKey); if (num == 1 || num == 3) { return CataclysmicClassification.CorruptOrIncomplete; } int num2 = reader.GetInt(SavedTierKey); int num3 = reader.GetInt(TierOverrideKey); int num4 = ((num2 > 0) ? num2 : num3); int num5 = reader.GetInt(IsCataclysmicKey); bool flag = reader.GetInt(IsUndeadKey) == 1; switch (num4) { default: return CataclysmicClassification.CorruptOrIncomplete; case 9: if (!flag) { return CataclysmicClassification.LegacyAmbiguous; } return CataclysmicClassification.LegacyAmbiguousUndead; case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 10: case 11: if (num5 == 1) { if ((num4 >= 1 && num4 <= 8) || num4 == 10) { return CataclysmicClassification.DecoupledCataclysmic; } return CataclysmicClassification.CorruptOrIncomplete; } if ((num4 >= 1 && num4 <= 8) || num4 == 10) { return CataclysmicClassification.NormalValid; } return CataclysmicClassification.CorruptOrIncomplete; } } public static CataclysmicClassification Classify(ZDO zdo) { if (zdo == null) { return CataclysmicClassification.CorruptOrIncomplete; } return Classify((IZdoPropertyReader)new ValheimZdoReader(zdo)); } public static bool IsCataclysmic(IZdoPropertyReader reader) { if (reader == null) { return false; } CataclysmicClassification cataclysmicClassification = Classify(reader); if (cataclysmicClassification != CataclysmicClassification.LegacyAmbiguous && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguousUndead) { return cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic; } return true; } public static bool IsCataclysmic(ZDO zdo) { if (zdo == null) { return false; } return IsCataclysmic((IZdoPropertyReader)new ValheimZdoReader(zdo)); } public static bool IsUndead(IZdoPropertyReader reader) { if (reader == null) { return false; } return reader.GetInt(IsUndeadKey) == 1; } public static bool IsUndead(ZDO zdo) { if (zdo == null) { return false; } return IsUndead((IZdoPropertyReader)new ValheimZdoReader(zdo)); } public static int GetEffectiveBaseTier(IZdoPropertyReader reader) { if (reader == null) { return 0; } switch (Classify(reader)) { case CataclysmicClassification.NormalValid: case CataclysmicClassification.DecoupledCataclysmic: { int num = reader.GetInt(SavedTierKey); if (num <= 0) { num = reader.GetInt(TierOverrideKey, 1); } return Mathf.Clamp(num, 1, 10); } case CataclysmicClassification.LegacyAmbiguous: case CataclysmicClassification.LegacyAmbiguousUndead: return 9; default: return 0; } } public static int GetEffectiveBaseTier(ZDO zdo) { if (zdo == null) { return 0; } return GetEffectiveBaseTier((IZdoPropertyReader)new ValheimZdoReader(zdo)); } public static bool HasIndependentCataclysmicMitigation(IZdoPropertyReader reader) { CataclysmicClassification cataclysmicClassification = Classify(reader); return cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic; } public static bool HasIndependentCataclysmicMitigation(ZDO zdo) { if (zdo == null) { return false; } return HasIndependentCataclysmicMitigation((IZdoPropertyReader)new ValheimZdoReader(zdo)); } public static bool HasWriteAuthority(ZNetView netView) { if (object.ReferenceEquals(netView, null)) { return false; } try { if (!netView.IsValid()) { return false; } return netView.IsOwner(); } catch { return false; } } public static bool HasWriteAuthorityForZdo(ZDO zdo) { if (zdo == null) { return false; } if ((Object)(object)ZNet.instance == (Object)null) { return true; } return zdo.IsOwner(); } public static ZdoInspectionScope AssessLiveWorldZdoScope(out int loadedZdoCount, out string explanation) { loadedZdoCount = 0; try { if (ZDOMan.instance != null) { loadedZdoCount = ZDOMan.instance.NrOfObjects(); } } catch { } explanation = string.Format(CultureInfo.InvariantCulture, "Alcance parcial en vivo (PartialOrUnverified): ZDOMan mantiene {0} ZDOs en memoria de los sectores actualmente cargados. Los sectores inactivos residen en disco en el archivo .db del mundo; ZNet.IsServer() no garantiza cobertura completa del 100% del mundo.", loadedZdoCount); return ZdoInspectionScope.PartialOrUnverified; } public static WorldExecutionMode AssessWorldExecutionMode(out string detail) { detail = string.Empty; if (WorldExecutionModeResolverForTests != null) { WorldExecutionMode worldExecutionMode = WorldExecutionModeResolverForTests(); detail = "Modo forzado por entorno de pruebas: " + worldExecutionMode; return worldExecutionMode; } if ((Object)(object)ZNet.instance == (Object)null) { detail = "ZNet.instance no está inicializado."; return WorldExecutionMode.Unknown; } try { if (!ZNet.instance.IsServer()) { detail = "Cliente remoto multijugador conectado a un servidor."; return WorldExecutionMode.RemoteClient; } if (ZNet.instance.IsDedicated()) { detail = "Servidor dedicado sin jugador local."; return WorldExecutionMode.DedicatedServer; } bool flag = false; try { flag = ZNet.IsOpenServer(); } catch { } int num = 0; try { num = ZNet.instance.GetPeers()?.Count ?? 0; } catch { } if (flag || num > 0) { detail = string.Format(CultureInfo.InvariantCulture, "Anfitrión local con servidor abierto ({0}) o clientes conectados ({1}).", flag, num); return WorldExecutionMode.LocalHost; } detail = "Partida local en solitario (Singleplayer): servidor local, 0 clientes y servidor privado."; return WorldExecutionMode.Singleplayer; } catch (Exception ex) { detail = "Error evaluando modo de ejecución: " + ex.Message; return WorldExecutionMode.Unknown; } } public static bool IsWorldLoadingCompleted(out string failureReason) { failureReason = null; if (WorldLoadingCompletedResolverForTests != null) { bool flag = WorldLoadingCompletedResolverForTests(); if (!flag) { failureReason = "Carga de mundo incompleta (simulada en pruebas)."; } return flag; } if ((Object)(object)ZNet.instance == (Object)null) { failureReason = "ZNet.instance es nulo."; return false; } try { Assembly assembly = typeof(ZNet).Assembly; Type type = assembly.GetType("Player"); if (type == null) { failureReason = "Tipo Player no encontrado."; return false; } FieldInfo field = type.GetField("m_localPlayer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object obj = ((field != null) ? field.GetValue(null) : null); if (obj == null) { failureReason = "Player.m_localPlayer es nulo."; return false; } MethodInfo method = obj.GetType().GetMethod("IsDead", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method != null && (bool)method.Invoke(obj, null)) { failureReason = "Player.m_localPlayer está muerto."; return false; } MethodInfo method2 = obj.GetType().GetMethod("IsTeleporting", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method2 != null && (bool)method2.Invoke(obj, null)) { failureReason = "El jugador local se encuentra en teletransporte."; return false; } FieldInfo field2 = type.GetField("m_isLoading", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field2 != null && (bool)field2.GetValue(obj)) { failureReason = "Player.m_isLoading es true (inventario/datos aún cargando)."; return false; } Type type2 = assembly.GetType("ZNetScene"); if (type2 != null) { PropertyInfo property = type2.GetProperty("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object obj2 = ((property != null) ? property.GetValue(null, null) : null); if (obj2 != null) { MethodInfo method3 = type2.GetMethod("InLoadingScreen", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method3 != null && (bool)method3.Invoke(obj2, null)) { failureReason = "ZNetScene reporta pantalla de carga activa."; return false; } } } Type type3 = assembly.GetType("ZoneSystem"); if (type3 != null) { PropertyInfo property2 = type3.GetProperty("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object obj3 = ((property2 != null) ? property2.GetValue(null, null) : null); if (obj3 != null) { MethodInfo method4 = type3.GetMethod("IsActiveAreaLoaded", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method4 != null && !(bool)method4.Invoke(obj3, null)) { failureReason = "ZoneSystem reporta que el área activa no ha terminado de cargar."; return false; } } } } catch (Exception ex) { failureReason = "Error inspeccionando estado de carga: " + ex.Message; return false; } return true; } public static bool IsSaveStateSafe(out string failureReason) { failureReason = null; if (SaveStateSafeResolverForTests != null) { bool flag = SaveStateSafeResolverForTests(); if (!flag) { failureReason = "Estado de guardado inseguro (simulado en pruebas)."; } return flag; } if (ZDOMan.instance == null) { failureReason = "ZDOMan.instance es nulo."; return false; } try { FieldInfo field = typeof(ZDOMan).GetField("m_currentSaveState", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(ZDOMan.instance); if (Convert.ToInt32(value, CultureInfo.InvariantCulture) != 0) { failureReason = string.Format(CultureInfo.InvariantCulture, "Estado de guardado inseguro: ZDOMan.m_currentSaveState = {0} (guardado asíncrono activo).", value); return false; } } } catch (Exception ex) { failureReason = "Error inspeccionando estado de guardado de ZDOMan: " + ex.Message; return false; } return true; } public static ZdoInspectionScope AssessCompleteWorldZdoScope(out int loadedZdoCount, out WorldExecutionMode mode, out string explanation) { loadedZdoCount = 0; mode = AssessWorldExecutionMode(out var detail); if (mode != WorldExecutionMode.Singleplayer) { explanation = string.Format(CultureInfo.InvariantCulture, "Alcance parcial forzado: la modalidad '{0}' no garantiza censo exhaustivo en el cliente ({1}).", mode, detail); return ZdoInspectionScope.PartialOrUnverified; } if (!IsWorldLoadingCompleted(out var failureReason)) { explanation = "Alcance parcial: la carga del mundo no ha concluido (" + failureReason + ")."; return ZdoInspectionScope.PartialOrUnverified; } if (!IsSaveStateSafe(out var failureReason2)) { explanation = "Alcance parcial: estado de guardado inseguro (" + failureReason2 + ")."; return ZdoInspectionScope.PartialOrUnverified; } if (ZdoObjectsCountResolverForTests != null) { loadedZdoCount = ZdoObjectsCountResolverForTests(); } else { if (ZDOMan.instance == null) { explanation = "Alcance parcial: ZDOMan.instance es nulo."; return ZdoInspectionScope.PartialOrUnverified; } try { FieldInfo field = typeof(ZDOMan).GetField("m_objectsByID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { explanation = "Alcance parcial: no se pudo acceder al diccionario m_objectsByID de ZDOMan."; return ZdoInspectionScope.PartialOrUnverified; } if (!(field.GetValue(ZDOMan.instance) is IDictionary dictionary)) { explanation = "Alcance parcial: m_objectsByID no es un diccionario válido."; return ZdoInspectionScope.PartialOrUnverified; } loadedZdoCount = dictionary.Count; } catch (Exception ex) { explanation = "Alcance parcial: excepción leyendo objetos de ZDOMan: " + ex.Message; return ZdoInspectionScope.PartialOrUnverified; } } if (loadedZdoCount <= 0) { explanation = "Alcance parcial: ZDOMan no contiene objetos persistentes registrados."; return ZdoInspectionScope.PartialOrUnverified; } if (loadedZdoCount > 300000) { explanation = string.Format(CultureInfo.InvariantCulture, "Alcance parcial: la cantidad de objetos ({0}) supera el techo máximo de seguridad de laboratorio ({1}).", loadedZdoCount, 300000); return ZdoInspectionScope.PartialOrUnverified; } explanation = string.Format(CultureInfo.InvariantCulture, "Cobertura completa verificada (CompleteWorldVerified): Singleplayer con censo exhaustivo de {0} ZDOs en memoria, carga finalizada y sin operaciones de guardado concurrentes.", loadedZdoCount); return ZdoInspectionScope.CompleteWorldVerified; } public static CompanionZdoSnapshot CreateSnapshot(ZDO zdo) { return CompanionZdoSnapshot.Create(zdo); } public static bool VerifySubsetCUnchanged(CompanionZdoSnapshot before, CompanionZdoSnapshot after, out string diffReason) { diffReason = null; if (before == null || after == null) { diffReason = "Uno o ambos snapshots son nulos."; return false; } int[] array = new int[14] { WildLevelKey, CompanionLevelKey, CompanionPointsKey, StatHealthKey, StatStaminaKey, StatDamageKey, StatDefenseKey, StatSpeedKey, TamedBoolKey, HaveSaddleKey, MasteryBranchKey, MasteryPointsKey, LegacyUndeadFlagKey, IsUndeadKey }; int[] array2 = array; foreach (int num in array2) { int num2 = (before.IntValues.ContainsKey(num) ? before.IntValues[num] : 0); int num3 = (after.IntValues.ContainsKey(num) ? after.IntValues[num] : 0); bool flag = before.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('I', num)); bool flag2 = after.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('I', num)); if (flag != flag2 || num2 != num3) { diffReason = string.Format(CultureInfo.InvariantCulture, "Discrepancia en clave int de Subset C ({0}): antes={1} (abs={2}), despues={3} (abs={4})", num, num2, flag, num3, flag2); return false; } } int[] array3 = new int[11] { SavedEventKey, BagItemsStringKey, EquippedChestKey, EquippedCollarKey, EquippedSaddleKey, TamedNameKey, CustomNameKey, OwnerIdKey, OwnerNameKey, ActiveMasteryKey, MasteryUnlocksKey }; int[] array4 = array3; foreach (int num4 in array4) { string text = (before.StringValues.ContainsKey(num4) ? before.StringValues[num4] : ""); string text2 = (after.StringValues.ContainsKey(num4) ? after.StringValues[num4] : ""); bool flag3 = before.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('S', num4)); bool flag4 = after.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('S', num4)); if (flag3 != flag4 || !string.Equals(text, text2, StringComparison.Ordinal)) { diffReason = string.Format(CultureInfo.InvariantCulture, "Discrepancia en clave string de Subset C ({0}): antes='{1}' (abs={2}), despues='{3}' (abs={4})", num4, text, flag3, text2, flag4); return false; } } long value; bool flag5 = before.LongValues.TryGetValue(OwnerIdKey, out value); long value2; bool flag6 = after.LongValues.TryGetValue(OwnerIdKey, out value2); if (flag5 != flag6 || value != value2) { diffReason = "El propietario nativo tm_owner (long) cambió."; return false; } int companionXpKey = CompanionXpKey; float num5 = (before.FloatValues.ContainsKey(companionXpKey) ? before.FloatValues[companionXpKey] : 0f); float num6 = (after.FloatValues.ContainsKey(companionXpKey) ? after.FloatValues[companionXpKey] : 0f); bool flag7 = before.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('F', companionXpKey)); bool flag8 = after.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('F', companionXpKey)); if (flag7 != flag8 || Math.Abs(num5 - num6) > 0.0001f) { diffReason = string.Format(CultureInfo.InvariantCulture, "Discrepancia en XP de Subset C: antes={0}, despues={1}", num5, num6); return false; } int itemsByteKey = ItemsByteKey; byte[] array5 = (before.ByteArrayValues.ContainsKey(itemsByteKey) ? before.ByteArrayValues[itemsByteKey] : null); byte[] array6 = (after.ByteArrayValues.ContainsKey(itemsByteKey) ? after.ByteArrayValues[itemsByteKey] : null); bool flag9 = before.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('B', itemsByteKey)); bool flag10 = after.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('B', itemsByteKey)); if (flag9 != flag10) { diffReason = string.Format(CultureInfo.InvariantCulture, "Discrepancia en presencia de alforjas (items byte[]): abs1={0}, abs2={1}", flag9, flag10); return false; } if (array5 != null || array6 != null) { if (array5 == null || array6 == null || array5.Length != array6.Length) { diffReason = "Discrepancia en longitud de bytes de alforjas (items byte[])."; return false; } for (int k = 0; k < array5.Length; k++) { if (array5[k] != array6[k]) { diffReason = string.Format(CultureInfo.InvariantCulture, "Discrepancia a nivel de byte en alforjas en el indice {0}.", k); return false; } } } return true; } } internal static class ChestFoodQuery { private static List containers; private static ConfigEntry range; private static ConfigEntry wildEnabled; private static ConfigEntry tameEnabled; private static ConfigEntry onlyFood; internal static float Range { get { Initialize(); return Mathf.Max(0f, range.Value); } } internal static bool OnlyFoodChests { get { Initialize(); return onlyFood.Value; } } internal static void Initialize() { if (range == null || containers == null || wildEnabled == null || tameEnabled == null || onlyFood == null) { Type type = Type.GetType("TameMate.FeedingRegistry, TameMate"); Type type2 = Type.GetType("TameMate.TameMateConfig, TameMate"); if (type == null || type2 == null) { throw new NotSupportedException("Chest feeding core types unavailable"); } containers = AccessTools.Field(type, "Containers").GetValue(null) as List; range = AccessTools.Field(type2, "ChestFeedingRange").GetValue(null) as ConfigEntry; wildEnabled = AccessTools.Field(type2, "WildChestFeeding").GetValue(null) as ConfigEntry; tameEnabled = AccessTools.Field(type2, "TameChestFeeding").GetValue(null) as ConfigEntry; onlyFood = AccessTools.Field(type2, "OnlyFoodChests").GetValue(null) as ConfigEntry; if (containers == null || range == null || wildEnabled == null || tameEnabled == null || onlyFood == null) { throw new NotSupportedException("Chest feeding core fields unavailable"); } } } internal static bool Enabled(Character creature) { if ((Object)(object)creature == (Object)null) { return false; } Initialize(); if (!creature.IsTamed()) { return wildEnabled.Value; } return tameEnabled.Value; } private static bool Accepts(MonsterAI monster, bool herbivore, ItemData item) { if (item == null || item.m_shared == null || item.m_stack <= 0) { return false; } if (herbivore) { return TamingRules0740.IsHerbivoreFood(item); } if ((Object)(object)item.m_dropPrefab == (Object)null) { return false; } if ((Object)(object)monster == (Object)null || monster.m_consumeItems == null) { return false; } for (int i = 0; i < monster.m_consumeItems.Count; i++) { ItemDrop val = monster.m_consumeItems[i]; if ((Object)(object)val != (Object)null && val.m_itemData != null && val.m_itemData.m_shared != null && val.m_itemData.m_shared.m_name == item.m_shared.m_name) { return true; } } return false; } private static Inventory EligibleInventory(Container chest, Vector3 position, float squaredRange, MonsterAI monster, bool herbivore) { //IL_002b: 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_0031: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)chest == (Object)null) { return null; } Piece component = ((Component)chest).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsPlacedByPlayer()) { return null; } if (Vector3.SqrMagnitude(((Component)chest).transform.position - position) > squaredRange) { return null; } Inventory inventory = chest.GetInventory(); if (inventory == null) { return null; } if (onlyFood.Value) { List allItems = inventory.GetAllItems(); if (allItems == null || allItems.Count == 0) { return null; } for (int i = 0; i < allItems.Count; i++) { if (!Accepts(monster, herbivore, allItems[i])) { return null; } } } return inventory; } internal static int Find(Character creature, bool firstOnly, out Container source, out ItemData meal, out string sampleName) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) source = null; meal = null; sampleName = ""; if (!Enabled(creature)) { return 0; } float num = Range; float squaredRange = num * num; MonsterAI component = ((Component)creature).GetComponent(); bool flag = (Object)(object)component == (Object)null && (Object)(object)((Component)creature).GetComponent() != (Object)null; if ((Object)(object)component == (Object)null && !flag) { return 0; } int num2 = 0; for (int num3 = containers.Count - 1; num3 >= 0; num3--) { Container val = containers[num3]; Inventory val2 = EligibleInventory(val, ((Component)creature).transform.position, squaredRange, component, flag); if (val2 != null) { List allItems = val2.GetAllItems(); if (allItems != null) { for (int i = 0; i < allItems.Count; i++) { ItemData val3 = allItems[i]; if (Accepts(component, flag, val3)) { num2 += val3.m_stack; if (meal == null) { source = val; meal = val3; sampleName = val3.m_shared.m_name; } if (firstOnly) { return num2; } } } } } } return num2; } } public static class CommandWheelSaddlebagsIntegration { private const BindingFlags AllFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; public const float MaxSaddlebagOpenSurfaceDistance = 6f; public const float MaxSaddlebagKeepOpenSurfaceDistance = 7.5f; private const int SectorTextureWidth = 152; private const int SectorTextureHeight = 128; private const float SectorInnerRadius = 116f; private const float SectorOuterRadius = 222f; private const float SectorTextureMargin = 4f; private const int DismountIconIndex = 9; public const float LegacyArtificialHoverOffset = 8.5f; private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.WheelSaddlebags"); private static Type s_commandWheelType; private static Type s_companionRuntimeType; private static Type s_companionStateType; private static Type s_tameInteractPatchType; private static Type s_tameHoverPatchType; private static Type s_biomeReadinessEngineType; private static PropertyInfo s_isOpenProp; private static FieldInfo s_pageField; private static FieldInfo s_scopeField; private static FieldInfo s_selectedField; private static FieldInfo s_selectedGroupField; private static FieldInfo s_lockedTargetField; private static FieldInfo s_centerField; private static FieldInfo s_suppressHotbarUntilField; private static FieldInfo s_medallionStyleField; private static FieldInfo s_medallionSelectedStyleField; private static FieldInfo s_centerStyleField; private static FieldInfo s_pillStyleField; private static MethodInfo s_ensureStylesMethod; private static MethodInfo s_currentTargetMethod; private static MethodInfo s_labelsMethod; private static MethodInfo s_glyphsMethod; private static MethodInfo s_selectMethod; private static MethodInfo s_closeMethod; private static MethodInfo s_stepSelectionMethod; private static MethodInfo s_dynamicLabelMethod; private static MethodInfo s_statSummaryMethod; private static MethodInfo s_pageTitleMethod; private static PropertyInfo s_runtimeSelectedProp; private static MethodInfo s_findLookedAtTameMethod; private static MethodInfo s_canControlMethod; private static MethodInfo s_levelMethod; private static MethodInfo s_stanceMethod; private static MethodInfo s_orderMethod; private static MethodInfo s_readinessSummaryMethod; private static MethodInfo s_invalidateHoverCacheMethod; private static FieldInfo s_cachedHoverSuffixField; private static Texture2D s_sectorNormalTex; private static Texture2D s_sectorSelectedTex; private static Texture2D s_sectorDisabledTex; private static Texture2D s_centerHubTex; private static Texture2D s_pillTex; private static Texture2D s_pillSelectedTex; private static Texture2D[] s_mainWheelIcons; private static GUIStyle s_transparentLabelStyle; private static GUIStyle s_transparentLabelCenterStyle; private static GUIStyle s_nordicPillStyle; private static GUIStyle s_nordicPillSelectedStyle; private static readonly FieldInfo s_currentContainerField = typeof(InventoryGui).GetField("m_currentContainer", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); private static float s_originalAutoCloseDistance = -1f; private static bool s_autoCloseDistanceModified; private static bool s_installed; public static readonly string[] OccluderLayerNames = new string[4] { "Default", "static_solid", "piece", "terrain" }; public static void Install(Harmony harmony, Assembly coreAssembly) { if (s_installed || harmony == null || coreAssembly == null) { return; } try { s_commandWheelType = coreAssembly.GetType("TameMate.CommandWheel", throwOnError: false); s_companionRuntimeType = coreAssembly.GetType("TameMate.CompanionRuntime", throwOnError: false); s_companionStateType = coreAssembly.GetType("TameMate.CompanionState", throwOnError: false); s_tameInteractPatchType = coreAssembly.GetType("TameMate.TameInteractPatch", throwOnError: false); s_tameHoverPatchType = coreAssembly.GetType("TameMate.TameHoverPatch", throwOnError: false); s_biomeReadinessEngineType = coreAssembly.GetType("TameMate.BiomeReadinessEngine", throwOnError: false); if (s_commandWheelType == null) { Log.LogWarning((object)"[WheelSaddlebags] TameMate.CommandWheel not found in core assembly."); return; } s_isOpenProp = s_commandWheelType.GetProperty("IsOpen", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_pageField = s_commandWheelType.GetField("page", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_scopeField = s_commandWheelType.GetField("scope", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_selectedField = s_commandWheelType.GetField("selected", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_selectedGroupField = s_commandWheelType.GetField("selectedGroup", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_lockedTargetField = s_commandWheelType.GetField("lockedTarget", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_centerField = s_commandWheelType.GetField("center", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_suppressHotbarUntilField = s_commandWheelType.GetField("s_suppressHotbarUntil", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_medallionStyleField = s_commandWheelType.GetField("s_medallionStyle", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_medallionSelectedStyleField = s_commandWheelType.GetField("s_medallionSelectedStyle", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_centerStyleField = s_commandWheelType.GetField("s_centerStyle", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_pillStyleField = s_commandWheelType.GetField("s_pillStyle", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_ensureStylesMethod = s_commandWheelType.GetMethod("EnsureStyles", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_currentTargetMethod = s_commandWheelType.GetMethod("CurrentTarget", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_labelsMethod = s_commandWheelType.GetMethod("Labels", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_glyphsMethod = s_commandWheelType.GetMethod("Glyphs", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_selectMethod = s_commandWheelType.GetMethod("Select", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null); s_closeMethod = s_commandWheelType.GetMethod("Close", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_stepSelectionMethod = s_commandWheelType.GetMethod("StepSelection", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null); s_dynamicLabelMethod = s_commandWheelType.GetMethod("DynamicLabel", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(string), typeof(int) }, null); s_statSummaryMethod = s_commandWheelType.GetMethod("StatSummary", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Character) }, null); s_pageTitleMethod = s_commandWheelType.GetMethod("PageTitle", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (s_companionRuntimeType != null) { s_runtimeSelectedProp = s_companionRuntimeType.GetProperty("Selected", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_findLookedAtTameMethod = s_companionRuntimeType.GetMethod("FindLookedAtTame", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } if (s_companionStateType != null) { s_canControlMethod = s_companionStateType.GetMethod("CanControl", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(Player), typeof(Character) }, null); s_levelMethod = s_companionStateType.GetMethod("Level", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Character) }, null); s_stanceMethod = s_companionStateType.GetMethod("Stance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Character) }, null); s_orderMethod = s_companionStateType.GetMethod("Order", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Character) }, null); } if (s_biomeReadinessEngineType != null) { s_readinessSummaryMethod = s_biomeReadinessEngineType.GetMethod("GetReadinessShortSummary", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } if (s_tameHoverPatchType != null) { s_invalidateHoverCacheMethod = s_tameHoverPatchType.GetMethod("InvalidateCache", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_cachedHoverSuffixField = s_tameHoverPatchType.GetField("s_cachedHoverSuffix", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } PatchSafe(harmony, s_commandWheelType, "Open", Type.EmptyTypes, "CommandWheel_Open_Prefix"); PatchSafe(harmony, s_commandWheelType, "Labels", Type.EmptyTypes, null, "CommandWheel_Labels_Postfix"); PatchSafe(harmony, s_commandWheelType, "Glyphs", Type.EmptyTypes, null, "CommandWheel_Glyphs_Postfix"); PatchSafe(harmony, s_commandWheelType, "SelectMain", new Type[1] { typeof(int) }, "CommandWheel_SelectMain_Prefix"); PatchSafe(harmony, s_commandWheelType, "StepSelection", new Type[1] { typeof(int) }, "CommandWheel_StepSelection_Prefix"); PatchSafe(harmony, s_commandWheelType, "Update", Type.EmptyTypes, "CommandWheel_Update_Prefix"); PatchSafe(harmony, s_commandWheelType, "OnGUI", Type.EmptyTypes, "CommandWheel_OnGUI_Prefix"); if (s_companionRuntimeType != null) { PatchSafe(harmony, s_companionRuntimeType, "FindLookedAtTame", Type.EmptyTypes, null, "CompanionRuntime_FindLookedAtTame_Postfix"); } if (s_tameInteractPatchType != null) { PatchSafe(harmony, s_tameInteractPatchType, "Prefix", new Type[5] { typeof(Tameable), typeof(Humanoid), typeof(bool), typeof(bool), typeof(bool).MakeByRefType() }, "TameInteractPatch_Prefix_Guard"); } PatchSafe(harmony, typeof(Tameable), "Interact", new Type[3] { typeof(Humanoid), typeof(bool), typeof(bool) }, "Tameable_Interact_RenameGuard_Prefix", null, 600); if (s_tameHoverPatchType != null) { PatchSafe(harmony, s_tameHoverPatchType, "Postfix", new Type[2] { typeof(Tameable), typeof(string).MakeByRefType() }, null, "TameHoverPatch_Postfix_Update"); } PatchSafe(harmony, typeof(InventoryGui), "UpdateContainer", new Type[1] { typeof(Player) }, "InventoryGui_UpdateContainer_Prefix", "InventoryGui_UpdateContainer_Postfix"); PatchSafe(harmony, typeof(InventoryGui), "CloseContainer", Type.EmptyTypes, null, "InventoryGui_CloseOrHide_Postfix"); PatchSafe(harmony, typeof(InventoryGui), "Hide", Type.EmptyTypes, null, "InventoryGui_CloseOrHide_Postfix"); s_installed = true; Log.LogInfo((object)"[WheelSaddlebags] Integrated 'Alforjas' (U -> 8), exclusive Shift+E Rename, and surface-distance container range."); } catch (Exception ex) { Log.LogError((object)("[WheelSaddlebags] Installation failed: " + ex)); } } private static void PatchSafe(Harmony harmony, Type targetType, string methodName, Type[] paramTypes, string prefix = null, string postfix = null, int priority = 400) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown try { MethodInfo methodInfo = AccessTools.Method(targetType, methodName, paramTypes, (Type[])null); if (methodInfo == null) { Log.LogWarning((object)("[WheelSaddlebags] Target method not found: " + targetType.FullName + "." + methodName)); return; } HarmonyMethod val = null; if (prefix != null) { MethodInfo methodInfo2 = AccessTools.Method(typeof(CommandWheelSaddlebagsIntegration), prefix, (Type[])null, (Type[])null); if (methodInfo2 != null) { HarmonyMethod val2 = new HarmonyMethod(methodInfo2); val2.priority = priority; val = val2; } } HarmonyMethod val3 = null; if (postfix != null) { MethodInfo methodInfo3 = AccessTools.Method(typeof(CommandWheelSaddlebagsIntegration), postfix, (Type[])null, (Type[])null); if (methodInfo3 != null) { HarmonyMethod val4 = new HarmonyMethod(methodInfo3); val4.priority = priority; val3 = val4; } } harmony.Patch((MethodBase)methodInfo, val, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { Log.LogError((object)("[WheelSaddlebags] Failed patching " + targetType.FullName + "." + methodName + ": " + ex.Message)); } } public static float GetSurfaceDistanceToGameObject(Vector3 playerPos, Vector3 eyePos, GameObject companionGo, float fallbackRadius) { //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_0075: 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_0078: Unknown result type (might be due to invalid IL or missing references) if (companionGo == null) { return float.MaxValue; } float num = float.MaxValue; Collider[] componentsInChildren = companionGo.GetComponentsInChildren(false); if (componentsInChildren != null) { foreach (Collider val in componentsInChildren) { if ((Object)(object)val == (Object)null || !val.enabled || val.isTrigger || string.Equals(((Object)((Component)val).gameObject).name, "TameMate_InteractionZone", StringComparison.OrdinalIgnoreCase)) { continue; } try { Vector3 val2 = val.ClosestPoint(playerPos); float num2 = Vector3.Distance(playerPos, val2); if (num2 < num) { num = num2; } Vector3 val3 = val.ClosestPoint(eyePos); float num3 = Vector3.Distance(eyePos, val3); if (num3 < num) { num = num3; } } catch { } } } if (num < float.MaxValue) { return num; } float num4 = Vector3.Distance(playerPos, companionGo.transform.position); float num5 = Mathf.Max(companionGo.transform.localScale.x, companionGo.transform.localScale.z); float num6 = Mathf.Max(fallbackRadius, 1.5f) * Mathf.Max(1f, num5); return Mathf.Max(0f, num4 - num6); } public static float GetSurfaceDistanceToCompanion(Player player, Character companion) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || (Object)(object)companion == (Object)null) { return float.MaxValue; } if (((Character)player).IsAttached()) { IDoodadController doodadController = player.GetDoodadController(); Sadle val = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); if ((Object)(object)val != (Object)null) { Character val2 = val.GetCharacter() ?? ((Component)val).GetComponentInParent(); if ((Object)(object)val2 == (Object)(object)companion) { return 0f; } } } EnsureScaledCompanionHoverZone(companion); Vector3 position = ((Component)player).transform.position; Vector3 eyePoint = ((Character)player).GetEyePoint(); return GetSurfaceDistanceToGameObject(position, eyePoint, ((Component)companion).gameObject, companion.GetRadius()); } public static void CommandWheel_Open_Prefix() { try { if (s_findLookedAtTameMethod == null || s_runtimeSelectedProp == null) { return; } object? obj = s_findLookedAtTameMethod.Invoke(null, null); Character val = (Character)((obj is Character) ? obj : null); if ((Object)(object)val != (Object)null) { s_runtimeSelectedProp.SetValue(null, val, null); return; } object? value = s_runtimeSelectedProp.GetValue(null, null); Character val2 = (Character)((value is Character) ? value : null); Player localPlayer = Player.m_localPlayer; if ((Object)(object)val2 != (Object)null && (Object)(object)localPlayer != (Object)null && (val2.IsDead() || !val2.IsTamed() || GetSurfaceDistanceToCompanion(localPlayer, val2) > 6f)) { s_runtimeSelectedProp.SetValue(null, null, null); } } catch (Exception ex) { Log.LogWarning((object)("[WheelSaddlebags] Open prefix error: " + ex.Message)); } } public static int GetOccluderLayerMask() { return LayerMask.GetMask(OccluderLayerNames); } public static bool ShouldIgnoreCameraToEyeHit(float hitDistance, float camToEye) { return hitDistance < camToEye - 0.05f; } public static bool IsSelfOrPlayerCollider(Collider col, Player player, Character targetCompanion) { if ((Object)(object)col == (Object)null) { return true; } if ((Object)(object)player != (Object)null && (Object)(object)((Component)col).transform.root == (Object)(object)((Component)player).transform.root) { return true; } if ((Object)(object)targetCompanion != (Object)null) { if ((Object)(object)((Component)col).transform.root == (Object)(object)((Component)targetCompanion).transform.root) { return true; } Character componentInParent = ((Component)col).GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null && (Object)(object)componentInParent == (Object)(object)targetCompanion) { return true; } } return false; } public static bool IsEyeToTargetBlockedByObstacle(bool isTrigger, bool isPlayerRoot, bool isTargetCompanionCollider, float obstacleDistance, float targetDistanceFromEye) { if (isTrigger || isPlayerRoot || isTargetCompanionCollider) { return false; } if (obstacleDistance > 0f) { return obstacleDistance < targetDistanceFromEye - 0.05f; } return false; } public static bool IsTameMateArtificialHoverOffset(float hoverOffset, bool hasArtificialZone) { if (!Mathf.Approximately(hoverOffset, 8.5f)) { if (hasArtificialZone) { return Mathf.Approximately(hoverOffset, 8.5f); } return false; } return true; } public static void CompanionRuntime_FindLookedAtTame_Postfix(ref Character __result) { //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: 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_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) try { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } if ((Object)(object)__result != (Object)null && __result.IsTamed()) { GameObject hoverObject = ((Humanoid)localPlayer).GetHoverObject(); bool flag = (Object)(object)hoverObject != (Object)null && string.Equals(((Object)hoverObject).name, "TameMate_InteractionZone", StringComparison.OrdinalIgnoreCase); EnsureScaledCompanionHoverZone(__result); if (!flag) { return; } __result = null; } if (((Character)localPlayer).IsAttached()) { IDoodadController doodadController = localPlayer.GetDoodadController(); Sadle val = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); if ((Object)(object)val != (Object)null) { Character val2 = val.GetCharacter() ?? ((Component)val).GetComponentInParent(); if ((Object)(object)val2 != (Object)null && !val2.IsDead() && val2.IsTamed()) { EnsureScaledCompanionHoverZone(val2); __result = val2; return; } } } if ((Object)(object)GameCamera.instance == (Object)null) { return; } Transform transform = ((Component)GameCamera.instance).transform; Vector3 position = transform.position; Vector3 forward = transform.forward; Vector3 eyePoint = ((Character)localPlayer).GetEyePoint(); float num = Vector3.Distance(position, eyePoint); float num2 = num + 14f; RaycastHit[] array = Physics.RaycastAll(position, forward, num2); if (array == null || array.Length == 0) { return; } Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance)); for (int num3 = 0; num3 < array.Length; num3++) { if (ShouldIgnoreCameraToEyeHit(((RaycastHit)(ref array[num3])).distance, num)) { continue; } Collider collider = ((RaycastHit)(ref array[num3])).collider; if ((Object)(object)collider == (Object)null || (Object)(object)((Component)collider).transform.root == (Object)(object)((Component)localPlayer).transform.root || (collider.isTrigger && string.Equals(((Object)((Component)collider).gameObject).name, "TameMate_InteractionZone", StringComparison.OrdinalIgnoreCase))) { continue; } Character componentInParent = ((Component)collider).GetComponentInParent(); if ((Object)(object)componentInParent == (Object)null) { if ((Object)(object)((Component)collider).GetComponentInParent() != (Object)null || ((Component)collider).GetComponentInParent() != null || (Object)(object)((Component)collider).GetComponentInParent() != (Object)null || !collider.isTrigger) { break; } } else { if (componentInParent.IsPlayer() || componentInParent.IsDead() || !componentInParent.IsTamed()) { continue; } EnsureScaledCompanionHoverZone(componentInParent); float num4 = Vector3.Distance(eyePoint, ((RaycastHit)(ref array[num3])).point); float surfaceDistanceToCompanion = GetSurfaceDistanceToCompanion(localPlayer, componentInParent); if (!(num4 <= 9.5f) || !(surfaceDistanceToCompanion <= 6f)) { continue; } Vector3 val3 = ((RaycastHit)(ref array[num3])).point - eyePoint; float magnitude = ((Vector3)(ref val3)).magnitude; if (magnitude > 0.1f) { int occluderLayerMask = GetOccluderLayerMask(); RaycastHit[] array2 = Physics.RaycastAll(eyePoint, ((Vector3)(ref val3)).normalized, magnitude - 0.05f, occluderLayerMask); if (array2 != null && array2.Length > 0) { for (int num5 = 0; num5 < array2.Length; num5++) { Collider collider2 = ((RaycastHit)(ref array2[num5])).collider; if (!((Object)(object)collider2 == (Object)null) && !collider2.isTrigger && !IsSelfOrPlayerCollider(collider2, localPlayer, componentInParent) && IsEyeToTargetBlockedByObstacle(collider2.isTrigger, (Object)(object)((Component)collider2).transform.root == (Object)(object)((Component)localPlayer).transform.root, isTargetCompanionCollider: false, ((RaycastHit)(ref array2[num5])).distance, magnitude)) { return; } } } } __result = componentInParent; break; } } } catch { } } public static void CleanArtificialHoverZone(GameObject companionGo, ref float hoverOffset) { bool flag = false; Transform val = null; if (companionGo != null) { try { val = companionGo.transform.Find("TameMate_InteractionZone"); flag = val != null; } catch { } } if (IsTameMateArtificialHoverOffset(hoverOffset, flag)) { hoverOffset = 0f; } if (flag && val != null) { try { Object.Destroy((Object)(object)((Component)val).gameObject); } catch { } } } public static void EnsureScaledCompanionHoverZone(Character c) { if (!((Object)(object)c == (Object)null)) { float hoverOffset = c.m_hoverOffset; CleanArtificialHoverZone(((Component)c).gameObject, ref hoverOffset); c.m_hoverOffset = hoverOffset; } } private static int GetPageInt(object wheelInstance) { if (wheelInstance == null || s_pageField == null) { return 0; } object value = s_pageField.GetValue(wheelInstance); if (value == null) { return 0; } return Convert.ToInt32(value); } private static Character GetWheelCurrentTarget(object wheelInstance) { if (wheelInstance == null) { return null; } if (s_lockedTargetField != null) { object? value = s_lockedTargetField.GetValue(wheelInstance); Character val = (Character)((value is Character) ? value : null); if ((Object)(object)val != (Object)null) { return val; } } if (s_currentTargetMethod != null) { object? obj = s_currentTargetMethod.Invoke(wheelInstance, null); return (Character)((obj is Character) ? obj : null); } return null; } public static bool IsValidSaddlebagTarget(Character target, out string reason) { reason = null; if ((Object)(object)target == (Object)null) { reason = (ModLanguage.IsEnglish ? "No companion selected. Aim at your companion and press [U]." : "Ningún compañero seleccionado. Apunta a tu compañero y abre la rueda [U]."); return false; } if (target.IsDead() || (Object)(object)((Component)target).gameObject == (Object)null || !((Component)target).gameObject.activeInHierarchy) { reason = (ModLanguage.IsEnglish ? "The selected companion is no longer available." : "El compañero seleccionado ya no está disponible."); return false; } if (!target.IsTamed()) { reason = (ModLanguage.IsEnglish ? "Target creature is not tamed." : "La criatura seleccionada no está domesticada."); return false; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { if (s_canControlMethod != null) { object obj = s_canControlMethod.Invoke(null, new object[2] { localPlayer, target }); if (obj is bool && !(bool)obj) { reason = (ModLanguage.IsEnglish ? "You do not have permission to open this companion's saddlebags." : "No tienes permiso para abrir las alforjas de este compañero."); return false; } } float surfaceDistanceToCompanion = GetSurfaceDistanceToCompanion(localPlayer, target); if (surfaceDistanceToCompanion > 6f) { reason = (ModLanguage.IsEnglish ? $"Too far from {target.GetHoverName()} ({surfaceDistanceToCompanion:F1}m > {6f:F0}m)." : $"Demasiado lejos de {target.GetHoverName()} ({surfaceDistanceToCompanion:F1}m > {6f:F0}m)."); return false; } } return true; } public static void CommandWheel_Labels_Postfix(object __instance, ref string[] __result) { try { if (GetPageInt(__instance) != 0 || __result == null || __result.Length != 8) { return; } bool isEnglish = ModLanguage.IsEnglish; bool flag = false; Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsAttached()) { IDoodadController doodadController = localPlayer.GetDoodadController(); Sadle val = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); if ((Object)(object)val != (Object)null) { flag = true; } } string text = ((!flag) ? __result[5] : (isEnglish ? "Dismount" : "Desmontar")); __result = new string[9] { __result[0], __result[1], __result[2], __result[3], __result[4], text, __result[6], isEnglish ? "Saddlebags" : "Alforjas", __result[7] }; } catch { } } public static void CommandWheel_Glyphs_Postfix(object __instance, ref string[] __result) { try { if (GetPageInt(__instance) != 0 || __result == null || __result.Length != 8) { return; } bool flag = false; Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsAttached()) { IDoodadController doodadController = localPlayer.GetDoodadController(); Sadle val = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); if ((Object)(object)val != (Object)null) { flag = true; } } __result = new string[9] { "\ud83d\udea9", "\ud83d\udc3e", "\ud83d\udc65", "\ud83d\udee1\ufe0f", "⭐", flag ? "↩\ufe0f" : "\ud83d\udc0e", "\ud83d\udcef", "\ud83c\udf92", "✕" }; } catch { } } public static bool CommandWheel_SelectMain_Prefix(object __instance, int index) { try { switch (index) { case 5: { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsAttached()) { IDoodadController doodadController = localPlayer.GetDoodadController(); Sadle val = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); if ((Object)(object)val != (Object)null) { val.OnUseStop(localPlayer); if (s_closeMethod != null) { s_closeMethod.Invoke(__instance, null); } return false; } } return true; } case 0: case 1: case 2: case 3: case 4: case 6: return true; default: switch (index) { case 7: HandleSelectSaddlebags(__instance); return false; case 8: if (s_closeMethod != null) { s_closeMethod.Invoke(__instance, null); } return false; } break; } } catch (Exception ex) { Log.LogWarning((object)("[WheelSaddlebags] SelectMain error: " + ex.Message)); } return false; } private static void HandleSelectSaddlebags(object wheelInstance) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } Character wheelCurrentTarget = GetWheelCurrentTarget(wheelInstance); if (!IsValidSaddlebagTarget(wheelCurrentTarget, out var reason)) { ((Character)localPlayer).Message((MessageType)2, reason, 0, (Sprite)null, false); return; } if (s_closeMethod != null) { s_closeMethod.Invoke(wheelInstance, null); } if ((Object)(object)InventoryGui.instance != (Object)null) { UpdateCompanionContainerAutoCloseDistance(InventoryGui.instance, localPlayer, wheelCurrentTarget); } if (CompanionSaddlebagsSync.OpenAuthorized(localPlayer, wheelCurrentTarget)) { Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; } } public static bool CommandWheel_StepSelection_Prefix(object __instance, int direction) { try { if (__instance == null || s_labelsMethod == null || s_selectedField == null) { return true; } int num = ((s_labelsMethod.Invoke(__instance, null) is string[] array && array.Length > 0) ? array.Length : 8); int num2 = (int)s_selectedField.GetValue(__instance); if (num2 < 0) { s_selectedField.SetValue(__instance, (direction <= 0) ? (num - 1) : 0); return false; } int num3 = (num2 + direction + num) % num; s_selectedField.SetValue(__instance, num3); return false; } catch { return true; } } public static bool CommandWheel_Update_Prefix(object __instance) { //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) try { if (!(s_isOpenProp != null) || !(bool)s_isOpenProp.GetValue(null, null)) { return true; } if ((Object)(object)Player.m_localPlayer == (Object)null) { if (s_closeMethod != null) { s_closeMethod.Invoke(__instance, null); } return false; } if (Input.GetKeyDown((KeyCode)117) || Input.GetKeyDown((KeyCode)27)) { if (s_closeMethod != null) { s_closeMethod.Invoke(__instance, null); } return false; } Character.SetTakeInputDelay(0.15f); Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; string[] array = ((s_labelsMethod != null) ? (s_labelsMethod.Invoke(__instance, null) as string[]) : null); int num = ((array != null && array.Length > 0) ? array.Length : 8); float num2 = 360f / (float)num; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(Mathf.Round((float)Screen.width * 0.5f), Mathf.Round((float)Screen.height * 0.5f)); if (s_centerField != null) { s_centerField.SetValue(__instance, val); } Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(Input.mousePosition.x, (float)Screen.height - Input.mousePosition.y); Vector2 val3 = val2 - val; if (((Vector2)(ref val3)).magnitude > 45f && s_selectedField != null) { float num3 = Mathf.Atan2(val3.y, val3.x) * 57.29578f + 90f; if (num3 < 0f) { num3 += 360f; } int num4 = Mathf.RoundToInt(num3 / num2) % num; s_selectedField.SetValue(__instance, num4); } if (Input.GetKeyDown((KeyCode)276) || Input.GetKeyDown((KeyCode)273)) { CommandWheel_StepSelection_Prefix(__instance, -1); } if (Input.GetKeyDown((KeyCode)275) || Input.GetKeyDown((KeyCode)274)) { CommandWheel_StepSelection_Prefix(__instance, 1); } for (int i = 0; i < num && i < 9; i++) { if (Input.GetKeyDown((KeyCode)(49 + i))) { SuppressHotbarInput(); if (s_selectedField != null) { s_selectedField.SetValue(__instance, i); } if (s_selectMethod != null) { s_selectMethod.Invoke(__instance, new object[1] { i }); } return false; } } if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271)) { int num5 = ((s_selectedField != null) ? ((int)s_selectedField.GetValue(__instance)) : (-1)); if (num5 >= 0 && num5 < num) { SuppressHotbarInput(); if (s_selectMethod != null) { s_selectMethod.Invoke(__instance, new object[1] { num5 }); } } return false; } return false; } catch (Exception ex) { Log.LogWarning((object)("[WheelSaddlebags] Update prefix error: " + ex.Message)); return true; } } private static void SuppressHotbarInput() { try { if (s_suppressHotbarUntilField != null) { s_suppressHotbarUntilField.SetValue(null, Time.unscaledTime + 0.35f); } for (int i = 1; i <= 8; i++) { ZInput.ResetButtonStatus($"Hotbar{i}"); ZInput.ResetButtonStatus($"Hotbar{i}Alt"); } } catch { } } public static bool CommandWheel_OnGUI_Prefix(object __instance) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0819: Unknown result type (might be due to invalid IL or missing references) //IL_0a53: Unknown result type (might be due to invalid IL or missing references) //IL_0a59: Unknown result type (might be due to invalid IL or missing references) //IL_060f: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0664: Unknown result type (might be due to invalid IL or missing references) //IL_0666: Unknown result type (might be due to invalid IL or missing references) //IL_066d: Unknown result type (might be due to invalid IL or missing references) //IL_0672: Unknown result type (might be due to invalid IL or missing references) //IL_0677: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_088d: Unknown result type (might be due to invalid IL or missing references) //IL_08ad: Unknown result type (might be due to invalid IL or missing references) //IL_0915: Unknown result type (might be due to invalid IL or missing references) //IL_07d9: Unknown result type (might be due to invalid IL or missing references) //IL_07de: Unknown result type (might be due to invalid IL or missing references) //IL_09a8: Unknown result type (might be due to invalid IL or missing references) //IL_09aa: Unknown result type (might be due to invalid IL or missing references) //IL_09b1: Unknown result type (might be due to invalid IL or missing references) //IL_09b6: Unknown result type (might be due to invalid IL or missing references) //IL_09bb: Unknown result type (might be due to invalid IL or missing references) //IL_09c2: Unknown result type (might be due to invalid IL or missing references) //IL_09c7: Unknown result type (might be due to invalid IL or missing references) //IL_09cc: Unknown result type (might be due to invalid IL or missing references) //IL_09f9: Unknown result type (might be due to invalid IL or missing references) //IL_098b: Unknown result type (might be due to invalid IL or missing references) //IL_0809: Unknown result type (might be due to invalid IL or missing references) //IL_07e4: 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_07ff: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 matrix = GUI.matrix; Color color = GUI.color; try { if (!(s_isOpenProp != null) || !(bool)s_isOpenProp.GetValue(null, null)) { return false; } GUI.matrix = Matrix4x4.identity; GUI.color = Color.white; if (s_ensureStylesMethod != null) { s_ensureStylesMethod.Invoke(__instance, null); } EnsureCustomAssets(); string[] array = ((s_labelsMethod != null) ? (s_labelsMethod.Invoke(__instance, null) as string[]) : new string[0]); int num = array.Length; if (num == 0) { return false; } Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(Mathf.Round((float)Screen.width * 0.5f), Mathf.Round((float)Screen.height * 0.5f)); if (s_centerField != null) { s_centerField.SetValue(__instance, val); } int pageInt = GetPageInt(__instance); string[] array2 = ((pageInt != 0 && s_glyphsMethod != null) ? (s_glyphsMethod.Invoke(__instance, null) as string[]) : null); int num2 = ((s_selectedField != null) ? ((int)s_selectedField.GetValue(__instance)) : (-1)); Character wheelCurrentTarget = GetWheelCurrentTarget(__instance); string reason; bool flag = IsValidSaddlebagTarget(wheelCurrentTarget, out reason); bool flag2 = false; Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsAttached()) { IDoodadController doodadController = localPlayer.GetDoodadController(); Sadle val2 = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); if ((Object)(object)val2 != (Object)null) { flag2 = true; } } float num3 = 360f / (float)num; Rect val3 = default(Rect); ((Rect)(ref val3))..ctor(val.x - 76f, val.y - 222f - 4f, 152f, 128f); for (int i = 0; i < num; i++) { bool flag3 = i == num2; bool flag4 = pageInt == 0 && i == 7 && !flag; Texture2D val4 = (flag3 ? s_sectorSelectedTex : (flag4 ? s_sectorDisabledTex : s_sectorNormalTex)); float num4 = (float)i * num3; Matrix4x4 matrix2 = GUI.matrix; GUIUtility.RotateAroundPivot(num4, val); GUI.DrawTexture(val3, (Texture)(object)val4, (ScaleMode)0, true); GUI.matrix = matrix2; } Rect val5 = default(Rect); ((Rect)(ref val5))..ctor(val.x - 64f, val.y - 64f, 128f, 128f); if ((Object)(object)s_centerHubTex != (Object)null) { GUI.DrawTexture(val5, (Texture)(object)s_centerHubTex, (ScaleMode)0, true); } int num5 = ((s_scopeField != null) ? Convert.ToInt32(s_scopeField.GetValue(__instance)) : 0); int num6 = ((s_selectedGroupField != null) ? ((int)s_selectedGroupField.GetValue(__instance)) : 0); string arg = num5 switch { 0 => ModLanguage.IsEnglish ? "This only" : "Sólo este", 1 => ModLanguage.IsEnglish ? "Nearby" : "Cercanos", _ => (ModLanguage.IsEnglish ? "Group " : "Grupo ") + num6, }; string text = (ModLanguage.IsEnglish ? "1-9 / Click · U / Esc: close" : "1-9 / Clic · U / Esc: cerrar"); string text4; if ((Object)(object)wheelCurrentTarget != (Object)null) { ZNetView component = ((Component)wheelCurrentTarget).GetComponent(); ZDO val6 = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); string companionCleanName = CataclysmicHudFormatter.GetCompanionCleanName(wheelCurrentTarget, val6); string text2 = CataclysmicHudFormatter.FormatLineageTags(wheelCurrentTarget, val6); string text3; if (pageInt == 0) { if (num2 == 7 && !flag) { text3 = "" + reason + ""; } else { int num7 = 1; if (s_levelMethod != null) { try { num7 = (int)s_levelMethod.Invoke(null, new object[1] { wheelCurrentTarget }); } catch { } } else if (val6 != null) { num7 = Mathf.Max(1, val6.GetInt(StringExtensionMethods.GetStableHashCode("tm_level"), 1)); } string arg2 = "Defensivo"; if (s_stanceMethod != null) { try { object obj2 = s_stanceMethod.Invoke(null, new object[1] { wheelCurrentTarget }); if (obj2 != null) { arg2 = obj2.ToString(); } } catch { } } else if (val6 != null) { int stance = val6.GetInt(StringExtensionMethods.GetStableHashCode("tm_stance"), 1); arg2 = CataclysmicHudFormatter.FormatStanceName(stance); } string arg3 = "Seguir"; if (s_orderMethod != null) { try { object obj4 = s_orderMethod.Invoke(null, new object[1] { wheelCurrentTarget }); if (obj4 != null) { arg3 = obj4.ToString(); } } catch { } } else if (val6 != null) { int order = val6.GetInt(StringExtensionMethods.GetStableHashCode("tm_order"), 0); arg3 = CataclysmicHudFormatter.FormatOrderName(order); } text3 = $"Nv. {num7} · {arg2} · {arg3}"; } } else if (pageInt == 6 && s_statSummaryMethod != null) { text3 = s_statSummaryMethod.Invoke(null, new object[1] { wheelCurrentTarget }) as string; } else { string arg4 = ((s_pageTitleMethod != null) ? (s_pageTitleMethod.Invoke(__instance, null) as string) : "Comandos"); text3 = $"{arg4} · {arg}"; } text4 = $"{companionCleanName}\n{text2}\n{text3}\n{text}"; } else { string text5 = (ModLanguage.IsEnglish ? "Companions" : "Compañeros"); string text6 = (ModLanguage.IsEnglish ? "(No target)" : "(Sin objetivo)"); string arg5 = ((s_pageTitleMethod != null) ? (s_pageTitleMethod.Invoke(__instance, null) as string) : "Comandos"); string text7 = $"{arg5} · {arg}"; text4 = $"{text5}\n{text6}\n{text7}\n{text}"; } GUI.Label(val5, text4, s_transparentLabelCenterStyle); Vector2 val7 = default(Vector2); Vector2 val8 = default(Vector2); Rect val11 = default(Rect); Rect val12 = default(Rect); Rect val13 = default(Rect); Rect val14 = default(Rect); Rect val15 = default(Rect); Rect val17 = default(Rect); for (int j = 0; j < num; j++) { float num8 = ((float)j * num3 - 90f) * ((float)Math.PI / 180f); ((Vector2)(ref val7))..ctor(Mathf.Cos(num8), Mathf.Sin(num8)); ((Vector2)(ref val8))..ctor(0f - val7.y, val7.x); Vector2 val9 = val + val7 * 164f; bool flag5 = j == num2; bool flag6 = pageInt == 0 && j == 7; bool flag7 = pageInt == 0 && j == 5; bool flag8 = flag6 && !flag; string text8 = ((s_dynamicLabelMethod != null) ? (s_dynamicLabelMethod.Invoke(__instance, new object[2] { array[j], j }) as string) : array[j]); string text9 = null; if (flag6 && !flag) { text9 = ((!((Object)(object)wheelCurrentTarget == (Object)null)) ? ((!((Object)(object)((Component)wheelCurrentTarget).GetComponent() == (Object)null)) ? (ModLanguage.IsEnglish ? "(Far)" : "(Lejos)") : (ModLanguage.IsEnglish ? "(No bags)" : "(Sin alforjas)")) : (ModLanguage.IsEnglish ? "(No target)" : "(Sin objetivo)")); } else if (flag7 && !flag2 && (Object)(object)wheelCurrentTarget != (Object)null && (Object)(object)((Component)wheelCurrentTarget).GetComponentInChildren() == (Object)null) { text9 = (ModLanguage.IsEnglish ? "(No mount)" : "(Sin montura)"); } if (pageInt == 0 && j < 9) { Texture2D val10 = s_mainWheelIcons[(flag7 && flag2) ? 9 : j]; ((Rect)(ref val11))..ctor(val9.x - 30f, val9.y - 40f, 60f, 60f); Color color2 = GUI.color; try { if (flag8) { GUI.color = color2 * new Color(0.76f, 0.76f, 0.76f, 0.8f); } GUI.DrawTexture(val11, (Texture)(object)val10, (ScaleMode)0, true); } finally { GUI.color = color2; } } else if (array2 != null && j < array2.Length) { ((Rect)(ref val12))..ctor(val9.x - 30f, val9.y - 32f, 60f, 48f); ((Rect)(ref val13))..ctor(((Rect)(ref val12)).x + 1f, ((Rect)(ref val12)).y + 1.5f, ((Rect)(ref val12)).width, ((Rect)(ref val12)).height); GUI.Label(val13, "" + array2[j] + "", s_transparentLabelStyle); GUI.Label(val12, "" + array2[j] + "", s_transparentLabelStyle); } string text10 = (flag8 ? "#B0BEC5" : (flag5 ? "#FFFFFF" : "#ECEFF1")); ((Rect)(ref val14))..ctor(val9.x - 52f, val9.y + 21f, 104f, 20f); GUI.Label(val14, "" + text8 + "", s_transparentLabelStyle); if (!string.IsNullOrEmpty(text9)) { ((Rect)(ref val15))..ctor(val9.x - 52f, val9.y + 42f, 104f, 14f); GUI.Label(val15, "" + text9 + "", s_transparentLabelStyle); } Vector2 val16 = val + val7 * 203f + val8 * 42f; ((Rect)(ref val17))..ctor(val16.x - 8f, val16.y - 7f, 16f, 14f); GUI.Box(val17, (j + 1).ToString(), flag5 ? s_nordicPillSelectedStyle : s_nordicPillStyle); } return false; } catch (Exception ex) { Log.LogWarning((object)("[WheelSaddlebags] OnGUI prefix error: " + ex.Message)); return true; } finally { GUI.matrix = matrix; GUI.color = color; } } private static Texture2D CreateRadialSectorTexture(int texW, int texH, float rIn, float rOut, float phiMaxRad, Color fillColor, Color borderColor, float borderWidth, float cornerRadius, bool hasGlow, Color glowColor, float glowWidth) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(texW, texH, (TextureFormat)4, false); ((Object)val).hideFlags = (HideFlags)61; ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; Color[] array = (Color[])(object)new Color[texW * texH]; float num = (float)texW * 0.5f; float num2 = rOut + 4f; for (int i = 0; i < texH; i++) { float num3 = (float)(texH - i) - 0.5f - num2; for (int j = 0; j < texW; j++) { float num4 = (float)j + 0.5f - num; float num5 = Mathf.Sqrt(num4 * num4 + num3 * num3); float num6 = Mathf.Atan2(Mathf.Abs(num4), 0f - num3); float num7 = Mathf.Max(rIn - num5, num5 - rOut); float num8 = num5 * (num6 - phiMaxRad); float num9 = num8; float num10 = num7; float num13; if (num9 > 0f - cornerRadius && num10 > 0f - cornerRadius) { float num11 = Mathf.Max(0f, num9 + cornerRadius); float num12 = Mathf.Max(0f, num10 + cornerRadius); num13 = Mathf.Sqrt(num11 * num11 + num12 * num12) - cornerRadius; } else { num13 = Mathf.Max(num9, num10); } Color clear = Color.clear; if (num13 > 0.5f) { if (hasGlow && glowWidth > 0f && num13 <= glowWidth + 0.5f) { float num14 = Mathf.Clamp01(1f - num13 / glowWidth); float num15 = num14 * num14 * glowColor.a; ((Color)(ref clear))..ctor(glowColor.r, glowColor.g, glowColor.b, num15); } } else { float num16 = Mathf.Clamp01(0.5f - num13); float num17 = Mathf.Clamp01((num13 + borderWidth) / 1f); if (num13 > 0f - borderWidth) { Color val2 = Color.Lerp(fillColor, borderColor, num17); ((Color)(ref clear))..ctor(val2.r, val2.g, val2.b, val2.a * num16); } else { ((Color)(ref clear))..ctor(fillColor.r, fillColor.g, fillColor.b, fillColor.a * num16); } } array[i * texW + j] = clear; } } val.SetPixels(array); val.Apply(); return val; } private static Texture2D CreateCircularMedallionTexture(int size, float radius, Color fillColor, Color borderColor, float borderWidth) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_0072: 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_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(size, size, (TextureFormat)4, false); ((Object)val).hideFlags = (HideFlags)61; ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; Color[] array = (Color[])(object)new Color[size * size]; float num = (float)size * 0.5f; for (int i = 0; i < size; i++) { float num2 = (float)i + 0.5f - num; for (int j = 0; j < size; j++) { float num3 = (float)j + 0.5f - num; float num4 = Mathf.Sqrt(num3 * num3 + num2 * num2); float num5 = num4 - radius; Color clear = Color.clear; if (num5 <= 0.5f) { float num6 = Mathf.Clamp01(0.5f - num5); if (num5 > 0f - borderWidth) { float num7 = Mathf.Clamp01((num5 + borderWidth) / 1f); Color val2 = Color.Lerp(fillColor, borderColor, num7); ((Color)(ref clear))..ctor(val2.r, val2.g, val2.b, val2.a * num6); } else { ((Color)(ref clear))..ctor(fillColor.r, fillColor.g, fillColor.b, fillColor.a * num6); } } array[i * size + j] = clear; } } val.SetPixels(array); val.Apply(); return val; } private static Texture2D CreateRoundedTexture(int width, int height, Color fill, Color border, float borderWidth, float cornerRadius) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(width, height, (TextureFormat)4, false); ((Object)val).hideFlags = (HideFlags)61; ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; Color[] array = (Color[])(object)new Color[width * height]; float num = (float)width * 0.5f; float num2 = (float)height * 0.5f; float num3 = Mathf.Min(cornerRadius, Mathf.Min(num, num2)); for (int i = 0; i < height; i++) { float num4 = (float)i + 0.5f - num2; float num5 = Mathf.Abs(num4); float num6 = num5 - (num2 - num3); for (int j = 0; j < width; j++) { float num7 = (float)j + 0.5f - num; float num8 = Mathf.Abs(num7); float num9 = num8 - (num - num3); float num10 = ((!(num9 > 0f) || !(num6 > 0f)) ? (Mathf.Max(num9, num6) - num3) : (Mathf.Sqrt(num9 * num9 + num6 * num6) - num3)); if (num10 > 0.5f) { ref Color reference = ref array[i * width + j]; reference = Color.clear; continue; } float num11 = Mathf.Clamp01(0.5f - num10); float num12 = num10 + borderWidth; Color val2; if (num12 > 0.5f) { val2 = border; val2.a *= num11; } else if (num12 >= -0.5f) { float num13 = Mathf.Clamp01(0.5f - num12); val2 = Color.Lerp(border, fill, num13); val2.a *= num11; } else { val2 = fill; val2.a *= num11; } array[i * width + j] = val2; } } val.SetPixels(array); val.Apply(); return val; } private static void EnsureCustomAssets() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: 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_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Expected O, but got Unknown //IL_02c9: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Expected O, but got Unknown //IL_02d8: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Expected O, but got Unknown //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Expected O, but got Unknown //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Expected O, but got Unknown //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Expected O, but got Unknown //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_037a: Expected O, but got Unknown //IL_039c: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Expected O, but got Unknown //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_03b5: Expected O, but got Unknown //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Unknown result type (might be due to invalid IL or missing references) //IL_040c: Expected O, but got Unknown //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0438: Expected O, but got Unknown //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Expected O, but got Unknown //IL_047f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)s_sectorNormalTex == (Object)null) { s_sectorNormalTex = CreateRadialSectorTexture(152, 128, 116f, 222f, 0.29670596f, new Color(0.08f, 0.11f, 0.16f, 0.4f), new Color(0.72f, 0.58f, 0.35f, 0.7f), 1.5f, 5f, hasGlow: false, Color.clear, 0f); } if ((Object)(object)s_sectorSelectedTex == (Object)null) { s_sectorSelectedTex = CreateRadialSectorTexture(152, 128, 116f, 222f, 0.29670596f, new Color(0.12f, 0.16f, 0.24f, 0.58f), new Color(1f, 0.85f, 0.38f, 1f), 2.2f, 5f, hasGlow: true, new Color(1f, 0.8f, 0.3f, 0.35f), 3.5f); } if ((Object)(object)s_sectorDisabledTex == (Object)null) { s_sectorDisabledTex = CreateRadialSectorTexture(152, 128, 116f, 222f, 0.29670596f, new Color(0.06f, 0.08f, 0.1f, 0.25f), new Color(0.4f, 0.42f, 0.45f, 0.35f), 1f, 5f, hasGlow: false, Color.clear, 0f); } if ((Object)(object)s_centerHubTex == (Object)null) { s_centerHubTex = CreateCircularMedallionTexture(140, 68f, new Color(0.07f, 0.09f, 0.13f, 0.48f), new Color(0.78f, 0.64f, 0.38f, 0.8f), 1.8f); } if ((Object)(object)s_pillTex == (Object)null) { s_pillTex = CreateRoundedTexture(18, 15, new Color(0.09f, 0.11f, 0.15f, 0.75f), new Color(0.65f, 0.54f, 0.35f, 0.7f), 1f, 4f); } if ((Object)(object)s_pillSelectedTex == (Object)null) { s_pillSelectedTex = CreateRoundedTexture(18, 15, new Color(0.96f, 0.82f, 0.4f, 0.95f), new Color(1f, 0.95f, 0.75f, 1f), 1.2f, 4f); } if (s_mainWheelIcons == null) { s_mainWheelIcons = CreateMainWheelIcons(); } if (s_transparentLabelStyle == null) { GUIStyle val = new GUIStyle(GUI.skin.label); val.alignment = (TextAnchor)4; val.richText = true; val.wordWrap = true; val.fontSize = 11; val.padding = new RectOffset(0, 0, 0, 0); val.margin = new RectOffset(0, 0, 0, 0); s_transparentLabelStyle = val; s_transparentLabelStyle.normal.background = null; } if (s_transparentLabelCenterStyle == null) { GUIStyle val2 = new GUIStyle(GUI.skin.label); val2.alignment = (TextAnchor)4; val2.richText = true; val2.wordWrap = true; val2.fontSize = 11; val2.padding = new RectOffset(8, 8, 8, 8); val2.margin = new RectOffset(0, 0, 0, 0); s_transparentLabelCenterStyle = val2; s_transparentLabelCenterStyle.normal.background = null; } if (s_nordicPillStyle == null) { GUIStyle val3 = new GUIStyle(GUI.skin.box); val3.alignment = (TextAnchor)4; val3.richText = true; val3.fontSize = 9; val3.fontStyle = (FontStyle)1; val3.border = new RectOffset(4, 4, 4, 4); val3.padding = new RectOffset(0, 0, 0, 0); s_nordicPillStyle = val3; s_nordicPillStyle.normal.background = s_pillTex; s_nordicPillStyle.normal.textColor = new Color(0.9f, 0.82f, 0.6f, 0.95f); } if (s_nordicPillSelectedStyle == null) { GUIStyle val4 = new GUIStyle(s_nordicPillStyle); val4.alignment = (TextAnchor)4; val4.richText = true; val4.fontSize = 9; val4.fontStyle = (FontStyle)1; val4.border = new RectOffset(4, 4, 4, 4); val4.padding = new RectOffset(0, 0, 0, 0); s_nordicPillSelectedStyle = val4; s_nordicPillSelectedStyle.normal.background = s_pillSelectedTex; s_nordicPillSelectedStyle.normal.textColor = new Color(0.12f, 0.09f, 0.04f, 1f); } } private static Texture2D[] CreateMainWheelIcons() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: 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_0251: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Unknown result type (might be due to invalid IL or missing references) return (Texture2D[])(object)new Texture2D[10] { CreateWheelIcon(new Color32(byte.MaxValue, (byte)122, (byte)96, byte.MaxValue), new int[12] { 5, 21, 5, 3, 20, 3, 16, 8, 20, 13, 5, 13 }), CreateWheelIcon(new Color32((byte)78, (byte)227, (byte)194, byte.MaxValue), new int[16] { 5, 16, 9, 11, 15, 11, 19, 16, 17, 20, 12, 18, 7, 20, 5, 16 }, new int[4] { 4, 9, 3, 7 }, new int[4] { 9, 6, 9, 3 }, new int[4] { 15, 6, 15, 3 }, new int[4] { 20, 9, 21, 7 }), CreateWheelIcon(new Color32((byte)100, (byte)191, byte.MaxValue, byte.MaxValue), new int[6] { 8, 8, 12, 4, 16, 8 }, new int[6] { 4, 14, 12, 10, 20, 14 }, new int[6] { 3, 20, 12, 16, 21, 20 }), CreateWheelIcon(new Color32((byte)67, (byte)216, (byte)242, byte.MaxValue), new int[18] { 4, 5, 12, 3, 20, 5, 20, 12, 17, 17, 12, 21, 7, 17, 4, 12, 4, 5 }, new int[4] { 12, 8, 12, 15 }, new int[4] { 9, 11, 15, 11 }), CreateWheelIcon(new Color32(byte.MaxValue, (byte)212, (byte)92, byte.MaxValue), new int[22] { 12, 3, 15, 9, 21, 10, 17, 14, 18, 21, 12, 17, 6, 21, 7, 14, 3, 10, 9, 9, 12, 3 }), CreateWheelIcon(new Color32(byte.MaxValue, (byte)168, (byte)92, byte.MaxValue), new int[4] { 12, 3, 12, 8 }, new int[14] { 9, 8, 15, 8, 20, 17, 20, 21, 4, 21, 4, 17, 9, 8 }, new int[4] { 4, 17, 20, 17 }), CreateWheelIcon(new Color32((byte)200, (byte)149, byte.MaxValue, byte.MaxValue), new int[20] { 3, 15, 6, 15, 11, 12, 15, 5, 21, 5, 18, 14, 13, 18, 6, 19, 3, 19, 3, 15 }, new int[6] { 15, 5, 18, 9, 20, 9 }), CreateSaddlebagIconTexture(), CreateWheelIcon(new Color32((byte)231, (byte)239, (byte)246, byte.MaxValue), new int[4] { 5, 5, 19, 19 }, new int[4] { 19, 5, 5, 19 }), CreateWheelIcon(new Color32(byte.MaxValue, (byte)168, (byte)92, byte.MaxValue), new int[8] { 6, 4, 6, 12, 9, 15, 20, 15 }, new int[6] { 15, 10, 20, 15, 15, 20 }) }; } private static Texture2D CreateWheelIcon(Color32 ink, params int[][] paths) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Expected O, but got Unknown //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: 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_017d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) Color32 val = default(Color32); ((Color32)(ref val))..ctor((byte)14, (byte)19, (byte)28, byte.MaxValue); float[] array = new float[9216]; for (int i = 0; i < array.Length; i++) { array[i] = 9f; } Vector2 val2 = default(Vector2); Vector2 val3 = default(Vector2); foreach (int[] array2 in paths) { for (int k = 0; k < array2.Length - 2; k += 2) { ((Vector2)(ref val2))..ctor((float)array2[k], (float)array2[k + 1]); ((Vector2)(ref val3))..ctor((float)array2[k + 2], (float)array2[k + 3]); Vector2 val4 = val3 - val2; float num = 1f / ((Vector2)(ref val4)).sqrMagnitude; int num2 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(val2.x, val3.x) - 3f) * 4f)); int num3 = Mathf.Min(96, Mathf.CeilToInt((Mathf.Max(val2.x, val3.x) + 3f) * 4f)); int num4 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(val2.y, val3.y) - 3f) * 4f)); int num5 = Mathf.Min(96, Mathf.CeilToInt((Mathf.Max(val2.y, val3.y) + 3f) * 4f)); for (int l = num4; l < num5; l++) { for (int m = num2; m < num3; m++) { Vector2 val5 = new Vector2(((float)m + 0.5f) / 4f, ((float)l + 0.5f) / 4f) - val2; float num6 = Mathf.Clamp01(Vector2.Dot(val5, val4) * num); int num7 = (95 - l) * 96 + m; float num8 = array[num7]; Vector2 val6 = val5 - val4 * num6; array[num7] = Mathf.Min(num8, ((Vector2)(ref val6)).sqrMagnitude); } } } } Color32[] array3 = (Color32[])(object)new Color32[array.Length]; for (int n = 0; n < array3.Length; n++) { float num9 = Mathf.Sqrt(array[n]); float num10 = Mathf.Clamp01((2.325f - num9) * 4f); float num11 = Mathf.Clamp01((1.425f - num9) * 4f); Color32 val7 = Color32.Lerp(val, ink, num11); val7.a = (byte)Mathf.RoundToInt(num10 * 255f); array3[n] = val7; } Texture2D val8 = new Texture2D(96, 96, (TextureFormat)4, false); ((Object)val8).hideFlags = (HideFlags)61; ((Texture)val8).filterMode = (FilterMode)1; ((Texture)val8).wrapMode = (TextureWrapMode)1; Texture2D val9 = val8; val9.SetPixels32(array3); val9.Apply(false, true); return val9; } private static Texture2D CreateSaddlebagIconTexture() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_00cc: 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_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0122: 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_0139: 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_014f: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(24, 24, (TextureFormat)4, false); ((Object)val).hideFlags = (HideFlags)61; ((Texture)val).filterMode = (FilterMode)1; Color val2 = default(Color); ((Color)(ref val2))..ctor(0f, 0f, 0f, 0f); Color val3 = default(Color); ((Color)(ref val3))..ctor(0.18f, 0.12f, 0.06f, 0.98f); Color val4 = default(Color); ((Color)(ref val4))..ctor(0.46f, 0.29f, 0.14f, 0.96f); Color val5 = default(Color); ((Color)(ref val5))..ctor(0.62f, 0.4f, 0.2f, 0.98f); Color val6 = default(Color); ((Color)(ref val6))..ctor(0.74f, 0.5f, 0.26f, 0.98f); Color val7 = default(Color); ((Color)(ref val7))..ctor(0.96f, 0.79f, 0.35f, 1f); for (int i = 0; i < 24; i++) { for (int j = 0; j < 24; j++) { val.SetPixel(j, i, val2); } } for (int k = 9; k <= 14; k++) { val.SetPixel(k, 21, val3); val.SetPixel(k, 20, val7); } val.SetPixel(8, 19, val3); val.SetPixel(9, 19, val7); val.SetPixel(15, 19, val3); val.SetPixel(14, 19, val7); val.SetPixel(8, 18, val3); val.SetPixel(15, 18, val3); for (int l = 3; l <= 17; l++) { for (int m = 4; m <= 19; m++) { if (m == 4 || m == 19 || l == 3 || l == 17) { val.SetPixel(m, l, val3); } else if (l >= 12) { val.SetPixel(m, l, (l == 12) ? val3 : val6); } else { val.SetPixel(m, l, (l <= 5) ? val4 : val5); } } } for (int n = 5; n <= 12; n++) { val.SetPixel(2, n, val3); val.SetPixel(3, n, (n == 5 || n == 12) ? val3 : val4); val.SetPixel(21, n, val3); val.SetPixel(20, n, (n == 5 || n == 12) ? val3 : val4); } int[] array = new int[2] { 7, 16 }; foreach (int num2 in array) { for (int num3 = 5; num3 <= 16; num3++) { val.SetPixel(num2, num3, val4); } val.SetPixel(num2, 11, val7); val.SetPixel(num2, 10, val7); } for (int num4 = 11; num4 <= 13; num4++) { for (int num5 = 11; num5 <= 12; num5++) { val.SetPixel(num5, num4, val7); } } val.Apply(); return val; } public static bool TameInteractPatch_Prefix_Guard(Tameable __instance, Humanoid user, bool hold, bool alt, ref bool __result) { if (hold) { return true; } bool flag = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303); if (alt || flag) { __result = true; return false; } return true; } public static bool Tameable_Interact_RenameGuard_Prefix(Tameable __instance, Humanoid user, bool hold, ref bool alt) { if (hold || (Object)(object)__instance == (Object)null || (Object)(object)user == (Object)null) { return true; } if (Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303)) { alt = true; } return true; } public static void TameHoverPatch_Postfix_Update(Tameable __0, ref string __1) { try { if (!string.IsNullOrEmpty(__1)) { if (ModLanguage.IsEnglish) { __1 = __1.Replace("[Shift + E] Saddlebags", "[Shift + E] Rename | [U → 8] Saddlebags").Replace("[Shift + E] Saddlebags", "[Shift + E] Rename | [U → 8] Saddlebags"); } else { __1 = __1.Replace("[Mayús + E] Alforjas", "[Mayús + E] Renombrar | [U → 8] Alforjas").Replace("[Mayús + E] Alforjas", "[Mayús + E] Renombrar | [U → 8] Alforjas"); } } } catch { } } private static void UpdateCompanionContainerAutoCloseDistance(InventoryGui gui, Player player, Character companion) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)gui == (Object)null) && !((Object)(object)player == (Object)null) && !((Object)(object)companion == (Object)null)) { if (!s_autoCloseDistanceModified) { s_originalAutoCloseDistance = gui.m_autoCloseDistance; s_autoCloseDistanceModified = true; } float surfaceDistanceToCompanion = GetSurfaceDistanceToCompanion(player, companion); float num = Vector3.Distance(((Component)companion).transform.position, ((Component)player).transform.position); if (surfaceDistanceToCompanion <= 7.5f) { float num2 = ((s_originalAutoCloseDistance > 0f) ? s_originalAutoCloseDistance : 4f); gui.m_autoCloseDistance = Mathf.Max(num2, num + 1.5f); } else { RestoreOriginalAutoCloseDistance(gui); } } } private static void RestoreOriginalAutoCloseDistance(InventoryGui gui) { if (s_autoCloseDistanceModified && (Object)(object)gui != (Object)null) { if (s_originalAutoCloseDistance > 0f) { gui.m_autoCloseDistance = s_originalAutoCloseDistance; } s_originalAutoCloseDistance = -1f; s_autoCloseDistanceModified = false; } } public static void InventoryGui_UpdateContainer_Prefix(InventoryGui __instance, Player player) { try { if ((Object)(object)__instance == (Object)null || s_currentContainerField == null) { return; } object? value = s_currentContainerField.GetValue(__instance); Container val = (Container)((value is Container) ? value : null); if ((Object)(object)val == (Object)null || (Object)(object)player == (Object)null) { RestoreOriginalAutoCloseDistance(__instance); return; } Character component = ((Component)val).GetComponent(); if ((Object)(object)component != (Object)null && !component.IsPlayer() && component.IsTamed()) { UpdateCompanionContainerAutoCloseDistance(__instance, player, component); } else { RestoreOriginalAutoCloseDistance(__instance); } } catch { } } public static void InventoryGui_UpdateContainer_Postfix(InventoryGui __instance) { try { if (!((Object)(object)__instance == (Object)null) && !(s_currentContainerField == null)) { object? value = s_currentContainerField.GetValue(__instance); Container val = (Container)((value is Container) ? value : null); if ((Object)(object)val == (Object)null) { RestoreOriginalAutoCloseDistance(__instance); } } } catch { } } public static void InventoryGui_CloseOrHide_Postfix(InventoryGui __instance) { try { RestoreOriginalAutoCloseDistance(__instance); } catch { } } } public enum WriteOnceBackupStatus { CreatedNewVerified, AlreadyExistsVerified, BlockedInvalidInput, BlockedExistingCorruptOrMismatch, BlockedIoOrVerificationError } public enum RitualJournalState { None, BackupVerified, ZdoMutating, Committed, QuarantinedInterrupted, RecoveredToLegacy, RecoveringLineage, CommittedInMemory, RolledBackInMemory } public enum InterruptionScenarioType { None, InterruptedBeforeCommit, InterruptedDuringWrite, InterruptedAfterCommitBeforeWorldSave, CleanlyPersistedAfterWorldSave, InterruptedDuringRecovery, WorldPersistenceUnconfirmed } public sealed class RitualTransactionJournal { public string TransactionId { get; set; } public long WorldUid { get; set; } public string CompanionGuid { get; set; } public int PrefabHash { get; set; } public int TargetBaseTier { get; set; } public RitualJournalState State { get; set; } public string LegacyOriginSha256 { get; set; } public string PreStateSha256 { get; set; } public string PostStateSha256 { get; set; } public string TimestampUtc { get; set; } public string IntegritySha256 { get; set; } public string ComputeSha256() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("JRNL_V1|").Append(TransactionId ?? string.Empty).Append('|') .Append(WorldUid.ToString(CultureInfo.InvariantCulture)) .Append('|') .Append(CompanionGuid ?? string.Empty) .Append('|') .Append(PrefabHash.ToString(CultureInfo.InvariantCulture)) .Append('|') .Append(TargetBaseTier.ToString(CultureInfo.InvariantCulture)) .Append('|') .Append(((int)State).ToString(CultureInfo.InvariantCulture)) .Append('|') .Append(LegacyOriginSha256 ?? string.Empty) .Append('|') .Append(PreStateSha256 ?? string.Empty) .Append('|') .Append(PostStateSha256 ?? string.Empty) .Append('|') .Append(TimestampUtc ?? string.Empty); using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())); StringBuilder stringBuilder2 = new StringBuilder(array.Length * 2); for (int i = 0; i < array.Length; i++) { stringBuilder2.Append(array[i].ToString("X2")); } return stringBuilder2.ToString(); } public bool VerifyIntegrity() { if (string.IsNullOrEmpty(IntegritySha256)) { return false; } return string.Equals(IntegritySha256, ComputeSha256(), StringComparison.OrdinalIgnoreCase); } } public sealed class InterruptionDiagnosis { public bool IsInterrupted { get; set; } public bool IsQuarantined { get; set; } public bool AutoDestructiveRestoreExecuted { get; set; } public bool HasVerifiedLegacyOriginBackup { get; set; } public bool CanSafelyRecoverLineage { get; set; } public int ZdoTxState { get; set; } public RitualJournalState JournalState { get; set; } public InterruptionScenarioType ScenarioType { get; set; } public string CompanionGuid { get; set; } public long WorldUid { get; set; } public string SummaryMessage { get; set; } } public static class CompanionPersistentBackup { private static string s_customBackupDirectory; public static bool EnableLiveLineageRecovery => false; public static string GetBackupDirectory() { if (!string.IsNullOrEmpty(s_customBackupDirectory)) { if (!Directory.Exists(s_customBackupDirectory)) { Directory.CreateDirectory(s_customBackupDirectory); } return s_customBackupDirectory; } string path = AppDomain.CurrentDomain.BaseDirectory; try { Type type = Type.GetType("BepInEx.Paths, BepInEx"); if (type != null) { PropertyInfo property = type.GetProperty("ConfigPath"); if (property != null) { path = (string)property.GetValue(null, null); } } } catch { } string path2 = Path.Combine(path, "TameMate"); string text = Path.Combine(path2, "backups"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } return text; } public static void SetCustomBackupDirectory(string dir) { s_customBackupDirectory = dir; if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } public static string GetBackupFilePath(long userId, uint entityId) { return Path.Combine(GetBackupDirectory(), string.Format(CultureInfo.InvariantCulture, "companion_backup_{0}_{1}.json", userId, entityId)); } public static string GetBackupFilePath(ZDOID zdoid) { return GetBackupFilePath(((ZDOID)(ref zdoid)).UserID, ((ZDOID)(ref zdoid)).ID); } public static string GetLegacyOriginBackupPath(long worldUid, string companionGuid) { string arg = (companionGuid ?? string.Empty).Trim().ToLowerInvariant(); return Path.Combine(GetBackupDirectory(), string.Format(CultureInfo.InvariantCulture, "legacy_origin_{0}_{1}.json", worldUid, arg)); } public static string GetJournalFilePath(long worldUid, string companionGuid) { string arg = (companionGuid ?? string.Empty).Trim().ToLowerInvariant(); return Path.Combine(GetBackupDirectory(), string.Format(CultureInfo.InvariantCulture, "ritual_journal_{0}_{1}.json", worldUid, arg)); } public static WriteOnceBackupStatus SaveLegacyOriginBackupWriteOnce(CompanionZdoSnapshot snapshot, string reason, out string outPath, out string statusMessage) { outPath = null; statusMessage = null; if (snapshot == null) { statusMessage = "Snapshot nulo."; return WriteOnceBackupStatus.BlockedInvalidInput; } if (!CataclysmicStateReader.IsValidCompanionGuid(snapshot.CompanionGuid)) { statusMessage = "CompanionGuid inválido o ausente en el snapshot."; return WriteOnceBackupStatus.BlockedInvalidInput; } if (snapshot.WorldUid == 0 || snapshot.PrefabHash == 0) { statusMessage = "WorldUid o PrefabHash ausente (cero) en el snapshot."; return WriteOnceBackupStatus.BlockedInvalidInput; } if (!snapshot.VerifyIntegrity()) { statusMessage = "El snapshot en memoria no superó VerifyIntegrity()."; return WriteOnceBackupStatus.BlockedInvalidInput; } string legacyOriginBackupPath = GetLegacyOriginBackupPath(snapshot.WorldUid, snapshot.CompanionGuid); if (File.Exists(legacyOriginBackupPath)) { string error; CompanionZdoSnapshot companionZdoSnapshot = LoadLegacyOriginBackup(snapshot.WorldUid, snapshot.CompanionGuid, snapshot.PrefabHash, out error); if (companionZdoSnapshot != null && companionZdoSnapshot.VerifyIntegrity()) { outPath = legacyOriginBackupPath; statusMessage = $"Respaldo Legacy original ya existe y es inmutable (SHA256={companionZdoSnapshot.IntegritySha256}). Se preservó intacto sin sobrescribir."; return WriteOnceBackupStatus.AlreadyExistsVerified; } statusMessage = "BLOQUEO DE SEGURIDAD: El archivo legacy_origin existente está corrupto o no coincide con la identidad: " + (error ?? "Error desconocido."); return WriteOnceBackupStatus.BlockedExistingCorruptOrMismatch; } string path = legacyOriginBackupPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { string s = SerializeSnapshot(snapshot, reason ?? "Legacy Origin Write-Once Backup"); byte[] bytes = Encoding.UTF8.GetBytes(s); using (FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(flushToDisk: true); } using (FileStream fileStream2 = new FileStream(legacyOriginBackupPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { fileStream2.Write(bytes, 0, bytes.Length); fileStream2.Flush(flushToDisk: true); } File.Delete(path); string error2; CompanionZdoSnapshot companionZdoSnapshot2 = LoadLegacyOriginBackup(snapshot.WorldUid, snapshot.CompanionGuid, snapshot.PrefabHash, out error2); if (companionZdoSnapshot2 == null || !companionZdoSnapshot2.VerifyIntegrity() || !string.Equals(companionZdoSnapshot2.IntegritySha256, snapshot.IntegritySha256, StringComparison.OrdinalIgnoreCase)) { statusMessage = "Fallo en la verificación post-escritura del respaldo legacy_origin: " + (error2 ?? "Hash discrepante."); return WriteOnceBackupStatus.BlockedIoOrVerificationError; } outPath = legacyOriginBackupPath; statusMessage = $"Respaldo Legacy original Write-Once creado y verificado (SHA256={companionZdoSnapshot2.IntegritySha256})."; return WriteOnceBackupStatus.CreatedNewVerified; } catch (IOException ex) { statusMessage = "Bloqueo de creación exclusiva (IOException): " + ex.Message; return WriteOnceBackupStatus.BlockedIoOrVerificationError; } catch (Exception ex2) { statusMessage = "Excepción al crear respaldo legacy_origin: " + ex2.Message; return WriteOnceBackupStatus.BlockedIoOrVerificationError; } finally { try { if (File.Exists(path)) { File.Delete(path); } } catch { } } } public static CompanionZdoSnapshot LoadLegacyOriginBackup(long expectedWorldUid, string expectedCompanionGuid, int expectedPrefabHash, out string error) { error = null; if (!CataclysmicStateReader.IsValidCompanionGuid(expectedCompanionGuid)) { error = "CompanionGuid inválido."; return null; } if (expectedWorldUid == 0 || expectedPrefabHash == 0) { error = "WorldUid o PrefabHash esperado inválido (cero)."; return null; } string legacyOriginBackupPath = GetLegacyOriginBackupPath(expectedWorldUid, expectedCompanionGuid); if (!File.Exists(legacyOriginBackupPath)) { error = "Archivo legacy_origin no encontrado: " + legacyOriginBackupPath; return null; } try { string json = File.ReadAllText(legacyOriginBackupPath, Encoding.UTF8); CompanionZdoSnapshot companionZdoSnapshot = DeserializeSnapshot(json, out error); if (companionZdoSnapshot == null) { return null; } if (!companionZdoSnapshot.VerifyIntegrity()) { error = "Integridad criptográfica SHA256 fallida en legacy_origin."; return null; } if (companionZdoSnapshot.WorldUid != expectedWorldUid) { error = $"Discrepancia de WorldUid en respaldo: esperado {expectedWorldUid}, encontrado {companionZdoSnapshot.WorldUid}."; return null; } if (!string.Equals(companionZdoSnapshot.CompanionGuid, expectedCompanionGuid, StringComparison.OrdinalIgnoreCase)) { error = $"Discrepancia de CompanionGuid en respaldo: esperado {expectedCompanionGuid}, encontrado {companionZdoSnapshot.CompanionGuid}."; return null; } if (companionZdoSnapshot.PrefabHash != expectedPrefabHash) { error = $"Discrepancia de PrefabHash en respaldo: esperado {expectedPrefabHash}, encontrado {companionZdoSnapshot.PrefabHash}."; return null; } return companionZdoSnapshot; } catch (Exception ex) { error = "Excepción al leer legacy_origin: " + ex.Message; return null; } } public static bool SaveJournal(RitualTransactionJournal journal, out string outPath, out string error) { outPath = null; error = null; if (journal == null || !CataclysmicStateReader.IsValidCompanionGuid(journal.CompanionGuid) || journal.WorldUid == 0) { error = "Journal nulo o con identidad inválida."; return false; } journal.TimestampUtc = DateTime.UtcNow.ToString("o"); journal.IntegritySha256 = journal.ComputeSha256(); string journalFilePath = GetJournalFilePath(journal.WorldUid, journal.CompanionGuid); string text = journalFilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{"); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"TransactionId\": \"{0}\",", EscapeJson(journal.TransactionId ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"WorldUid\": {0},", journal.WorldUid)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"CompanionGuid\": \"{0}\",", EscapeJson(journal.CompanionGuid))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"PrefabHash\": {0},", journal.PrefabHash)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"TargetBaseTier\": {0},", journal.TargetBaseTier)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"State\": {0},", (int)journal.State)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"LegacyOriginSha256\": \"{0}\",", EscapeJson(journal.LegacyOriginSha256 ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"PreStateSha256\": \"{0}\",", EscapeJson(journal.PreStateSha256 ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"PostStateSha256\": \"{0}\",", EscapeJson(journal.PostStateSha256 ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"TimestampUtc\": \"{0}\",", EscapeJson(journal.TimestampUtc))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"IntegritySha256\": \"{0}\"", EscapeJson(journal.IntegritySha256))); stringBuilder.AppendLine("}"); byte[] bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString()); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) { fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(journalFilePath)) { File.Replace(text, journalFilePath, null); } else { File.Move(text, journalFilePath); } RitualTransactionJournal ritualTransactionJournal = LoadJournal(journal.WorldUid, journal.CompanionGuid, out error); if (ritualTransactionJournal == null || !ritualTransactionJournal.VerifyIntegrity() || ritualTransactionJournal.IntegritySha256 != journal.IntegritySha256) { error = "Fallo en la verificación post-escritura del journal transaccional."; return false; } outPath = journalFilePath; return true; } catch (Exception ex) { error = "Excepción al guardar journal: " + ex.Message; return false; } finally { try { if (File.Exists(text)) { File.Delete(text); } } catch { } } } public static RitualTransactionJournal LoadJournal(long worldUid, string companionGuid, out string error) { error = null; if (!CataclysmicStateReader.IsValidCompanionGuid(companionGuid) || worldUid == 0) { error = "Parámetros de búsqueda de journal inválidos."; return null; } string journalFilePath = GetJournalFilePath(worldUid, companionGuid); if (!File.Exists(journalFilePath)) { error = "Journal no encontrado."; return null; } try { string json = File.ReadAllText(journalFilePath, Encoding.UTF8); RitualTransactionJournal ritualTransactionJournal = new RitualTransactionJournal(); ritualTransactionJournal.TransactionId = ExtractString(json, "TransactionId"); ritualTransactionJournal.WorldUid = ExtractLong(json, "WorldUid"); ritualTransactionJournal.CompanionGuid = ExtractString(json, "CompanionGuid"); ritualTransactionJournal.PrefabHash = (int)ExtractLong(json, "PrefabHash"); ritualTransactionJournal.TargetBaseTier = (int)ExtractLong(json, "TargetBaseTier"); ritualTransactionJournal.State = (RitualJournalState)ExtractLong(json, "State"); ritualTransactionJournal.LegacyOriginSha256 = ExtractString(json, "LegacyOriginSha256"); ritualTransactionJournal.PreStateSha256 = ExtractString(json, "PreStateSha256"); ritualTransactionJournal.PostStateSha256 = ExtractString(json, "PostStateSha256"); ritualTransactionJournal.TimestampUtc = ExtractString(json, "TimestampUtc"); ritualTransactionJournal.IntegritySha256 = ExtractString(json, "IntegritySha256"); RitualTransactionJournal ritualTransactionJournal2 = ritualTransactionJournal; if (!ritualTransactionJournal2.VerifyIntegrity()) { error = "El archivo de journal transaccional presenta corrupción SHA256."; return null; } if (ritualTransactionJournal2.WorldUid != worldUid || !string.Equals(ritualTransactionJournal2.CompanionGuid, companionGuid, StringComparison.OrdinalIgnoreCase) || !Enum.IsDefined(typeof(RitualJournalState), ritualTransactionJournal2.State)) { error = "Journal con identidad/estado contradictorio."; return null; } return ritualTransactionJournal2; } catch (Exception ex) { error = "Error al leer journal: " + ex.Message; return null; } } public static InterruptionDiagnosis InspectInterruptedTransaction(IZdoPropertyReader reader, long expectedWorldUid, int expectedPrefabHash) { InterruptionDiagnosis interruptionDiagnosis = new InterruptionDiagnosis(); interruptionDiagnosis.IsInterrupted = false; interruptionDiagnosis.IsQuarantined = false; interruptionDiagnosis.AutoDestructiveRestoreExecuted = false; interruptionDiagnosis.HasVerifiedLegacyOriginBackup = false; interruptionDiagnosis.CanSafelyRecoverLineage = false; interruptionDiagnosis.WorldUid = expectedWorldUid; interruptionDiagnosis.ScenarioType = InterruptionScenarioType.None; InterruptionDiagnosis interruptionDiagnosis2 = interruptionDiagnosis; if (reader == null) { interruptionDiagnosis2.SummaryMessage = "Lector ZDO nulo."; return interruptionDiagnosis2; } string text = reader.GetString(CataclysmicStateReader.CompanionGuidKey, string.Empty); int num = reader.GetInt(CataclysmicStateReader.RitualTxStateKey); interruptionDiagnosis2.CompanionGuid = text; interruptionDiagnosis2.ZdoTxState = num; string error; RitualTransactionJournal ritualTransactionJournal = (CataclysmicStateReader.IsValidCompanionGuid(text) ? LoadJournal(expectedWorldUid, text, out error) : null); interruptionDiagnosis2.JournalState = ritualTransactionJournal?.State ?? RitualJournalState.None; interruptionDiagnosis2.HasVerifiedLegacyOriginBackup = (CataclysmicStateReader.IsValidCompanionGuid(text) ? LoadLegacyOriginBackup(expectedWorldUid, text, expectedPrefabHash, out var _) : null)?.VerifyIntegrity() ?? false; if (ritualTransactionJournal != null && (ritualTransactionJournal.State == RitualJournalState.CommittedInMemory || ritualTransactionJournal.State == RitualJournalState.RolledBackInMemory)) { interruptionDiagnosis2.IsQuarantined = true; interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.WorldPersistenceUnconfirmed; interruptionDiagnosis2.SummaryMessage = "Transacción en memoria; no existe evidencia de guardado confirmado del mundo. No se restaura automáticamente."; return interruptionDiagnosis2; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify(reader); if (num == 3 || (ritualTransactionJournal != null && ritualTransactionJournal.State == RitualJournalState.RecoveringLineage)) { interruptionDiagnosis2.IsInterrupted = true; interruptionDiagnosis2.IsQuarantined = true; interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.InterruptedDuringRecovery; interruptionDiagnosis2.CanSafelyRecoverLineage = interruptionDiagnosis2.HasVerifiedLegacyOriginBackup; interruptionDiagnosis2.SummaryMessage = string.Format("[CUARENTENA SEGURA - INTERRUPCIÓN EN RECUPERACIÓN] Operación de rollback interrumpida para GUID={0} (ZdoTx={1}, Journal={2}). Respaldo legacy_origin verificado={3}.", text, num, interruptionDiagnosis2.JournalState, interruptionDiagnosis2.HasVerifiedLegacyOriginBackup ? "SÍ" : "NO"); return interruptionDiagnosis2; } if (num == 1 || (ritualTransactionJournal != null && (ritualTransactionJournal.State == RitualJournalState.ZdoMutating || ritualTransactionJournal.State == RitualJournalState.QuarantinedInterrupted))) { interruptionDiagnosis2.IsInterrupted = true; interruptionDiagnosis2.IsQuarantined = true; interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.InterruptedDuringWrite; interruptionDiagnosis2.CanSafelyRecoverLineage = interruptionDiagnosis2.HasVerifiedLegacyOriginBackup; interruptionDiagnosis2.SummaryMessage = string.Format("[CUARENTENA SEGURA - INTERRUPCIÓN DURANTE ESCRITURA] Transacción interrumpida a mitad de mutación para GUID={0} (ZdoTx={1}, Journal={2}). Cero restauraciones destructivas automáticas ejecutadas. Respaldo legacy_origin verificado={3}.", text, num, interruptionDiagnosis2.JournalState, interruptionDiagnosis2.HasVerifiedLegacyOriginBackup ? "SÍ" : "NO"); return interruptionDiagnosis2; } if (ritualTransactionJournal != null && ritualTransactionJournal.State == RitualJournalState.BackupVerified && num == 0) { interruptionDiagnosis2.IsInterrupted = true; interruptionDiagnosis2.IsQuarantined = false; interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.InterruptedBeforeCommit; interruptionDiagnosis2.CanSafelyRecoverLineage = false; interruptionDiagnosis2.SummaryMessage = $"[INTERRUPCIÓN PREVIA AL COMMIT] Se verificó respaldo en disco, pero el ZDO no fue mutado (ZdoTx=0). La criatura permanece íntegra en su estado Legado original (GUID={text})."; return interruptionDiagnosis2; } if (ritualTransactionJournal != null && ritualTransactionJournal.State == RitualJournalState.Committed && num == 0 && (cataclysmicClassification == CataclysmicClassification.LegacyAmbiguous || cataclysmicClassification == CataclysmicClassification.LegacyAmbiguousUndead)) { interruptionDiagnosis2.IsInterrupted = true; interruptionDiagnosis2.IsQuarantined = false; interruptionDiagnosis2.AutoDestructiveRestoreExecuted = false; interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.InterruptedAfterCommitBeforeWorldSave; interruptionDiagnosis2.CanSafelyRecoverLineage = false; interruptionDiagnosis2.SummaryMessage = $"[INTERRUPCIÓN POST-COMMIT PRE-GUARDADO DE MUNDO] El journal de disco registra 'Committed', pero el archivo .db del mundo cargó el ZDO en estado Legado previo (ZdoTx=0). No se ejecutan escrituras destructivas automáticas; la criatura se mantiene segura e íntegra en estado Legado (GUID={text})."; return interruptionDiagnosis2; } if (ritualTransactionJournal != null && ritualTransactionJournal.State == RitualJournalState.Committed && num == 2 && cataclysmicClassification == CataclysmicClassification.DecoupledCataclysmic) { interruptionDiagnosis2.IsInterrupted = false; interruptionDiagnosis2.IsQuarantined = false; interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.CleanlyPersistedAfterWorldSave; interruptionDiagnosis2.SummaryMessage = "Transacción armonizada y persistida limpiamente en el guardado del mundo."; return interruptionDiagnosis2; } interruptionDiagnosis2.ScenarioType = InterruptionScenarioType.None; interruptionDiagnosis2.SummaryMessage = "Estado transaccional consistente (sin interrupciones activas)."; return interruptionDiagnosis2; } public static bool TryExecuteLiveLineageRecovery(ZDO liveZdo, out string statusMessage) { statusMessage = "[BLOQUEADO EN 4B-2B.1] La ejecución de recuperación o rollback en vivo sobre compañeros reales está deshabilitada hasta la aprobación de 4B-2B.2 (0 escrituras realizadas)."; return false; } public static bool TryRecoverSyntheticLineageFromOrigin(IDictionary targetInts, IDictionary targetStrings, IDictionary targetByteArrays, long currentWorldUid, string companionGuid, int currentPrefabHash, IEnumerable worldZdos, ZdoInspectionScope scope, out string statusMessage) { if (targetInts == null || targetStrings == null) { statusMessage = "Diccionarios de destino nulos."; return false; } CompanionIdentityResolution companionIdentityResolution = CataclysmicStateReader.ResolveCompanionIdentity(companionGuid, currentWorldUid, currentPrefabHash, worldZdos, scope); if (!companionIdentityResolution.IsUnambiguousAndSafe || !companionIdentityResolution.IsGlobalUniquenessProven) { statusMessage = "Recuperación bloqueada por validación de identidad/alcance: " + companionIdentityResolution.FailureReason; return false; } string error; CompanionZdoSnapshot companionZdoSnapshot = LoadLegacyOriginBackup(currentWorldUid, companionGuid, currentPrefabHash, out error); if (companionZdoSnapshot == null || !companionZdoSnapshot.VerifyIntegrity()) { statusMessage = "Recuperación bloqueada: respaldo legacy_origin inválido o ausente: " + error; return false; } byte[] array = null; if (targetByteArrays != null && targetByteArrays.ContainsKey(CataclysmicStateReader.ItemsByteKey)) { byte[] array2 = targetByteArrays[CataclysmicStateReader.ItemsByteKey]; if (array2 != null) { array = new byte[array2.Length]; Buffer.BlockCopy(array2, 0, array, 0, array2.Length); } } int[] array3 = new int[3] { CataclysmicStateReader.SavedTierKey, CataclysmicStateReader.TierOverrideKey, CataclysmicStateReader.IsCataclysmicKey }; int[] array4 = array3; foreach (int num in array4) { if (companionZdoSnapshot.IntValues.TryGetValue(num, out var value)) { targetInts[num] = value; } else if (companionZdoSnapshot.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('I', num))) { targetInts.Remove(num); } } targetInts[CataclysmicStateReader.RitualTxStateKey] = 0; targetInts[CataclysmicStateReader.HarmonizedFromLegacyKey] = 0; targetInts[CataclysmicStateReader.HarmonizedTargetTierKey] = 0; targetStrings.Remove(CataclysmicStateReader.HarmonizedTimestampKey); if (array != null && targetByteArrays != null) { byte[] array5 = targetByteArrays[CataclysmicStateReader.ItemsByteKey]; if (array5 == null || array5.Length != array.Length) { statusMessage = "Error de invariante: alteración detectada en bytes de alforjas."; return false; } } statusMessage = $"Recuperación sintética de linaje completada desde legacy_origin (GUID={companionGuid}, SHA256={companionZdoSnapshot.IntegritySha256}). Alforjas y Subconjunto C 100% preservados."; return true; } public static bool SaveBackup(ZDO zdo, string reason, out string outPath, out string error) { //IL_0059: 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) outPath = null; error = null; if (zdo == null) { error = "ZDO nulo."; return false; } try { CompanionZdoSnapshot companionZdoSnapshot = CompanionZdoSnapshot.Create(zdo); if (companionZdoSnapshot == null || !companionZdoSnapshot.VerifyIntegrity()) { error = "Fallo al generar snapshot verificado en memoria."; return false; } string backupFilePath = GetBackupFilePath(companionZdoSnapshot.UserID, companionZdoSnapshot.EntityID); if (File.Exists(backupFilePath)) { CompanionZdoSnapshot companionZdoSnapshot2 = LoadBackup(new ZDOID(companionZdoSnapshot.UserID, companionZdoSnapshot.EntityID), out error); if (companionZdoSnapshot2 != null && companionZdoSnapshot2.VerifyIntegrity()) { outPath = backupFilePath; return true; } } string contents = SerializeSnapshot(companionZdoSnapshot, reason); string text = backupFilePath + ".tmp"; File.WriteAllText(text, contents, Encoding.UTF8); if (!File.Exists(backupFilePath)) { File.Move(text, backupFilePath); } else { File.Delete(text); } CompanionZdoSnapshot companionZdoSnapshot3 = LoadBackup(new ZDOID(companionZdoSnapshot.UserID, companionZdoSnapshot.EntityID), out error); if (companionZdoSnapshot3 == null || !companionZdoSnapshot3.VerifyIntegrity()) { error = "Verificación posterior a la escritura fallida."; return false; } outPath = backupFilePath; return true; } catch (Exception ex) { error = "Excepción al guardar respaldo persistente: " + ex.Message; return false; } } public static CompanionZdoSnapshot LoadBackup(ZDOID zdoid, out string error) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) error = null; string backupFilePath = GetBackupFilePath(zdoid); if (!File.Exists(backupFilePath)) { error = "Archivo de respaldo no encontrado: " + backupFilePath; return null; } try { string json = File.ReadAllText(backupFilePath, Encoding.UTF8); CompanionZdoSnapshot companionZdoSnapshot = DeserializeSnapshot(json, out error); if (companionZdoSnapshot == null) { return null; } if (!companionZdoSnapshot.VerifyIntegrity()) { error = "Verificación de integridad fallida: el hash SHA256 no coincide con los datos del respaldo."; return null; } return companionZdoSnapshot; } catch (Exception ex) { error = "Error al leer respaldo de disco: " + ex.Message; return null; } } public static bool RestoreBackup(ZDO zdo, out string statusMessage) { statusMessage = "[BLOQUEADO EN 4B-2B.1] La restauración en vivo sobre ZDOs de compañeros está deshabilitada hasta la aprobación de 4B-2B.2 (0 escrituras)."; return false; } public static List ListBackups() { List list = new List(); string backupDirectory = GetBackupDirectory(); if (!Directory.Exists(backupDirectory)) { return list; } string[] files = Directory.GetFiles(backupDirectory, "*.json"); foreach (string item in files) { list.Add(item); } return list; } public static string SerializeSnapshot(CompanionZdoSnapshot s, string reason) { //IL_04c4: Unknown result type (might be due to invalid IL or missing references) //IL_04d9: Unknown result type (might be due to invalid IL or missing references) //IL_04ee: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{"); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"WorldUid\": {0},", s.WorldUid)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"CompanionGuid\": \"{0}\",", EscapeJson(s.CompanionGuid ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"UserID\": {0},", s.UserID)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"EntityID\": {0},", s.EntityID)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"PrefabHash\": {0},", s.PrefabHash)); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"TimestampUtc\": \"{0}\",", EscapeJson(s.TimestampUtc ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"Reason\": \"{0}\",", EscapeJson(reason ?? string.Empty))); stringBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, " \"IntegritySha256\": \"{0}\",", EscapeJson(s.IntegritySha256 ?? string.Empty))); stringBuilder.AppendLine(" \"IntValues\": {"); int num = 0; foreach (KeyValuePair item in new SortedDictionary(s.IntValues)) { stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\": {1}{2}\n", item.Key, item.Value, (++num < s.IntValues.Count) ? "," : "")); } stringBuilder.AppendLine(" },"); stringBuilder.AppendLine(" \"StringValues\": {"); num = 0; foreach (KeyValuePair item2 in new SortedDictionary(s.StringValues)) { stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\": \"{1}\"{2}\n", item2.Key, EscapeJson(item2.Value ?? string.Empty), (++num < s.StringValues.Count) ? "," : "")); } stringBuilder.AppendLine(" },"); stringBuilder.AppendLine(" \"FloatValues\": {"); num = 0; foreach (KeyValuePair item3 in new SortedDictionary(s.FloatValues)) { stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\": {1}{2}\n", item3.Key, item3.Value.ToString("R", CultureInfo.InvariantCulture), (++num < s.FloatValues.Count) ? "," : "")); } stringBuilder.AppendLine(" },"); stringBuilder.AppendLine(" \"LongValues\": {"); num = 0; foreach (KeyValuePair item4 in new SortedDictionary(s.LongValues)) { stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\": {1}{2}\n", item4.Key, item4.Value, (++num < s.LongValues.Count) ? "," : "")); } stringBuilder.AppendLine(" },"); stringBuilder.AppendLine(" \"ByteArrayValues\": {"); num = 0; foreach (KeyValuePair item5 in new SortedDictionary(s.ByteArrayValues)) { string arg = ((item5.Value != null) ? Convert.ToBase64String(item5.Value) : string.Empty); stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\": \"{1}\"{2}\n", item5.Key, arg, (++num < s.ByteArrayValues.Count) ? "," : "")); } stringBuilder.AppendLine(" },"); stringBuilder.AppendLine(" \"Vec3Values\": {"); num = 0; foreach (KeyValuePair item6 in new SortedDictionary(s.Vec3Values)) { stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\": \"{1:R},{2:R},{3:R}\"{4}\n", item6.Key, item6.Value.x, item6.Value.y, item6.Value.z, (++num < s.Vec3Values.Count) ? "," : "")); } stringBuilder.AppendLine(" },"); stringBuilder.AppendLine(" \"AbsentKeys\": ["); num = 0; int num2 = ((s.AbsentKeys != null) ? s.AbsentKeys.Count : 0); if (s.AbsentKeys != null) { foreach (string absentKey in s.AbsentKeys) { stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\"{1}\n", EscapeJson(absentKey), (++num < num2) ? "," : "")); } } stringBuilder.AppendLine(" ]"); stringBuilder.AppendLine("}"); return stringBuilder.ToString(); } public static CompanionZdoSnapshot DeserializeSnapshot(string json, out string error) { error = null; if (string.IsNullOrEmpty(json)) { error = "JSON vacío."; return null; } CompanionZdoSnapshot companionZdoSnapshot = new CompanionZdoSnapshot(); try { companionZdoSnapshot.WorldUid = ExtractLong(json, "WorldUid"); companionZdoSnapshot.CompanionGuid = ExtractString(json, "CompanionGuid"); companionZdoSnapshot.UserID = ExtractLong(json, "UserID"); companionZdoSnapshot.EntityID = (uint)ExtractLong(json, "EntityID"); companionZdoSnapshot.PrefabHash = (int)ExtractLong(json, "PrefabHash"); companionZdoSnapshot.TimestampUtc = ExtractString(json, "TimestampUtc"); companionZdoSnapshot.IntegritySha256 = ExtractString(json, "IntegritySha256"); ExtractIntDictionary(json, "IntValues", companionZdoSnapshot.IntValues); ExtractStringDictionary(json, "StringValues", companionZdoSnapshot.StringValues); ExtractFloatDictionary(json, "FloatValues", companionZdoSnapshot.FloatValues); ExtractLongDictionary(json, "LongValues", companionZdoSnapshot.LongValues); ExtractByteArrayDictionary(json, "ByteArrayValues", companionZdoSnapshot.ByteArrayValues); ExtractVec3Dictionary(json, "Vec3Values", companionZdoSnapshot.Vec3Values); ExtractStringSet(json, "AbsentKeys", companionZdoSnapshot.AbsentKeys); return companionZdoSnapshot; } catch (Exception ex) { error = "Fallo al deserializar snapshot: " + ex.Message; return null; } } private static string EscapeJson(string s) { if (string.IsNullOrEmpty(s)) { return ""; } return s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") .Replace("\r", "\\r"); } private static string UnescapeJson(string s) { if (string.IsNullOrEmpty(s)) { return ""; } return s.Replace("\\\"", "\"").Replace("\\\\", "\\").Replace("\\n", "\n") .Replace("\\r", "\r"); } private static long ExtractLong(string json, string key) { string text = "\"" + key + "\":"; int num = json.IndexOf(text, StringComparison.Ordinal); if (num < 0) { return 0L; } for (num += text.Length; num < json.Length && char.IsWhiteSpace(json[num]); num++) { } int i; for (i = num; i < json.Length && (char.IsDigit(json[i]) || json[i] == '-'); i++) { } long.TryParse(json.Substring(num, i - num), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result); return result; } private static string ExtractString(string json, string key) { string text = "\"" + key + "\":"; int num = json.IndexOf(text, StringComparison.Ordinal); if (num < 0) { return ""; } for (num += text.Length; num < json.Length && (json[num] == ' ' || json[num] == '\t'); num++) { } if (num >= json.Length || json[num] != '"') { return ""; } num++; int i; for (i = num; i < json.Length && (json[i] != '"' || json[i - 1] == '\\'); i++) { } return UnescapeJson(json.Substring(num, i - num)); } private static void ExtractIntDictionary(string json, string blockName, Dictionary dict) { string text = ExtractObjectBlock(json, blockName); if (string.IsNullOrEmpty(text)) { return; } string[] array = text.Split(new char[3] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { int num = text2.IndexOf(':'); if (num > 0) { string s = text2.Substring(0, num).Replace("\"", "").Trim(); string s2 = text2.Substring(num + 1).Trim(); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && int.TryParse(s2, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2)) { dict[result] = result2; } } } } private static void ExtractStringDictionary(string json, string blockName, Dictionary dict) { string text = ExtractObjectBlock(json, blockName); if (string.IsNullOrEmpty(text)) { return; } string[] array = text.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { int num = text2.IndexOf(':'); if (num > 0) { string s = text2.Substring(0, num).Replace("\"", "").Trim(); string text3 = text2.Substring(num + 1).Trim(); if (text3.EndsWith(",", StringComparison.Ordinal)) { text3 = text3.Substring(0, text3.Length - 1).Trim(); } if (text3.StartsWith("\"", StringComparison.Ordinal) && text3.EndsWith("\"", StringComparison.Ordinal) && text3.Length >= 2) { text3 = text3.Substring(1, text3.Length - 2); } if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { dict[result] = UnescapeJson(text3); } } } } private static void ExtractFloatDictionary(string json, string blockName, Dictionary dict) { string text = ExtractObjectBlock(json, blockName); if (string.IsNullOrEmpty(text)) { return; } string[] array = text.Split(new char[3] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { int num = text2.IndexOf(':'); if (num > 0) { string s = text2.Substring(0, num).Replace("\"", "").Trim(); string s2 = text2.Substring(num + 1).Trim(); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && float.TryParse(s2, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { dict[result] = result2; } } } } private static void ExtractLongDictionary(string json, string blockName, Dictionary dict) { string text = ExtractObjectBlock(json, blockName); if (string.IsNullOrEmpty(text)) { return; } string[] array = text.Split(new char[3] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { int num = text2.IndexOf(':'); if (num > 0) { string s = text2.Substring(0, num).Replace("\"", "").Trim(); string s2 = text2.Substring(num + 1).Trim(); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && long.TryParse(s2, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2)) { dict[result] = result2; } } } } private static void ExtractByteArrayDictionary(string json, string blockName, Dictionary dict) { string text = ExtractObjectBlock(json, blockName); if (string.IsNullOrEmpty(text)) { return; } string[] array = text.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { int num = text2.IndexOf(':'); if (num > 0) { string s = text2.Substring(0, num).Replace("\"", "").Trim(); string text3 = text2.Substring(num + 1).Trim(); if (text3.EndsWith(",", StringComparison.Ordinal)) { text3 = text3.Substring(0, text3.Length - 1).Trim(); } if (text3.StartsWith("\"", StringComparison.Ordinal) && text3.EndsWith("\"", StringComparison.Ordinal) && text3.Length >= 2) { text3 = text3.Substring(1, text3.Length - 2); } if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { dict[result] = (string.IsNullOrEmpty(text3) ? new byte[0] : Convert.FromBase64String(text3)); } } } } private static void ExtractVec3Dictionary(string json, string blockName, Dictionary dict) { //IL_015c: Unknown result type (might be due to invalid IL or missing references) string text = ExtractObjectBlock(json, blockName); if (string.IsNullOrEmpty(text)) { return; } string[] array = text.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { int num = text2.IndexOf(':'); if (num > 0) { string s = text2.Substring(0, num).Replace("\"", "").Trim(); string text3 = text2.Substring(num + 1).Trim(); if (text3.EndsWith(",", StringComparison.Ordinal)) { text3 = text3.Substring(0, text3.Length - 1).Trim(); } if (text3.StartsWith("\"", StringComparison.Ordinal) && text3.EndsWith("\"", StringComparison.Ordinal) && text3.Length >= 2) { text3 = text3.Substring(1, text3.Length - 2); } string[] array3 = text3.Split(new char[1] { ',' }); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && array3.Length == 3) { float.TryParse(array3[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2); float.TryParse(array3[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result3); float.TryParse(array3[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var result4); dict[result] = new Vector3(result2, result3, result4); } } } } private static void ExtractStringSet(string json, string arrayName, SortedSet set) { string value = "\"" + arrayName + "\":"; int num = json.IndexOf(value, StringComparison.Ordinal); if (num < 0) { return; } int num2 = json.IndexOf('[', num); if (num2 < 0) { return; } int num3 = json.IndexOf(']', num2); if (num3 < 0) { return; } string text = json.Substring(num2 + 1, num3 - num2 - 1); string[] array = text.Split(new char[3] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { string text3 = text2.Trim(); if (text3.StartsWith("\"", StringComparison.Ordinal) && text3.EndsWith("\"", StringComparison.Ordinal) && text3.Length >= 2) { text3 = UnescapeJson(text3.Substring(1, text3.Length - 2)); } if (!string.IsNullOrEmpty(text3)) { set.Add(text3); } } } private static string ExtractObjectBlock(string json, string blockName) { string value = "\"" + blockName + "\":"; int num = json.IndexOf(value, StringComparison.Ordinal); if (num < 0) { return ""; } num = json.IndexOf('{', num); if (num < 0) { return ""; } int num2 = num + 1; int num3 = 1; for (int i = num2; i < json.Length; i++) { if (json[i] == '{') { num3++; } else if (json[i] == '}') { num3--; if (num3 == 0) { return json.Substring(num2, i - num2); } } } return ""; } } public static class CompanionSaddlebagsSync { private sealed class DefinitiveDeathScope { internal DefinitiveDeathScope Previous; internal Character Source; internal DeliveryPermit Permit; internal BagOperation Operation; internal bool HelperInvoked; internal bool InHelper; internal bool HelperCompleted; internal bool NullResult; internal bool WasTamed; internal bool DropInvoked; internal bool DropCallSite; internal bool Invalid; } private sealed class DeathDropReceipt { internal byte[] ExpectedBytes; internal Dictionary Expected; internal int Prefab; internal ItemDrop Output; internal ZDOID Id; internal ushort OwnerRevision; internal bool Attempted; internal bool Identified; } private enum DeliveryPermitState { Registered, Bound, DropReady, DropBound, Consumed, Ambiguous } private sealed class DeliverySession { internal ZNet Network; internal ZDOMan Registry; internal long World; internal long Peer; internal readonly string Epoch = Guid.NewGuid().ToString("N"); } private sealed class DeliveryPermit { internal readonly DeliverySession Session; internal readonly Character Source; internal readonly int Instance; internal readonly int Prefab; internal readonly int Width; internal readonly int Height; internal readonly ZDOID SourceId; internal readonly long Owner; internal readonly ushort Revision; internal readonly string Nonce; internal readonly string Digest; internal readonly Vector3 DropPosition; private byte[] inventory; internal readonly Dictionary Integers; internal readonly Dictionary Strings; internal DeliveryPermitState State; internal DeliveryFrame Frame; internal DefinitiveDeathScope DeathScope; internal readonly List Drops = new List(); internal DeliveryPermit(DeliverySession session, Character source, ZDOID id, int prefab, long owner, ushort revision, int width, int height, byte[] bytes, Dictionary integers, Dictionary strings, Vector3 dropPosition) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) Session = session; Source = source; Instance = ((Object)source).GetInstanceID(); SourceId = id; Prefab = prefab; Owner = owner; Revision = revision; Width = width; Height = height; Nonce = Guid.NewGuid().ToString("N"); inventory = (byte[])bytes.Clone(); Digest = DeliveryHash(inventory); Integers = integers; Strings = strings; DropPosition = dropPosition; } internal byte[] InventoryBytes() { if (inventory == null || DeliveryHash(inventory) != Digest) { throw new InvalidOperationException("Delivery payload unavailable or altered."); } return (byte[])inventory.Clone(); } internal void ReleaseVerifiedPayload() { inventory = null; } } private sealed class DeliveryFrame { internal DeliveryFrame Previous; internal Character Source; internal Character Destination; internal DeliveryPermit Permit; internal BagOperation Operation; internal ZDOID DestinationId; internal int DestinationPrefab; internal int Width; internal int Height; internal ushort DestinationRevision; internal byte[] Before; internal Dictionary Expected; internal bool CallSite; internal bool Seen; internal bool Applied; internal bool Returned; internal bool ReturnedNull; } public class DyingTameInventorySnapshot { public int InstanceId; public ZDOID Zdoid; public ZDO ZdoRef; public Vector3 DropPosition; public byte[] SerializedBytes; public List CachedItems = new List(); public bool IsOwner; public string CreatureName; public DateTime CreatedAt = DateTime.UtcNow; public long WorldUid; public long ServerSession; public long SourceOwner; public ushort SourceRevision; public int SourcePrefab; public string DeathNonce; public string InventoryDigest; public bool InventoryVerified; } private enum BagOperationResult { Pending, Completed, Ambiguous } private sealed class BagOperation { internal string Id = Guid.NewGuid().ToString("N"); internal BagOperationResult Result; internal Character Source; internal Character Target; internal ZDOID SourceId; internal ZDOID TargetId; internal DyingTameInventorySnapshot Snapshot; internal Inventory RetainedSource; internal Inventory RetainedDestination; internal byte[] SourceBytes; internal byte[] DestinationBytes; internal readonly List Delivered = new List(); internal bool MayHaveApplied; } private sealed class BagAuthority { internal ZNet Network; internal long World; internal long Peer; internal ZNetView SourceView; internal ZNetView TargetView; internal ZDO Source; internal ZDO Target; internal ushort SourceRevision; internal ushort TargetRevision; internal int SourcePrefab; internal int TargetPrefab; internal void Check() { //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) if (World == 0 || SourcePrefab == 0 || (Target != null && TargetPrefab == 0) || (Object)(object)ZNet.instance != (Object)(object)Network || (Object)(object)Network == (Object)null || !Network.IsServer() || Network.GetWorldUID() != World || ZDOMan.instance == null || ZDOMan.GetSessionID() != Peer || (Object)(object)SourceView == (Object)null || !SourceView.IsValid() || !SourceView.IsOwner() || SourceView.GetZDO() != Source || Source.GetOwner() != Peer || Source.OwnerRevision != SourceRevision || Source.GetPrefab() != SourcePrefab || ZDOMan.instance.GetZDO(Source.m_uid) != Source || (Target != null && ((Object)(object)TargetView == (Object)null || !TargetView.IsValid() || !TargetView.IsOwner() || TargetView.GetZDO() != Target || Target.GetOwner() != Peer || Target.OwnerRevision != TargetRevision || Target.GetPrefab() != TargetPrefab || ZDOMan.instance.GetZDO(Target.m_uid) != Target))) { throw new InvalidOperationException("Current server ownership/revision is not verifiable; delivery retained."); } } } private const BindingFlags MemberFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; [ThreadStatic] private static DefinitiveDeathScope s_definitiveDeath; private static Func s_frozenDeathHelper; private static MethodInfo s_definitiveHelperMethod; private static DeliverySession s_deliverySession; private static readonly FieldInfo DeliveryDestroyQueue = typeof(ZDOMan).GetField("m_destroySendList", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly Dictionary s_deliveryPermits = new Dictionary(StringComparer.Ordinal); [ThreadStatic] private static DeliveryFrame s_deliveryFrame; private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.Saddlebags"); private static readonly FieldInfo InvWidthField = typeof(Inventory).GetField("m_width", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo InvHeightField = typeof(Inventory).GetField("m_height", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo InvNameField = typeof(Inventory).GetField("m_name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly MethodInfo ContainerLoadMethod = typeof(Container).GetMethod("Load", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); private static readonly MethodInfo ContainerSaveMethod = typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); private static readonly FieldInfo ContainerInUseField = typeof(Container).GetField("m_inUse", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo ContainerLastRevisionField = typeof(Container).GetField("m_lastRevision", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo ContainerLoadingField = typeof(Container).GetField("m_loading", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); public static readonly int BackupSaddlebagsKey = StringExtensionMethods.GetStableHashCode("tm_saddlebags"); private static readonly HashSet s_loadedContainers = new HashSet(); private static readonly Dictionary s_dyingSnapshots = new Dictionary(); private static readonly Dictionary s_bagOperations = new Dictionary(); public static readonly int EquippedRightKey = StringExtensionMethods.GetStableHashCode("tm_eq_right"); public static readonly int EquippedLeftKey = StringExtensionMethods.GetStableHashCode("tm_eq_left"); public static readonly int EquippedHelmetKey = StringExtensionMethods.GetStableHashCode("tm_eq_helm"); public static readonly int EquippedChestKey = StringExtensionMethods.GetStableHashCode("tm_eq_chest"); public static readonly int EquippedLegsKey = StringExtensionMethods.GetStableHashCode("tm_eq_legs"); public static readonly int EquippedShoulderKey = StringExtensionMethods.GetStableHashCode("tm_eq_shoulder"); public static readonly int LevelKey = StringExtensionMethods.GetStableHashCode("tm_level"); public static readonly int XpKey = StringExtensionMethods.GetStableHashCode("tm_xp"); public static readonly int PointsKey = StringExtensionMethods.GetStableHashCode("tm_points"); public static readonly int HealthKey = StringExtensionMethods.GetStableHashCode("tm_stat_health"); public static readonly int StaminaKey = StringExtensionMethods.GetStableHashCode("tm_stat_stamina"); public static readonly int DamageKey = StringExtensionMethods.GetStableHashCode("tm_stat_damage"); public static readonly int DefenseKey = StringExtensionMethods.GetStableHashCode("tm_stat_defense"); public static readonly int SpeedKey = StringExtensionMethods.GetStableHashCode("tm_stat_speed"); public static readonly int FoodKey = StringExtensionMethods.GetStableHashCode("tm_stat_food"); public static readonly int SavedTierKey = StringExtensionMethods.GetStableHashCode("TM_070_BaseTier"); private static MethodInfo s_whistleEmitMethod; private static object s_whistleRegroupVal; private static MethodInfo s_refreshVisualMethod; private static bool s_installed; private static bool s_allowWheelOrCommandOpen; private static bool FiniteDropPosition(Vector3 p) { if (!float.IsNaN(p.x) && !float.IsInfinity(p.x) && !float.IsNaN(p.y) && !float.IsInfinity(p.y) && !float.IsNaN(p.z)) { return !float.IsInfinity(p.z); } return false; } internal static void InstallDefinitiveDeathAdapter(Harmony harmony, Assembly core, MethodInfo helper) { //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Expected O, but got Unknown //IL_0130: Expected O, but got Unknown //IL_0130: Expected O, but got Unknown Type type = core.GetType("TameMate.ProgressionPatches"); MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "DeathPostfix", new Type[1] { typeof(Character) }, (Type[])null)); if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(void) || helper == null || helper.DeclaringType == null || helper.DeclaringType.Assembly != core || !helper.IsStatic || helper.ReturnType != typeof(Character)) { throw new NotSupportedException("Frozen death adapter signature unavailable; no definitive drops authorized."); } s_frozenDeathHelper = (Func)Delegate.CreateDelegate(typeof(Func), helper); s_definitiveHelperMethod = helper; harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(CompanionSaddlebagsSync), "BeginDefinitiveDeathScope", (Type[])null, (Type[])null)), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(CompanionSaddlebagsSync), "DefinitiveDeathPostfixTranspiler", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(CompanionSaddlebagsSync), "EndDefinitiveDeathScope", (Type[])null, (Type[])null)), (HarmonyMethod)null); } private static IEnumerable DefinitiveDeathPostfixTranspiler(IEnumerable instructions) { List list = new List(instructions); MethodInfo methodInfo = AccessTools.Method(typeof(CompanionSaddlebagsSync), "InvokeDefinitiveDeathHelper", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "InvokeDefinitiveDeathDrop", (Type[])null, (Type[])null); int num = 0; int num2 = 0; int num3 = -1; int num4 = -1; for (int i = 0; i < list.Count; i++) { CodeInstruction val = list[i]; MethodInfo methodInfo3 = val.operand as MethodInfo; if (val.opcode != OpCodes.Call || methodInfo3 == null || methodInfo3.DeclaringType == null) { continue; } ParameterInfo[] parameters = methodInfo3.GetParameters(); if (methodInfo3.DeclaringType.FullName == "TameMate.UndeadSystem" && methodInfo3.Name == "TryReanimateDefeated") { if (methodInfo3 != s_definitiveHelperMethod || parameters.Length != 4 || methodInfo == null) { throw new NotSupportedException("Unknown frozen death helper call site."); } val.operand = methodInfo; num++; num3 = i; } if (methodInfo3.DeclaringType.FullName == "TameMate.CompanionSaddlebags" && methodInfo3.Name == "DropOnDeath") { if (methodInfo3.DeclaringType.Assembly != s_definitiveHelperMethod.DeclaringType.Assembly || !methodInfo3.IsStatic || methodInfo3.ReturnType != typeof(void) || parameters.Length != 1 || parameters[0].ParameterType != typeof(Character) || methodInfo2 == null) { throw new NotSupportedException("Unknown frozen definitive drop call site."); } val.operand = methodInfo2; num2++; num4 = i; } } if (num != 1 || num2 != 1 || num3 >= num4) { throw new NotSupportedException("Expected one ordered helper/drop pair; definitive adapter not installed."); } return list; } private static void BeginDefinitiveDeathScope(Character __0, out DefinitiveDeathScope __state) { __state = new DefinitiveDeathScope { Previous = s_definitiveDeath, Source = __0 }; s_definitiveDeath = __state; } private static Character InvokeDefinitiveDeathHelper(Character source, bool wasTamed, long owner, int group) { DefinitiveDeathScope definitiveDeathScope = s_definitiveDeath; bool flag = definitiveDeathScope != null && object.ReferenceEquals(definitiveDeathScope.Source, source) && !definitiveDeathScope.Invalid && !definitiveDeathScope.HelperInvoked && !definitiveDeathScope.DropInvoked; if (!flag || s_frozenDeathHelper == null) { if (definitiveDeathScope != null) { definitiveDeathScope.Invalid = true; } throw new InvalidOperationException("Foreign or repeated frozen helper call; no additional RNG invocation."); } definitiveDeathScope.HelperInvoked = true; definitiveDeathScope.InHelper = true; definitiveDeathScope.WasTamed = wasTamed; try { Character val = s_frozenDeathHelper(source, wasTamed, owner, group); if (flag) { definitiveDeathScope.HelperCompleted = true; definitiveDeathScope.NullResult = object.ReferenceEquals(val, null); } return val; } catch { if (definitiveDeathScope != null) { definitiveDeathScope.Invalid = true; } throw; } finally { if (definitiveDeathScope != null) { definitiveDeathScope.InHelper = false; } } } private static DefinitiveDeathScope RequireDefinitiveHelperContext(DeliveryFrame frame) { DefinitiveDeathScope definitiveDeathScope = s_definitiveDeath; if (definitiveDeathScope == null || definitiveDeathScope.Invalid || !definitiveDeathScope.WasTamed || !definitiveDeathScope.HelperInvoked || !definitiveDeathScope.InHelper || definitiveDeathScope.HelperCompleted || definitiveDeathScope.DropInvoked || !object.ReferenceEquals(definitiveDeathScope.Source, frame.Source) || frame.Permit.State != DeliveryPermitState.Registered || frame.Permit.DeathScope != null) { throw new InvalidOperationException("Null result is not from the authenticated frozen death postfix."); } return definitiveDeathScope; } private static void InvokeDefinitiveDeathDrop(Character source) { DefinitiveDeathScope definitiveDeathScope = s_definitiveDeath; if (definitiveDeathScope == null || definitiveDeathScope.DropInvoked || definitiveDeathScope.Invalid || !object.ReferenceEquals(definitiveDeathScope.Source, source)) { LogDiagnosticWarning("[A-01M.4] Foreign or repeated definitive drop call rejected."); return; } definitiveDeathScope.DropInvoked = true; definitiveDeathScope.DropCallSite = true; try { DropOnDeath(source); } finally { definitiveDeathScope.DropCallSite = false; } } private static void CheckDefinitiveDropPermission(DefinitiveDeathScope death) { DeliveryThread(); DeliveryPermit deliveryPermit = death?.Permit; if (death == null || !object.ReferenceEquals(death, s_definitiveDeath) || death.Invalid || !death.WasTamed || !death.HelperCompleted || !death.NullResult || death.InHelper || !death.DropInvoked || !death.DropCallSite || deliveryPermit == null || !object.ReferenceEquals(deliveryPermit.DeathScope, death) || !object.ReferenceEquals(deliveryPermit.Source, death.Source) || CurrentDeliverySession() != deliveryPermit.Session || (deliveryPermit.State != DeliveryPermitState.DropReady && deliveryPermit.State != DeliveryPermitState.DropBound) || (death.Operation != null && death.Operation.Result != BagOperationResult.Pending) || !DetachedDeathView(deliveryPermit)) { throw new InvalidOperationException("No unused server permission for definitive drops in this session."); } } private static void VerifyDeathDrop(DefinitiveDeathScope death, DeathDropReceipt receipt, HashSet identities) { //IL_0032: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) CheckDefinitiveDropPermission(death); if (!receipt.Attempted || !receipt.Identified || (Object)(object)receipt.Output == (Object)null || receipt.Output.m_itemData == null || receipt.Id == ZDOID.None || receipt.Id == death.Permit.SourceId || !identities.Add(receipt.Id)) { throw new InvalidOperationException("Drop absent, unidentifiable or duplicated."); } ZDO zDO = death.Permit.Session.Registry.GetZDO(receipt.Id); ZNetView component = ((Component)receipt.Output).GetComponent(); if (zDO == null || zDO.m_uid != receipt.Id || (Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || component.GetZDO() != zDO || zDO.GetOwner() != death.Permit.Session.Peer || zDO.OwnerRevision != receipt.OwnerRevision || zDO.GetPrefab() != receipt.Prefab) { throw new InvalidOperationException("Drop registry identity, prefab or authority changed."); } SaddlebagSemanticInventory.Require(receipt.Expected, (IEnumerable)(object)new ItemData[1] { receipt.Output.m_itemData }); CheckDefinitiveDropPermission(death); } private static void ApplyAuthorizedDeathDrops(Character source) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00de: 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_026c: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0300: 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_0314: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) DefinitiveDeathScope definitiveDeathScope = s_definitiveDeath; BagOperation operation = null; try { if (definitiveDeathScope == null || !object.ReferenceEquals(definitiveDeathScope.Source, source)) { throw new InvalidOperationException("Definitive drop lacks authenticated postfix context."); } CheckDefinitiveDropPermission(definitiveDeathScope); DeliveryPermit permit = definitiveDeathScope.Permit; if (definitiveDeathScope.Operation != null || permit.Drops.Count != 0 || permit.State != DeliveryPermitState.DropReady) { throw new InvalidOperationException("Definitive delivery already reserved."); } if (!BeginBagOperation(source, null, out operation)) { throw new InvalidOperationException("Repeated source delivery."); } definitiveDeathScope.Operation = operation; operation.SourceId = permit.SourceId; permit.State = DeliveryPermitState.DropBound; operation.SourceBytes = permit.InventoryBytes(); operation.RetainedSource = SaddlebagSemanticInventory.Decode(operation.SourceBytes, permit.Width, permit.Height); List list = SaddlebagSemanticInventory.Copy(operation.RetainedSource.GetAllItems()); Dictionary expected = SaddlebagSemanticInventory.Manifest(list); ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null || !FiniteDropPosition(permit.DropPosition)) { throw new InvalidOperationException("World cannot create verifiable drops."); } HashSet identities = new HashSet(); foreach (ItemData item in list) { GameObject prefab = instance.GetPrefab(((Object)item.m_dropPrefab).name); if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent() == (Object)null || (Object)(object)prefab.GetComponent() == (Object)null) { throw new InvalidOperationException("Drop prefab is not registered in the current world."); } } foreach (ItemData item2 in list) { CheckDefinitiveDropPermission(definitiveDeathScope); if ((Object)(object)ZNetScene.instance != (Object)(object)instance) { throw new InvalidOperationException("World scene changed before drop creation."); } Inventory val = SaddlebagSemanticInventory.Empty(1, 1); val.GetAllItems().Add(SaddlebagSemanticInventory.Copy((IEnumerable)(object)new ItemData[1] { item2 })[0]); DeathDropReceipt deathDropReceipt = new DeathDropReceipt(); deathDropReceipt.ExpectedBytes = SaddlebagSemanticInventory.Save(val); deathDropReceipt.Expected = SaddlebagSemanticInventory.Manifest((IEnumerable)(object)new ItemData[1] { item2 }); deathDropReceipt.Prefab = StringExtensionMethods.GetStableHashCode(((Object)item2.m_dropPrefab).name); DeathDropReceipt deathDropReceipt2 = deathDropReceipt; permit.Drops.Add(deathDropReceipt2); ItemData val2 = SaddlebagSemanticInventory.Copy((IEnumerable)(object)new ItemData[1] { item2 })[0]; operation.MayHaveApplied = true; deathDropReceipt2.Attempted = true; deathDropReceipt2.Output = ItemDrop.DropItem(val2, item2.m_stack, permit.DropPosition, Quaternion.identity); if ((Object)(object)deathDropReceipt2.Output == (Object)null) { throw new InvalidOperationException("DropItem result unknown; automatic replay prohibited."); } operation.Delivered.Add(deathDropReceipt2.Output); ZNetView component = ((Component)deathDropReceipt2.Output).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { throw new InvalidOperationException("Generated drop has no live network identity."); } ZDO zDO = component.GetZDO(); if (zDO == null) { throw new InvalidOperationException("Generated drop has no verifiable record."); } deathDropReceipt2.Id = zDO.m_uid; if (deathDropReceipt2.Id == ZDOID.None || deathDropReceipt2.Id == permit.SourceId || permit.Session.Registry.GetZDO(deathDropReceipt2.Id) != zDO) { throw new InvalidOperationException("Drop identity is absent, reused or not registered."); } deathDropReceipt2.OwnerRevision = zDO.OwnerRevision; deathDropReceipt2.Identified = true; VerifyDeathDrop(definitiveDeathScope, deathDropReceipt2, identities); } if (permit.Drops.Count != list.Count) { throw new InvalidOperationException("Incomplete definitive delivery."); } HashSet identities2 = new HashSet(); List list2 = new List(); foreach (DeathDropReceipt drop in permit.Drops) { VerifyDeathDrop(definitiveDeathScope, drop, identities2); list2.Add(drop.Output.m_itemData); } SaddlebagSemanticInventory.Require(expected, list2); CheckDefinitiveDropPermission(definitiveDeathScope); permit.State = DeliveryPermitState.Consumed; operation.Result = BagOperationResult.Completed; s_dyingSnapshots.Remove(permit.Instance); operation.Snapshot = null; operation.RetainedSource = null; operation.SourceBytes = null; operation.Source = null; operation.Target = null; permit.ReleaseVerifiedPayload(); LogDiagnostic("[A-01M.4] Definitive delivery verified once: " + permit.Nonce + ". Session evidence only, not a world-save guarantee."); } catch (Exception error) { if (definitiveDeathScope != null && definitiveDeathScope.Permit != null && definitiveDeathScope.Permit.State != DeliveryPermitState.Consumed) { definitiveDeathScope.Permit.State = DeliveryPermitState.Ambiguous; } RetainBagFailure(operation, error); } } private static Exception EndDefinitiveDeathScope(Exception __exception, DefinitiveDeathScope __state) { try { if (__state != null && __state.Permit != null && __state.Permit.State != DeliveryPermitState.Consumed) { __state.Permit.State = DeliveryPermitState.Ambiguous; RetainBagFailure(__state.Operation, new InvalidOperationException("Postfix ended without a fully verified definitive delivery; retained without replay.")); } } finally { if (__state != null) { s_definitiveDeath = __state.Previous; } } return __exception; } private static void DeliveryThread() { SynchronizationContext current = SynchronizationContext.Current; if (current == null || current.GetType().FullName != "UnityEngine.UnitySynchronizationContext") { throw new InvalidOperationException("Delivery authorization requires Unity's main thread."); } } private static DeliverySession CurrentDeliverySession() { DeliveryThread(); ZNet instance = ZNet.instance; ZDOMan instance2 = ZDOMan.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer() || instance2 == null || instance.GetWorldUID() == 0) { throw new InvalidOperationException("No authoritative server session for delivery."); } long worldUID = instance.GetWorldUID(); long sessionID = ZDOMan.GetSessionID(); if (sessionID == 0) { throw new InvalidOperationException("Missing server peer identity."); } if (s_deliverySession == null || (Object)(object)s_deliverySession.Network != (Object)(object)instance || s_deliverySession.Registry != instance2 || s_deliverySession.World != worldUID || s_deliverySession.Peer != sessionID) { DeliverySession deliverySession = new DeliverySession(); deliverySession.Network = instance; deliverySession.Registry = instance2; deliverySession.World = worldUID; deliverySession.Peer = sessionID; s_deliverySession = deliverySession; } return s_deliverySession; } private static string PermitKey(DeliverySession session, int instance) { return session.Epoch + "|" + instance; } private static string DeliveryHash(byte[] bytes) { using SHA256 sHA = SHA256.Create(); return Convert.ToBase64String(sHA.ComputeHash(bytes)); } private static bool DetachedDeathView(DeliveryPermit permit) { if ((Object)(object)permit.Source == (Object)null || !permit.Source.IsDead()) { return false; } ZNetView component = ((Component)permit.Source).GetComponent(); if ((Object)(object)component != (Object)null) { return !component.IsValid(); } return false; } private static void RegisterPreDeathDelivery(Character source, DyingTameInventorySnapshot snapshot) { //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: 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_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: 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_0387: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_0396: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_03b8: Unknown result type (might be due to invalid IL or missing references) //IL_03ce: Unknown result type (might be due to invalid IL or missing references) try { DeliveryThread(); if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } DeliverySession deliverySession = CurrentDeliverySession(); string key = PermitKey(deliverySession, ((Object)source).GetInstanceID()); if (s_deliveryPermits.TryGetValue(key, out var value)) { if (value.State != DeliveryPermitState.Consumed) { value.State = DeliveryPermitState.Ambiguous; } throw new InvalidOperationException("A prior death authorization already exists; no replacement or stale-attempt reuse."); } ZNetView component = ((Component)source).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (source.IsPlayer() || !source.IsDead() || source.GetHealth() > 0f || val == null || !component.IsOwner() || val.GetOwner() != deliverySession.Peer || deliverySession.Registry.GetZDO(val.m_uid) != val || val.m_uid == ZDOID.None) { throw new InvalidOperationException("No pre-destruction server ownership validation; client-owned/absent source remains blocked."); } ZDOID uid = val.m_uid; ushort ownerRevision = val.OwnerRevision; int prefab = val.GetPrefab(); if (prefab == 0 || snapshot.Zdoid != uid) { throw new InvalidOperationException("Snapshot entity identity mismatch."); } int width; int height; Inventory val2 = ReadBagModel(source, val, out width, out height); BagOperation bagOperation = new BagOperation(); bagOperation.Snapshot = snapshot; VerifyDyingSnapshot(bagOperation, val2, width, height); byte[] array = SaddlebagSemanticInventory.Save(val2); SaddlebagSemanticInventory.Require(SaddlebagSemanticInventory.Manifest(val2.GetAllItems()), SaddlebagSemanticInventory.Decode(array, width, height).GetAllItems()); Dictionary dictionary = new Dictionary(); dictionary.Add(LevelKey, Math.Max(1, val.GetInt(LevelKey, 1))); dictionary.Add(XpKey, Math.Max(0, val.GetInt(XpKey, 0))); dictionary.Add(PointsKey, Math.Max(0, val.GetInt(PointsKey, 0))); int[] array2 = new int[6] { HealthKey, StaminaKey, DamageKey, DefenseKey, SpeedKey, FoodKey }; foreach (int num in array2) { dictionary.Add(num, val.GetInt(num, 0)); } dictionary.Add(SavedTierKey, val.GetInt(SavedTierKey, 1)); Dictionary dictionary2 = new Dictionary(); int[] array3 = new int[8] { EquippedRightKey, EquippedLeftKey, EquippedHelmetKey, EquippedChestKey, EquippedLegsKey, EquippedShoulderKey, ZDOVars.s_tamedName, ZDOVars.s_tamedNameAuthor }; foreach (int num2 in array3) { dictionary2.Add(num2, val.GetString(num2, string.Empty)); } int width2; int height2; Inventory inventory = ReadBagModel(source, val, out width2, out height2); if (!SaddlebagSemanticInventory.BytesEqual(array, SaddlebagSemanticInventory.Save(inventory)) || width != width2 || height != height2 || CurrentDeliverySession() != deliverySession || !component.IsValid() || !component.IsOwner() || component.GetZDO() != val || deliverySession.Registry.GetZDO(uid) != val || val.GetOwner() != deliverySession.Peer || val.OwnerRevision != ownerRevision || val.GetPrefab() != prefab) { throw new InvalidOperationException("Source changed during authorization capture."); } Vector3 val3 = ((Component)source).transform.position + Vector3.up * 0.75f; if (!FiniteDropPosition(val3)) { throw new InvalidOperationException("Unverifiable pre-death drop position."); } DeliveryPermit deliveryPermit = new DeliveryPermit(deliverySession, source, uid, prefab, deliverySession.Peer, ownerRevision, width, height, array, dictionary, dictionary2, val3); s_deliveryPermits.Add(key, deliveryPermit); snapshot.WorldUid = deliverySession.World; snapshot.ServerSession = deliverySession.Peer; snapshot.SourceOwner = deliveryPermit.Owner; snapshot.SourceRevision = ownerRevision; snapshot.SourcePrefab = prefab; snapshot.DeathNonce = deliveryPermit.Nonce; snapshot.InventoryDigest = deliveryPermit.Digest; snapshot.InventoryVerified = true; snapshot.SerializedBytes = (byte[])array.Clone(); } catch (Exception ex) { LogDiagnosticWarning("[A-01M.2] No prior delivery authorization: " + ex.Message); } } private static void BeginDeliveryReanimationScope(Character __0, out DeliveryFrame __state) { //IL_00d3: Unknown result type (might be due to invalid IL or missing references) __state = new DeliveryFrame { Previous = s_deliveryFrame, Source = __0 }; s_deliveryFrame = __state; try { DeliveryThread(); if ((Object)(object)__0 == (Object)null || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } DeliverySession deliverySession = CurrentDeliverySession(); if (s_deliveryPermits.TryGetValue(PermitKey(deliverySession, ((Object)__0).GetInstanceID()), out var value)) { if (!object.ReferenceEquals(value.Source, __0) || value.State != DeliveryPermitState.Registered || value.Frame != null) { throw new InvalidOperationException("No unused, previously registered permission for a detached death source."); } List list = ((DeliveryDestroyQueue == null) ? null : (DeliveryDestroyQueue.GetValue(deliverySession.Registry) as List)); if (!DetachedDeathView(value) || list == null || !list.Contains(value.SourceId)) { value.State = DeliveryPermitState.Ambiguous; throw new InvalidOperationException("Death view/destruction queue not observed; resurrection, authority loss or unknown deletion retained."); } value.Frame = __state; __state.Permit = value; } } catch (Exception ex) { LogDiagnosticWarning("[A-01M.2] Reanimation delivery unavailable: " + ex.Message); } } private static void AuthorizedReanimationTransfer(Character from, Character to) { DeliveryFrame deliveryFrame = s_deliveryFrame; if (deliveryFrame == null) { LogDiagnosticWarning("[A-01M.2] Missing authenticated transfer scope; delivery blocked."); return; } deliveryFrame.CallSite = true; try { TransferToReanimated(from, to); } finally { deliveryFrame.CallSite = false; } } private static void CheckDeliveryPermission(DeliveryFrame frame) { DeliveryThread(); DeliveryPermit deliveryPermit = frame?.Permit; if (frame == null || !object.ReferenceEquals(frame, s_deliveryFrame) || deliveryPermit == null || deliveryPermit.Frame != frame || (deliveryPermit.State != DeliveryPermitState.Registered && deliveryPermit.State != DeliveryPermitState.Bound) || (frame.Operation != null && frame.Operation.Result != BagOperationResult.Pending) || CurrentDeliverySession() != deliveryPermit.Session || !object.ReferenceEquals(frame.Source, deliveryPermit.Source) || !DetachedDeathView(deliveryPermit)) { throw new InvalidOperationException("Missing, replayed or wrong-session delivery permission."); } } private static ZDO CheckDeliveryDestination(DeliveryFrame frame) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: 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_0108: Unknown result type (might be due to invalid IL or missing references) CheckDeliveryPermission(frame); if ((Object)(object)frame.Destination == (Object)null) { throw new InvalidOperationException("Destination disappeared."); } ZNetView component = ((Component)frame.Destination).GetComponent(); ZDO zDO = frame.Permit.Session.Registry.GetZDO(frame.DestinationId); if (frame.DestinationId == ZDOID.None || frame.DestinationPrefab == 0 || zDO == null || (Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || component.GetZDO() != zDO || zDO.m_uid != frame.DestinationId || zDO.m_uid == frame.Permit.SourceId || zDO.GetOwner() != frame.Permit.Session.Peer || zDO.OwnerRevision != frame.DestinationRevision || zDO.GetPrefab() != frame.DestinationPrefab || frame.Permit.Session.Registry.GetZDO(frame.DestinationId) != zDO) { throw new InvalidOperationException("Destination identity/authority changed."); } return zDO; } private static void ApplyAuthorizedDelivery(Character from, Character to) { //IL_00fa: 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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Expected O, but got Unknown DeliveryFrame deliveryFrame = s_deliveryFrame; BagOperation operation = null; try { if (deliveryFrame == null || !deliveryFrame.CallSite || deliveryFrame.Seen || !object.ReferenceEquals(deliveryFrame.Source, from)) { throw new InvalidOperationException("Transfer did not originate at the authenticated frozen call site."); } deliveryFrame.Seen = true; if ((Object)(object)from == (Object)null) { throw new InvalidOperationException("Missing source character."); } if (deliveryFrame.Permit == null && !s_dyingSnapshots.ContainsKey(((Object)from).GetInstanceID())) { return; } if (!BeginBagOperation(from, to, out operation)) { throw new InvalidOperationException("Repeated bag operation."); } deliveryFrame.Operation = operation; CheckDeliveryPermission(deliveryFrame); DeliveryPermit permit = deliveryFrame.Permit; if ((Object)(object)to == (Object)null || object.ReferenceEquals(from, to)) { throw new InvalidOperationException("Invalid destination."); } ZNetView component = ((Component)to).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (val == null || !component.IsOwner() || val.GetOwner() != permit.Session.Peer || val.m_uid == permit.SourceId) { throw new InvalidOperationException("Destination requires actual server ownership."); } deliveryFrame.Destination = to; deliveryFrame.DestinationId = val.m_uid; deliveryFrame.DestinationPrefab = val.GetPrefab(); deliveryFrame.DestinationRevision = val.OwnerRevision; val = CheckDeliveryDestination(deliveryFrame); Inventory val2 = ReadBagModel(to, val, out deliveryFrame.Width, out deliveryFrame.Height); deliveryFrame.Before = SaddlebagSemanticInventory.Save(val2); operation.RetainedDestination = val2; operation.RetainedSource = SaddlebagSemanticInventory.Decode(permit.InventoryBytes(), permit.Width, permit.Height); operation.SourceBytes = permit.InventoryBytes(); operation.DestinationBytes = (byte[])deliveryFrame.Before.Clone(); operation.SourceId = permit.SourceId; operation.TargetId = deliveryFrame.DestinationId; deliveryFrame.Expected = SaddlebagSemanticInventory.Combined(val2.GetAllItems(), operation.RetainedSource.GetAllItems()); Inventory inventory = SaddlebagSemanticInventory.Prepare(val2, operation.RetainedSource.GetAllItems(), deliveryFrame.Width, deliveryFrame.Height); byte[] array = SaddlebagSemanticInventory.Save(inventory); CheckDeliveryDestination(deliveryFrame); int width; int height; Inventory inventory2 = ReadBagModel(to, val, out width, out height); if (width != deliveryFrame.Width || height != deliveryFrame.Height || !SaddlebagSemanticInventory.BytesEqual(deliveryFrame.Before, SaddlebagSemanticInventory.Save(inventory2))) { throw new InvalidOperationException("Destination preimage changed."); } Container component2 = ((Component)to).GetComponent(); if (((Object)(object)component2 != (Object)null && component2.IsInUse()) || ContainerLoadingField == null) { throw new InvalidOperationException("Destination unavailable for safe application."); } permit.State = DeliveryPermitState.Bound; operation.MayHaveApplied = true; Container val3 = Ensure(to); if ((Object)(object)val3 == (Object)null || val3.GetInventory() == null) { throw new InvalidOperationException("Destination container missing."); } SaddlebagSemanticInventory.Require(SaddlebagSemanticInventory.Manifest(val2.GetAllItems()), val3.GetInventory().GetAllItems()); val = CheckDeliveryDestination(deliveryFrame); bool flag = (bool)ContainerLoadingField.GetValue(val3); try { ContainerLoadingField.SetValue(val3, true); val3.GetInventory().Load(new ZPackage(array)); } finally { ContainerLoadingField.SetValue(val3, flag); } SaddlebagSemanticInventory.Require(deliveryFrame.Expected, val3.GetInventory().GetAllItems()); val = CheckDeliveryDestination(deliveryFrame); val.Set(ZDOVars.s_items, array); val = CheckDeliveryDestination(deliveryFrame); val.Set(BackupSaddlebagsKey, array); val.RemoveString(ZDOVars.s_items); val.RemoveString(BackupSaddlebagsKey); VerifyAuthorizedOutput(deliveryFrame); foreach (KeyValuePair integer in permit.Integers) { val = CheckDeliveryDestination(deliveryFrame); val.Set(integer.Key, integer.Value, false); } foreach (KeyValuePair @string in permit.Strings) { if (!string.IsNullOrEmpty(@string.Value)) { val = CheckDeliveryDestination(deliveryFrame); val.Set(@string.Key, @string.Value); } } RefreshVisual(to); VerifyAuthorizedOutput(deliveryFrame); deliveryFrame.Applied = true; } catch (Exception error) { if (deliveryFrame != null && deliveryFrame.Permit != null) { deliveryFrame.Permit.State = DeliveryPermitState.Ambiguous; } RetainBagFailure(operation, error); } } private static void VerifyAuthorizedOutput(DeliveryFrame frame) { ZDO zdo = CheckDeliveryDestination(frame); Container component = ((Component)frame.Destination).GetComponent(); if ((Object)(object)component == (Object)null || component.GetInventory() == null) { throw new InvalidOperationException("Applied inventory unavailable."); } SaddlebagSemanticInventory.Require(frame.Expected, component.GetInventory().GetAllItems()); SaddlebagSemanticInventory.Require(frame.Expected, SaddlebagSemanticInventory.Decode(ReadBagPacket(zdo), frame.Width, frame.Height).GetAllItems()); CheckDeliveryDestination(frame); } private static void CompleteDeliveryReanimationScope(Character __result, DeliveryFrame __state, bool __runOriginal) { try { if (__state == null || __state.Permit == null) { return; } if (__runOriginal && object.ReferenceEquals(__result, null) && !__state.Seen && !__state.Applied && __state.Operation == null) { CheckDeliveryPermission(__state); RequireDefinitiveHelperContext(__state); __state.ReturnedNull = true; return; } if (!__state.Applied || !object.ReferenceEquals(__result, __state.Destination)) { throw new InvalidOperationException("No verified matching reanimation result; permission cannot be replayed."); } VerifyAuthorizedOutput(__state); DeliveryPermit permit = __state.Permit; ZDO val = CheckDeliveryDestination(__state); foreach (KeyValuePair integer in permit.Integers) { if (val.GetInt(integer.Key, int.MinValue) != integer.Value) { throw new InvalidOperationException("Captured metadata mismatch."); } } foreach (KeyValuePair @string in permit.Strings) { if (!string.IsNullOrEmpty(@string.Value) && val.GetString(@string.Key, string.Empty) != @string.Value) { throw new InvalidOperationException("Captured metadata mismatch."); } } CheckDeliveryDestination(__state); __state.Returned = true; } catch (Exception error) { if (__state != null && __state.Permit != null) { __state.Permit.State = DeliveryPermitState.Ambiguous; } RetainBagFailure(__state?.Operation, error); } } private static Exception EndDeliveryReanimationScope(Exception __exception, Character __result, DeliveryFrame __state) { try { if (__state != null && __state.Permit != null) { if (__state.ReturnedNull && __exception == null && object.ReferenceEquals(__result, null) && !__state.Seen && !__state.Applied && __state.Operation == null) { CheckDeliveryPermission(__state); DefinitiveDeathScope definitiveDeathScope = RequireDefinitiveHelperContext(__state); __state.Permit.DeathScope = definitiveDeathScope; definitiveDeathScope.Permit = __state.Permit; __state.Permit.State = DeliveryPermitState.DropReady; return __exception; } if (!__state.Returned || __exception != null || !object.ReferenceEquals(__result, __state.Destination)) { throw new InvalidOperationException("Unfinished, exceptional or changed helper result; retain permission as ambiguous."); } VerifyAuthorizedOutput(__state); DeliveryPermit permit = __state.Permit; ZDO val = CheckDeliveryDestination(__state); foreach (KeyValuePair integer in permit.Integers) { if (val.GetInt(integer.Key, int.MinValue) != integer.Value) { throw new InvalidOperationException("Final metadata mismatch."); } } foreach (KeyValuePair @string in permit.Strings) { if (!string.IsNullOrEmpty(@string.Value) && val.GetString(@string.Key, string.Empty) != @string.Value) { throw new InvalidOperationException("Final metadata mismatch."); } } CheckDeliveryDestination(__state); permit.State = DeliveryPermitState.Consumed; __state.Operation.Result = BagOperationResult.Completed; s_dyingSnapshots.Remove(permit.Instance); __state.Operation.Snapshot = null; __state.Operation.SourceBytes = null; __state.Operation.DestinationBytes = null; __state.Operation.RetainedSource = null; __state.Operation.RetainedDestination = null; __state.Operation.Source = null; __state.Operation.Target = null; __state.Before = null; __state.Expected = null; permit.ReleaseVerifiedPayload(); LogDiagnostic("[A-01M.2] Prior permission consumed once after verified delivery: " + permit.Nonce + ". No world-save guarantee."); } } catch (Exception error) { if (__state != null && __state.Permit != null) { __state.Permit.State = DeliveryPermitState.Ambiguous; } RetainBagFailure(__state?.Operation, error); } finally { if (__state != null) { s_deliveryFrame = __state.Previous; } } return __exception; } private static BagAuthority ObserveBagAuthority(Character from, Character to, BagOperation operation) { //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011b: 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_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) BagAuthority bagAuthority = new BagAuthority(); bagAuthority.Network = ZNet.instance; if ((Object)(object)bagAuthority.Network == (Object)null || !bagAuthority.Network.IsServer() || ZDOMan.instance == null) { throw new InvalidOperationException("A-01M requires the authoritative host/server."); } bagAuthority.World = bagAuthority.Network.GetWorldUID(); bagAuthority.Peer = ZDOMan.GetSessionID(); bagAuthority.SourceView = ((Component)from).GetComponent(); bagAuthority.TargetView = (((Object)(object)to == (Object)null) ? null : ((Component)to).GetComponent()); if ((Object)(object)bagAuthority.SourceView == (Object)null || !bagAuthority.SourceView.IsValid() || ((Object)(object)to != (Object)null && ((Object)(object)bagAuthority.TargetView == (Object)null || !bagAuthority.TargetView.IsValid()))) { throw new InvalidOperationException("Detached source/target has no current authority; a saved ZDO reference is insufficient."); } bagAuthority.Source = bagAuthority.SourceView.GetZDO(); bagAuthority.Target = (((Object)(object)to == (Object)null) ? null : bagAuthority.TargetView.GetZDO()); if (bagAuthority.Source == null || ((Object)(object)to != (Object)null && bagAuthority.Target == null) || bagAuthority.Source.m_uid != operation.SourceId || (bagAuthority.Target != null && (bagAuthority.Target.m_uid != operation.TargetId || bagAuthority.Target.m_uid == bagAuthority.Source.m_uid))) { throw new InvalidOperationException("Operation entity identity changed."); } bagAuthority.SourceRevision = bagAuthority.Source.OwnerRevision; bagAuthority.TargetRevision = (ushort)((bagAuthority.Target != null) ? bagAuthority.Target.OwnerRevision : 0); bagAuthority.SourcePrefab = bagAuthority.Source.GetPrefab(); bagAuthority.TargetPrefab = ((bagAuthority.Target != null) ? bagAuthority.Target.GetPrefab() : 0); bagAuthority.Check(); return bagAuthority; } private static bool BeginBagOperation(Character from, Character to, out BagOperation operation) { //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) operation = null; SynchronizationContext current = SynchronizationContext.Current; if (current == null || current.GetType().FullName != "UnityEngine.UnitySynchronizationContext") { throw new InvalidOperationException("Bag delivery requires the Unity main thread."); } int instanceID = ((Object)from).GetInstanceID(); if (s_bagOperations.TryGetValue(instanceID, out operation)) { LogDiagnosticWarning(string.Concat("[A-01M] Repeated delivery blocked: ", operation.Id, " (", operation.Result, ").")); return false; } s_dyingSnapshots.TryGetValue(instanceID, out var value); ZNetView component = ((Component)from).GetComponent(); ZNetView val = (((Object)(object)to == (Object)null) ? null : ((Component)to).GetComponent()); operation = new BagOperation { Source = from, Target = to, Snapshot = value, SourceId = (value?.Zdoid ?? (((Object)(object)component != (Object)null && component.IsValid() && component.GetZDO() != null) ? component.GetZDO().m_uid : ZDOID.None)), TargetId = (((Object)(object)val != (Object)null && val.IsValid() && val.GetZDO() != null) ? val.GetZDO().m_uid : ZDOID.None) }; s_bagOperations.Add(instanceID, operation); foreach (BagOperation value2 in s_bagOperations.Values) { if (!object.ReferenceEquals(value2, operation) && value2.Result != BagOperationResult.Completed && (object.ReferenceEquals(value2.Source, from) || object.ReferenceEquals(value2.Target, from) || ((Object)(object)to != (Object)null && (object.ReferenceEquals(value2.Source, to) || object.ReferenceEquals(value2.Target, to))) || (operation.SourceId != ZDOID.None && (operation.SourceId == value2.SourceId || operation.SourceId == value2.TargetId)) || (operation.TargetId != ZDOID.None && (operation.TargetId == value2.SourceId || operation.TargetId == value2.TargetId)))) { throw new InvalidOperationException("Entity participates in another unresolved delivery; retained without application."); } } return true; } private static byte[] ReadBagPacket(ZDO zdo) { byte[] array = null; int[] array2 = new int[2] { ZDOVars.s_items, BackupSaddlebagsKey }; foreach (int num in array2) { byte[] array3 = zdo.GetByteArray(num, (byte[])null); string text = zdo.GetString(num, string.Empty); if (!string.IsNullOrEmpty(text)) { if (text.Length > 2097152) { throw new InvalidOperationException("Oversized legacy inventory."); } byte[] array4 = Convert.FromBase64String(text); if (array3 != null && !SaddlebagSemanticInventory.BytesEqual(array3, array4)) { throw new InvalidOperationException("Conflicting inventory encodings."); } array3 = array4; } if (array3 != null) { if (array3.Length == 0 || array3.Length > 1048576 || (array != null && !SaddlebagSemanticInventory.BytesEqual(array, array3))) { throw new InvalidOperationException("Conflicting or unverifiable inventory replicas."); } array = (byte[])array3.Clone(); } } return array; } private static Inventory ReadBagModel(Character c, ZDO zdo, out int width, out int height) { Container component = ((Component)c).GetComponent(); Inventory val = (((Object)(object)component == (Object)null) ? null : component.GetInventory()); GetDimensions(c, out width, out height); if (val != null) { if (InvWidthField == null || InvHeightField == null) { throw new InvalidOperationException("Inventory dimensions unavailable."); } width = (int)InvWidthField.GetValue(val); height = (int)InvHeightField.GetValue(val); } byte[] array = ReadBagPacket(zdo); Inventory val2 = SaddlebagSemanticInventory.Decode(array, width, height); if (val != null && (IsContainerLoaded(component) || val.NrOfItems() > 0)) { Inventory val3 = SaddlebagSemanticInventory.Decode(SaddlebagSemanticInventory.Save(val), width, height); if (array != null) { SaddlebagSemanticInventory.Require(SaddlebagSemanticInventory.Manifest(val3.GetAllItems()), val2.GetAllItems()); } return val3; } return val2; } private static void RetainBagFailure(BagOperation operation, Exception error) { if (operation != null && operation.Result == BagOperationResult.Completed) { LogDiagnosticWarning("[A-01M] Inventory delivery already completed; subsequent metadata/visual error does not authorize replay: " + operation.Id + ": " + error.Message); return; } if (operation != null && operation.MayHaveApplied && operation.Result != BagOperationResult.Completed) { operation.Result = BagOperationResult.Ambiguous; } LogDiagnosticWarning("[A-01M] Delivery retained; automatic retries blocked. " + ((operation == null) ? "" : string.Concat(operation.Id, " (", operation.Result, "): ")) + error.Message); } private static void VerifyDyingSnapshot(BagOperation operation, Inventory source, int width, int height) { DyingTameInventorySnapshot snapshot = operation.Snapshot; if (snapshot != null) { Dictionary expected = SaddlebagSemanticInventory.Manifest(source.GetAllItems()); if (snapshot.CachedItems.Count > 0) { SaddlebagSemanticInventory.Require(expected, snapshot.CachedItems); } if (snapshot.SerializedBytes != null) { SaddlebagSemanticInventory.Require(expected, SaddlebagSemanticInventory.Decode(snapshot.SerializedBytes, width, height).GetAllItems()); } } } private static void ClearVerifiedBagSource(Character from, BagAuthority authority, BagOperation operation, Action verifyDelivery) { authority.Check(); int width; int height; Inventory val = ReadBagModel(from, authority.Source, out width, out height); SaddlebagSemanticInventory.Require(SaddlebagSemanticInventory.Manifest(operation.RetainedSource.GetAllItems()), val.GetAllItems()); verifyDelivery(); authority.Check(); Container component = ((Component)from).GetComponent(); bool flag = (Object)(object)component != (Object)null && ContainerLoadingField != null && (bool)ContainerLoadingField.GetValue(component); if ((Object)(object)component != (Object)null && ContainerLoadingField == null) { throw new InvalidOperationException("Cannot suppress source save callbacks safely."); } try { if ((Object)(object)component != (Object)null) { ContainerLoadingField.SetValue(component, true); } authority.Check(); if ((Object)(object)component != (Object)null && component.GetInventory() != null) { component.GetInventory().RemoveAll(); } verifyDelivery(); authority.Check(); authority.Source.RemoveByteArray(ZDOVars.s_items); authority.Source.RemoveByteArray(BackupSaddlebagsKey); authority.Source.RemoveString(ZDOVars.s_items); authority.Source.RemoveString(BackupSaddlebagsKey); authority.Check(); if (((Object)(object)component != (Object)null && component.GetInventory() != null && component.GetInventory().NrOfItems() != 0) || ReadBagPacket(authority.Source) != null) { throw new InvalidOperationException("Source cleanup did not complete."); } } finally { if ((Object)(object)component != (Object)null && ContainerLoadingField != null) { ContainerLoadingField.SetValue(component, flag); } } operation.Result = BagOperationResult.Completed; s_dyingSnapshots.Remove(((Object)from).GetInstanceID()); operation.Snapshot = null; operation.RetainedSource = null; operation.RetainedDestination = null; operation.SourceBytes = null; operation.DestinationBytes = null; operation.Source = null; operation.Target = null; operation.Delivered.Clear(); } public static bool OpenAuthorized(Player player, Character c) { s_allowWheelOrCommandOpen = true; try { return Open(player, c); } finally { s_allowWheelOrCommandOpen = false; } } public static void LogDiagnostic(string message) { if (Log != null) { Log.LogInfo((object)message); } } public static void LogDiagnosticWarning(string message) { if (Log != null) { Log.LogWarning((object)message); } } public static ZDO GetZdo(Character c) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)c == (Object)null) { return null; } ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && ZDOMan.instance != null) { ZDO zDO = component.GetZDO(); if (zDO != null && ZDOMan.instance.GetZDO(zDO.m_uid) == zDO) { return zDO; } } return null; } public static bool TryGetDyingZdoid(Character c, out ZDOID zdoid) { //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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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) zdoid = ZDOID.None; if ((Object)(object)c == (Object)null) { return false; } if (s_dyingSnapshots.TryGetValue(((Object)c).GetInstanceID(), out var value) && value != null && value.Zdoid != ZDOID.None) { zdoid = value.Zdoid; return true; } return false; } public static byte[] GetSaddlebagBytes(ZDO zdo, out bool migrated) { migrated = false; if (zdo == null) { return null; } byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); if (byteArray != null && byteArray.Length > 0) { return byteArray; } byte[] byteArray2 = zdo.GetByteArray(BackupSaddlebagsKey, (byte[])null); if (byteArray2 != null && byteArray2.Length > 0) { zdo.Set(ZDOVars.s_items, byteArray2); LogDiagnostic("[Sync] Restored " + byteArray2.Length + " saddlebag bytes from backup key."); return byteArray2; } string text = zdo.GetString(ZDOVars.s_items, string.Empty); if (string.IsNullOrEmpty(text)) { text = zdo.GetString(BackupSaddlebagsKey, string.Empty); } if (!string.IsNullOrEmpty(text)) { try { byte[] array = Convert.FromBase64String(text); if (array != null && array.Length > 0) { zdo.Set(ZDOVars.s_items, array); zdo.Set(BackupSaddlebagsKey, array); zdo.RemoveString(ZDOVars.s_items); zdo.RemoveString(BackupSaddlebagsKey); migrated = true; LogDiagnostic("[Sync] Migrated legacy Base64 string (" + text.Length + " chars) to byte[] (" + array.Length + " bytes)."); return array; } } catch (FormatException ex) { LogDiagnosticWarning("[Sync] Failed to parse legacy string: " + ex.Message); } } return null; } public static bool HasSerializedItems(byte[] bytes) { if (bytes == null || bytes.Length <= 6) { return false; } try { short num = BitConverter.ToInt16(bytes, 4); return num > 0; } catch { return bytes.Length > 6; } } public static bool HasSaddlebagData(ZDO zdo) { if (zdo == null) { return false; } if (HasSerializedItems(zdo.GetByteArray(ZDOVars.s_items, (byte[])null))) { return true; } if (HasSerializedItems(zdo.GetByteArray(BackupSaddlebagsKey, (byte[])null))) { return true; } string text = zdo.GetString(ZDOVars.s_items, string.Empty); if (!string.IsNullOrEmpty(text) && text.Length > 8) { return true; } string text2 = zdo.GetString(BackupSaddlebagsKey, string.Empty); if (!string.IsNullOrEmpty(text2) && text2.Length > 8) { return true; } return false; } public static void GetDimensions(Character c, out int width, out int height) { if ((Object)(object)c == (Object)null) { width = 3; height = 2; return; } float height2 = c.GetHeight(); float radius = c.GetRadius(); if (height2 >= 4f || radius >= 2.2f) { width = 8; height = 4; } else if (height2 >= 2.2f || radius >= 1.5f) { width = 6; height = 4; } else if (height2 >= 1.2f || radius >= 0.9f) { width = 4; height = 3; } else { width = 3; height = 2; } } public static void ApplyDimensions(Container container, Character c) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)container != (Object)null) || !((Object)(object)c != (Object)null)) { return; } GetDimensions(c, out var width, out var height); container.m_width = width; container.m_height = height; string text = (ModLanguage.IsEnglish ? "Saddlebags of " : "Alforjas de "); container.m_name = text + c.GetHoverName(); container.m_privacy = (PrivacySetting)2; container.m_checkGuardStone = false; container.m_autoDestroyEmpty = false; Inventory inventory = container.GetInventory(); if (inventory != null) { if (InvNameField != null) { InvNameField.SetValue(inventory, container.m_name); } if (InvWidthField != null) { InvWidthField.SetValue(inventory, width); } if (InvHeightField != null) { InvHeightField.SetValue(inventory, height); } } } public static void ForceLoad(Container container, Character c) { //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Expected O, but got Unknown if ((Object)(object)container == (Object)null || (Object)(object)c == (Object)null) { return; } ApplyDimensions(container, c); ZDO zdo = GetZdo(c); if (zdo == null) { return; } bool migrated; byte[] saddlebagBytes = GetSaddlebagBytes(zdo, out migrated); Inventory inventory = container.GetInventory(); if (inventory != null && saddlebagBytes != null && saddlebagBytes.Length > 0) { bool flag = ContainerInUseField != null && (bool)ContainerInUseField.GetValue(container); try { if (flag && ContainerInUseField != null) { ContainerInUseField.SetValue(container, false); } if (inventory.NrOfItems() == 0 && ContainerLastRevisionField != null) { ContainerLastRevisionField.SetValue(container, uint.MaxValue); } if (ContainerLoadMethod != null) { ContainerLoadMethod.Invoke(container, null); } if (inventory.NrOfItems() == 0) { try { ZPackage val = new ZPackage(saddlebagBytes); if (ContainerLoadingField != null) { ContainerLoadingField.SetValue(container, true); } inventory.Load(val); } catch (Exception ex) { LogDiagnosticWarning("[Sync] Direct load fallback failed: " + ex.Message); } finally { if (ContainerLoadingField != null) { ContainerLoadingField.SetValue(container, false); } } } } catch (Exception ex2) { LogDiagnosticWarning("[Sync] Error loading saddlebags for " + ((Object)c).name + ": " + ex2.Message); } finally { if (flag && ContainerInUseField != null) { ContainerInUseField.SetValue(container, true); } } } if (saddlebagBytes != null && saddlebagBytes.Length > 0) { byte[] byteArray = zdo.GetByteArray(BackupSaddlebagsKey, (byte[])null); if (byteArray == null || byteArray.Length != saddlebagBytes.Length) { zdo.Set(BackupSaddlebagsKey, saddlebagBytes); } } s_loadedContainers.Add(((Object)container).GetInstanceID()); } public static bool IsContainerLoaded(Container container) { if ((Object)(object)container != (Object)null) { return s_loadedContainers.Contains(((Object)container).GetInstanceID()); } return false; } public static Container Ensure(Character c) { if ((Object)(object)c == (Object)null) { return null; } if (!c.IsTamed() && !s_dyingSnapshots.ContainsKey(((Object)c).GetInstanceID())) { return null; } Container val = ((Component)c).GetComponent(); if ((Object)(object)val == (Object)null) { val = ((Component)c).gameObject.AddComponent(); } ApplyDimensions(val, c); Inventory inventory = val.GetInventory(); ZDO zdo = GetZdo(c); bool flag = zdo != null && HasSaddlebagData(zdo); if (!IsContainerLoaded(val) || (inventory != null && inventory.NrOfItems() == 0 && flag && !val.IsInUse())) { ForceLoad(val, c); } return val; } public static Inventory GetInventory(Character c, bool claimOwnership) { if ((Object)(object)c == (Object)null || !c.IsTamed()) { return null; } if (claimOwnership) { ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && !component.IsOwner()) { component.ClaimOwnership(); } } Container val = Ensure(c); if ((Object)(object)val == (Object)null) { return null; } return val.GetInventory(); } public static bool Open(Player player, Character c) { if ((Object)(object)player == (Object)null || (Object)(object)c == (Object)null || !c.IsTamed()) { return false; } if (!s_allowWheelOrCommandOpen) { return false; } ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && !component.IsOwner()) { component.ClaimOwnership(); } Container val = Ensure(c); if ((Object)(object)val == (Object)null) { return false; } ForceLoad(val, c); if (val.IsInUse()) { ((Character)player).Message((MessageType)2, "$msg_inuse", 0, (Sprite)null, false); return false; } val.SetInUse(true); if ((Object)(object)InventoryGui.instance != (Object)null) { InventoryGui.instance.Show(val, 1); EmitWhistle(); return true; } return false; } private static void EmitWhistle() { try { if (s_whistleEmitMethod != null && s_whistleRegroupVal != null) { s_whistleEmitMethod.Invoke(null, new object[1] { s_whistleRegroupVal }); } } catch { } } private static void RefreshVisual(Character c) { try { if (s_refreshVisualMethod != null) { s_refreshVisualMethod.Invoke(null, new object[1] { c }); } } catch { } } public static void SaveNow(Character c) { if ((Object)(object)c == (Object)null) { return; } Container component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null) { ZNetView component2 = ((Component)c).GetComponent(); if ((Object)(object)component2 != (Object)null && component2.IsValid() && !component2.IsOwner()) { component2.ClaimOwnership(); } if (ContainerSaveMethod != null) { ContainerSaveMethod.Invoke(component, null); } } } public static void TransferToReanimated(Character from, Character to) { ApplyAuthorizedDelivery(from, to); } public static GameObject ResolveDropPrefab(ItemData item) { if (item == null) { return null; } if ((Object)(object)item.m_dropPrefab != (Object)null) { return item.m_dropPrefab; } if ((Object)(object)ObjectDB.instance == (Object)null) { return null; } string text = ((item.m_shared != null) ? item.m_shared.m_name : null); if (!string.IsNullOrEmpty(text)) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); if ((Object)(object)itemPrefab != (Object)null) { return itemPrefab; } if (ObjectDB.instance.m_items != null) { for (int i = 0; i < ObjectDB.instance.m_items.Count; i++) { GameObject val = ObjectDB.instance.m_items[i]; if (!((Object)(object)val == (Object)null)) { ItemDrop component = val.GetComponent(); if ((Object)(object)component != (Object)null && component.m_itemData != null && component.m_itemData.m_shared != null && string.Equals(component.m_itemData.m_shared.m_name, text, StringComparison.OrdinalIgnoreCase)) { return val; } } } } } return null; } public static void Character_OnDeath_Prefix(Character __instance) { //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: 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_0185: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_018a: 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_019b: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Expected O, but got Unknown if ((Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } int instanceID = ((Object)__instance).GetInstanceID(); bool flag = __instance.IsTamed(); ZNetView component = ((Component)__instance).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (!flag && (val == null || !HasSaddlebagData(val))) { return; } try { if (s_dyingSnapshots.Count > 10) { List list = null; DateTime dateTime = DateTime.UtcNow.AddSeconds(-60.0); foreach (KeyValuePair s_dyingSnapshot in s_dyingSnapshots) { if (s_dyingSnapshot.Value.CreatedAt < dateTime) { if (list == null) { list = new List(); } list.Add(s_dyingSnapshot.Key); } } if (list != null) { for (int i = 0; i < list.Count; i++) { s_dyingSnapshots.Remove(list[i]); } } } bool isOwner = (Object)(object)component != (Object)null && component.IsOwner(); Vector3 dropPosition = ((Component)__instance).transform.position + Vector3.up * 0.75f; Container component2 = ((Component)__instance).GetComponent(); if ((Object)(object)component2 != (Object)null) { ForceLoad(component2, __instance); } bool migrated; byte[] array = ((val != null) ? GetSaddlebagBytes(val, out migrated) : null); DyingTameInventorySnapshot dyingTameInventorySnapshot = new DyingTameInventorySnapshot(); dyingTameInventorySnapshot.InstanceId = instanceID; dyingTameInventorySnapshot.Zdoid = val?.m_uid ?? ZDOID.None; dyingTameInventorySnapshot.ZdoRef = null; dyingTameInventorySnapshot.DropPosition = dropPosition; dyingTameInventorySnapshot.SerializedBytes = ((array != null) ? ((byte[])array.Clone()) : null); dyingTameInventorySnapshot.IsOwner = isOwner; dyingTameInventorySnapshot.CreatureName = __instance.GetHoverName(); DyingTameInventorySnapshot dyingTameInventorySnapshot2 = dyingTameInventorySnapshot; if ((Object)(object)component2 != (Object)null && component2.GetInventory() != null && component2.GetInventory().NrOfItems() > 0) { foreach (ItemData allItem in component2.GetInventory().GetAllItems()) { if (allItem != null) { dyingTameInventorySnapshot2.CachedItems.Add(allItem.Clone()); } } } else if (array != null && array.Length > 6) { try { Inventory val2 = new Inventory("PreDeathInv", (Sprite)null, 10, 10); val2.Load(new ZPackage(array)); foreach (ItemData allItem2 in val2.GetAllItems()) { if (allItem2 != null) { dyingTameInventorySnapshot2.CachedItems.Add(allItem2.Clone()); } } } catch (Exception ex) { LogDiagnosticWarning("[Sync] Pre-death fallback inventory load error: " + ex.Message); } } s_dyingSnapshots[instanceID] = dyingTameInventorySnapshot2; RegisterPreDeathDelivery(__instance, dyingTameInventorySnapshot2); LogDiagnostic($"[Sync] Character.OnDeath PREFIX: captured dying companion '{dyingTameInventorySnapshot2.CreatureName}' (ID: {dyingTameInventorySnapshot2.Zdoid}, IsOwner: {dyingTameInventorySnapshot2.IsOwner}, Items: {dyingTameInventorySnapshot2.CachedItems.Count}, RawBytes: {((dyingTameInventorySnapshot2.SerializedBytes != null) ? dyingTameInventorySnapshot2.SerializedBytes.Length : 0)}). Protected from ZNetScene.Destroy ZDO detachment."); } catch (Exception ex2) { LogDiagnosticWarning("[Sync] Character.OnDeath PREFIX error capturing dying companion: " + ex2.Message); } } public static void DropOnDeath(Character c) { ApplyAuthorizedDeathDrops(c); } public static bool ContainerSavePrefix(Container __instance) { if ((Object)(object)__instance == (Object)null) { return true; } Character component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || component.IsPlayer()) { return true; } Inventory inventory = __instance.GetInventory(); ZDO zdo = GetZdo(component); if (inventory != null && zdo != null && inventory.NrOfItems() == 0 && !IsContainerLoaded(__instance) && HasSaddlebagData(zdo)) { LogDiagnostic("[Sync] Prevented empty overwrite on save for " + component.GetHoverName() + "; forcing load first."); ForceLoad(__instance, component); return false; } return true; } public static void ContainerSavePostfix(Container __instance) { if ((Object)(object)__instance == (Object)null) { return; } Character component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || component.IsPlayer()) { return; } ZDO zdo = GetZdo(component); if (zdo != null) { byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); Inventory inventory = __instance.GetInventory(); if (byteArray != null && byteArray.Length > 0) { zdo.Set(BackupSaddlebagsKey, byteArray); } else if (inventory != null && inventory.NrOfItems() == 0 && IsContainerLoaded(__instance)) { zdo.RemoveByteArray(BackupSaddlebagsKey); zdo.RemoveString(BackupSaddlebagsKey); } } } public static bool ForceLoad_Prefix(Container container, Character c) { ForceLoad(container, c); return false; } public static bool IsContainerLoaded_Prefix(Container container, ref bool __result) { __result = IsContainerLoaded(container); return false; } public static bool Ensure_Prefix(Character c, ref Container __result) { __result = Ensure(c); return false; } public static bool GetInventory_Prefix(Character c, bool claimOwnership, ref Inventory __result) { __result = GetInventory(c, claimOwnership); return false; } public static bool Open_Prefix(Player player, Character c, ref bool __result) { __result = Open(player, c); return false; } public static bool SaveNow_Prefix(Character c) { SaveNow(c); return false; } public static bool TransferToReanimated_Prefix(Character from, Character to) { TransferToReanimated(from, to); return false; } public static bool DropOnDeath_Prefix(Character c) { DropOnDeath(c); return false; } public static bool OldSavePrefix_Override(Container __instance, ref bool __result) { __result = ContainerSavePrefix(__instance); return false; } public static bool OldSavePostfix_Override(Container __instance) { ContainerSavePostfix(__instance); return false; } public static void Install(Harmony harmony, Assembly coreAssembly) { //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Expected O, but got Unknown //IL_033f: Expected O, but got Unknown //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_0397: Expected O, but got Unknown if (s_installed) { return; } try { Type type = coreAssembly.GetType("TameMate.WhistleAudio"); if (type != null) { s_whistleEmitMethod = AccessTools.Method(type, "Emit", (Type[])null, (Type[])null); Type type2 = coreAssembly.GetType("TameMate.WhistleKind"); if (type2 != null) { s_whistleRegroupVal = Enum.Parse(type2, "Regroup"); } } } catch { } try { Type type3 = coreAssembly.GetType("TameMate.CompanionEquipment"); if (type3 != null) { s_refreshVisualMethod = AccessTools.Method(type3, "RefreshVisualEquipment", new Type[1] { typeof(Character) }, (Type[])null); } } catch { } Type type4 = coreAssembly.GetType("TameMate.CompanionSaddlebags"); if (type4 != null) { PatchMethod(harmony, type4, "ForceLoad", new Type[2] { typeof(Container), typeof(Character) }, "ForceLoad_Prefix"); PatchMethod(harmony, type4, "IsContainerLoaded", new Type[1] { typeof(Container) }, "IsContainerLoaded_Prefix"); PatchMethod(harmony, type4, "Ensure", new Type[1] { typeof(Character) }, "Ensure_Prefix"); PatchMethod(harmony, type4, "GetInventory", new Type[2] { typeof(Character), typeof(bool) }, "GetInventory_Prefix"); PatchMethod(harmony, type4, "Open", new Type[2] { typeof(Player), typeof(Character) }, "Open_Prefix"); PatchMethod(harmony, type4, "SaveNow", new Type[1] { typeof(Character) }, "SaveNow_Prefix"); PatchMethod(harmony, type4, "TransferToReanimated", new Type[2] { typeof(Character), typeof(Character) }, "TransferToReanimated_Prefix"); PatchMethod(harmony, type4, "DropOnDeath", new Type[1] { typeof(Character) }, "DropOnDeath_Prefix"); } Type type5 = coreAssembly.GetType("TameMate.SaddlebagContainerSavePatch"); if (type5 != null) { PatchMethod(harmony, type5, "Prefix", new Type[1] { typeof(Container) }, "OldSavePrefix_Override"); PatchMethod(harmony, type5, "Postfix", new Type[1] { typeof(Container) }, "OldSavePostfix_Override"); } MethodInfo methodInfo = AccessTools.Method(typeof(Container), "Save", (Type[])null, (Type[])null); if (methodInfo != null) { try { harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)1, "mitsu.tamemate"); harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)2, "mitsu.tamemate"); } catch { } MethodInfo methodInfo2 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "ContainerSavePrefix", (Type[])null, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "ContainerSavePostfix", (Type[])null, (Type[])null); if (methodInfo2 != null && methodInfo3 != null) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } MethodInfo methodInfo4 = AccessTools.Method(typeof(Character), "OnDeath", (Type[])null, (Type[])null); if (methodInfo4 != null) { MethodInfo methodInfo5 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "Character_OnDeath_Prefix", (Type[])null, (Type[])null); if (methodInfo5 != null) { harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(methodInfo5), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); LogDiagnostic("[Sync] Pre-destruction Character.OnDeath snapshot prefix installed successfully."); } } s_installed = true; LogDiagnostic("[Sync] CompanionSaddlebagsSync 0.7.52 installed successfully."); } private static void PatchMethod(Harmony harmony, Type targetType, string methodName, Type[] parameters, string prefixName) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown try { MethodInfo methodInfo = AccessTools.Method(targetType, methodName, parameters, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(CompanionSaddlebagsSync), prefixName, (Type[])null, (Type[])null); if (methodInfo != null && methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex) { LogDiagnosticWarning("[Sync] Failed to patch " + targetType.Name + "." + methodName + ": " + ex.Message); } } public static void Uninstall() { s_loadedContainers.Clear(); s_installed = false; } } public static class ContextualAdviceEngine { private const float MinAdviceInterval = 20f; private static float s_lastAdviceTime; public static void Init(Harmony harmony) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown try { Type type = Type.GetType("TameMate.CompanionSaddlebags, TameMate"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "Open", new Type[2] { typeof(Player), typeof(Character) }, (Type[])null); if (methodInfo != null) { HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(ContextualAdviceEngine), "Saddlebag_Open_Postfix", (Type[])null, (Type[])null)); harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate] ContextualAdviceEngine saddlebags patch warning: " + ex.Message)); } } private static bool CanDeliverAdvice(Player player, string key) { if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer) { return false; } if (Time.time - s_lastAdviceTime < 20f) { return false; } string text = AdvicePolicy.Key(key); if (player.HaveSeenTutorial(text)) { return false; } return true; } public static void OnHoverTameable(Player player, Character target) { if (!((Object)(object)target == (Object)null) && !target.IsTamed() && !target.IsPlayer()) { string text = target.m_name ?? ""; if (text.IndexOf("Deer", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Hare", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Ciervo", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Liebre", StringComparison.OrdinalIgnoreCase) >= 0) { TriggerWildlifeAdvice(player); } else { TriggerTamingRulesAdvice(player); } } } public static void TriggerTamingRulesAdvice(Player player) { if (CanDeliverAdvice(player, "tamemate_taming_rules_0742")) { s_lastAdviceTime = Time.time; string text = "TameMate · Doma de Criaturas"; string text2 = (ModLanguage.IsEnglish ? "Starter Feral animals remain accessible. Higher tiers and Monstrum creatures require progression. Combat uses real health loss, bare fists for starter knockouts, and a sustained trial. See the target's hover and F11." : "Los animales Feral iniciales siguen siendo accesibles. Los tiers superiores y criaturas de Monstrum requieren progresión. La doma de combate usa pérdida real de salud, puños sin arma para los noqueos iniciales y una prueba sostenida. Consulta los requisitos al apuntar y en F11."); AdviceFeature.Queue("tamemate_taming_rules_0742", text, text2, "tamemate_guide"); } } public static void TriggerWildlifeAdvice(Player player) { if (CanDeliverAdvice(player, "tamemate_wildlife_fauna_0744")) { s_lastAdviceTime = Time.time; string text = (ModLanguage.IsEnglish ? "Wildlife Fauna" : "Fauna Silvestre"); string text2 = (ModLanguage.IsEnglish ? "Deer and hares can be knocked out and tamed with bare fists. They follow you and carry saddlebags, but are too delicate to be ridden. Check F11." : "Los ciervos y liebres se domestican noqueándolos a puño limpio. Te seguirán y llevarán alforjas, pero son demasiado delicados para montarlos. Consulta F11."); AdviceFeature.Queue("tamemate_wildlife_fauna_0744", text, text2, "tamemate_guide"); } } public static void Saddlebag_Open_Postfix(Player player, Character __1, bool __result) { if (__result && !((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer)) { TriggerSaddlebagsAdvice(player); } } public static void TriggerSaddlebagsAdvice(Player player) { if (CanDeliverAdvice(player, "tamemate_passive_saddlebags_0743")) { s_lastAdviceTime = Time.time; string text = (ModLanguage.IsEnglish ? "Saddlebags & Resources" : "Alforjas y Recursos"); string text2 = (ModLanguage.IsEnglish ? "Tamed companions autonomously generate unique world resources into their saddlebags. Aim at your companion and press Shift + E to open its inventory. Check F11 for species catalogue." : "Tus criaturas domesticadas generan recursos del mundo de forma autónoma en sus alforjas. Apunta a tu compañero y pulsa Shift + E para abrir su inventario. Consulta F11 para ver el catálogo de recursos."); AdviceFeature.Queue("tamemate_passive_saddlebags_0743", text, text2, "tamemate_guide"); } } public static void OnOpenMasteryCodex(Player player) { if (CanDeliverAdvice(player, "tamemate_masteries_codex_0745")) { s_lastAdviceTime = Time.time; string text = (ModLanguage.IsEnglish ? "Mastery Codex" : "Códice de Maestrías"); string text2 = (ModLanguage.IsEnglish ? "Ancient spirits grant you mastery paths. Press F7 to open the Mastery Codex and choose up to 2 active masteries for you and your beasts. Drag HUD medallions with Shift + Click. Check F11." : "Los espíritus antiguos te otorgan sus Maestrías rúnicas. Pulsa F7 para abrir el Códice y equipar hasta 2 sendas activas para ti y tus bestias. Arrastra los medallones del HUD con Shift + Clic. Consulta F11."); AdviceFeature.Queue("tamemate_masteries_codex_0745", text, text2, "tamemate_guide"); } } public static void OnMount(Player player, Character mount) { if (Bridge.Ready && CanDeliverAdvice(player, "tamemate_lineages_0740")) { s_lastAdviceTime = Time.time; string text = "TameMate · LinejaeserasRace"; string text2 = (ModLanguage.IsEnglish ? "Your racial taming ability now respects TameMate requirements and trophies. Its chance and food speed bonus remain racial benefits. You own creatures you tame. U opens the companion wheel; the conflicting player-passenger shortcut uses Y by default. See F11." : "Tu habilidad racial de doma respeta los requisitos y trofeos de TameMate. Conservas su probabilidad y la ventaja de alimentación. Las criaturas que domesticas te pertenecen. U abre la rueda; el atajo de transporte entre jugadores que coincidía con U usa Y por defecto. Consulta F11."); AdviceFeature.Queue("tamemate_lineages_0740", text, text2, "tamemate_guide"); } } public static void OnCompanionDamaged(Character companion) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && CanDeliverAdvice(localPlayer, "tamemate_survival_0741")) { s_lastAdviceTime = Time.time; string text = (ModLanguage.IsEnglish ? "Your companions can hold their ground" : "Tus compañeros pueden defenderse"); string text2 = (ModLanguage.IsEnglish ? "Fragile ordinary companions now receive more useful health and modest level growth. Assign health and defense points, feed them and choose their battles. Wild bonuses are softened against companions without making them invulnerable. F11 explains the changes." : "Las domas ordinarias frágiles reciben una salud más útil y crecimiento moderado por nivel. Reparte puntos de salud y defensa, aliméntalas y elige sus combates. Los bonos salvajes se moderan contra compañeros sin hacerlos invulnerables. Consulta los detalles en F11."); AdviceFeature.Queue("tamemate_survival_0741", text, text2, "tamemate_guide"); } } } public static class DeepNorthAscension { public const string KeyFrozenKingP3 = "defeated_frozenking_p3"; public const string KeyFrozenKing = "defeated_frozenking"; public const string KeyGammeltrollLord = "defeated_gammeltroll_lord"; public static Func, int> CustomAscensionHook; private static MethodInfo s_isBossDeadMethod = null; private static MethodInfo s_refreshCacheMethod = null; public static void Install(Harmony h, Assembly core) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown try { Type type = core.GetType("TameMate.SupremeTierEngine", throwOnError: true); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "ComputeBiomeAscensionLevel", new Type[1] { typeof(Biome) }, (Type[])null); if (methodInfo != null) { h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(DeepNorthAscension), "ComputeBiomeAscensionLevel_Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } s_isBossDeadMethod = AccessTools.Method(type, "IsBossDead", new Type[2] { typeof(string), typeof(string) }, (Type[])null); s_refreshCacheMethod = AccessTools.Method(type, "RefreshBiomeAscensionCache", Type.EmptyTypes, (Type[])null); Debug.Log((object)"[TameMate 0.7.53] Deep North Dynamic Ascension active (FrozenKing, GammeltrollLord; max level 3)."); } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate] DeepNorthAscension install error: " + ex.Message)); } } public static bool IsBossDead(string key, string passiveName) { if (s_isBossDeadMethod != null) { try { return (bool)s_isBossDeadMethod.Invoke(null, new object[2] { key, passiveName }); } catch { } } if ((Object)(object)ZoneSystem.instance == (Object)null) { return false; } if (ZoneSystem.instance.GetGlobalKey(key)) { return true; } if (!string.IsNullOrEmpty(key) && ZoneSystem.instance.GetGlobalKey(key.Replace("_", ""))) { return true; } if (!string.IsNullOrEmpty(passiveName)) { try { Type type = AccessTools.TypeByName("TameMate.BossPassiveEngine"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "IsBossDefeatedInWorld", new Type[1] { typeof(string) }, (Type[])null); if (methodInfo != null) { return (bool)methodInfo.Invoke(null, new object[1] { passiveName }); } } } catch { } } return false; } public static int ComputeDeepNorthAscension(Func isDeadFunc = null) { Func func = isDeadFunc ?? new Func(IsBossDead); int num = 0; if (func("defeated_frozenking_p3", "FrozenKing") || func("defeated_frozenking", "FrozenKing")) { num++; } if (func("defeated_gammeltroll_lord", "DeepNorth")) { num++; } if (CustomAscensionHook != null) { try { num += CustomAscensionHook(func); } catch { } } return Math.Min(3, num); } public static void ForceRefreshCache() { try { if (s_refreshCacheMethod != null) { s_refreshCacheMethod.Invoke(null, null); } } catch { } } public static void ComputeBiomeAscensionLevel_Postfix(Biome biome, ref int __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 if ((int)biome == 64) { __result = ComputeDeepNorthAscension(); } } } public enum CodexCategory { Combat, Creatures, World, TameMate, RpgProgression, ModCompatibility } public static class DifficultyCodexGui { public enum MessageType { Info, Success, Warning, Error } internal static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.DifficultyCodex"); private static GameObject s_uiHostObject = null; private static DifficultyCodexComponent s_component = null; private static Assembly s_coreAssembly = null; private static bool s_isOpen = false; private static CodexCategory s_currentCategory = CodexCategory.Combat; private static WorldDifficultyProfile s_stagedProfile = null; private static ResolvedDifficultyState s_resolvedState = null; private static Vector2 s_scrollPosition = Vector2.zero; private static string s_statusMessage = string.Empty; private static MessageType s_statusType = MessageType.Info; private static bool s_stylesInitialized = false; private static GUIStyle s_windowStyle; private static GUIStyle s_titleStyle; private static GUIStyle s_subtitleStyle; private static GUIStyle s_sectionHeaderStyle; private static GUIStyle s_labelStyle; private static GUIStyle s_valueStyle; private static GUIStyle s_buttonStyle; private static GUIStyle s_activeButtonStyle; private static GUIStyle s_tabStyle; private static GUIStyle s_activeTabStyle; private static GUIStyle s_statusBannerStyle; private static readonly Dictionary s_biomeDisplayNames = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Meadows", "Praderas" }, { "BlackForest", "Bosque Negro" }, { "Swamp", "Pantano" }, { "Mountain", "Montañas" }, { "Plains", "Llanuras" }, { "Mistlands", "Tierras Brumosas" }, { "Ashlands", "Tierras Cenicientas" }, { "DeepNorth", "Norte Profundo" }, { "Ocean", "Océano" } }; private static Font s_safeFont = null; public static bool IsOpen { get { return s_isOpen; } set { if (s_isOpen != value) { if (value) { Open(); } else { Close(); } } } } public static bool IsOperational => DifficultyCodexPatches.IsFullyInstalled; public static CodexCategory CurrentCategory { get { return s_currentCategory; } set { s_currentCategory = value; } } public static WorldDifficultyProfile StagedProfile => s_stagedProfile; public static ResolvedDifficultyState ResolvedState => s_resolvedState; public static string StatusMessage => s_statusMessage; public static MessageType StatusType => s_statusType; public static void Init(Assembly coreAssembly, ManualLogSource logger) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown s_coreAssembly = coreAssembly; try { if ((Object)(object)s_uiHostObject == (Object)null) { s_uiHostObject = new GameObject("_TameMate_DifficultyCodexUI"); Object.DontDestroyOnLoad((Object)(object)s_uiHostObject); s_component = s_uiHostObject.AddComponent(); if (logger != null) { logger.LogInfo((object)"[DifficultyCodexGui] UI host initialized successfully."); } } } catch (Exception ex) { if (logger != null) { logger.LogError((object)("[DifficultyCodexGui] UI host initialization failed: " + ex.Message)); } } } public static void Open() { if (!IsOperational) { if (Log != null) { Log.LogWarning((object)"[DifficultyCodexGui] Open cancelled: subsystem is not fully operational."); } return; } s_isOpen = true; ReloadStagedProfileFromActiveWorld(); s_statusMessage = "Listo. Los cambios preparados se aplicarán solo al pulsar 'Aplicar Cambios'."; s_statusType = MessageType.Info; if (Log != null) { Log.LogInfo((object)"[DifficultyCodexGui] Códice de dificultad F11 abierto."); } } public static void OpenWithPreset(DifficultyPreset preset) { if (!IsOperational) { if (Log != null) { Log.LogWarning((object)"[DifficultyCodexGui] OpenWithPreset cancelled: subsystem is not fully operational."); } return; } s_isOpen = true; ReloadStagedProfileFromActiveWorld(); StagePreset(preset); s_currentCategory = CodexCategory.Combat; s_statusMessage = $"Preset base cambiado a {preset}. Personaliza los valores y pulsa 'Aplicar Cambios'."; s_statusType = MessageType.Info; if (Log != null) { Log.LogInfo((object)$"[DifficultyCodexGui] Códice de dificultad F11 abierto con preset {preset}."); } } public static void Close() { s_isOpen = false; s_stagedProfile = null; s_resolvedState = null; if (Log != null) { Log.LogInfo((object)"[DifficultyCodexGui] Códice de dificultad F11 cerrado."); } } public static void Toggle() { if (s_isOpen) { Close(); } else { Open(); } } public static void ReloadStagedProfileFromActiveWorld() { string activeWorldId = DifficultyCoordinator.GetActiveWorldId(); WorldDifficultyProfile worldDifficultyProfile = DifficultyCoordinator.LoadWorldProfile(activeWorldId); s_stagedProfile = ((worldDifficultyProfile != null) ? worldDifficultyProfile.Clone() : new WorldDifficultyProfile(activeWorldId, activeWorldId, DifficultyPreset.Normal)); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StagePreset(DifficultyPreset newPreset) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.BasePreset = newPreset; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); s_statusMessage = $"Preset base cambiado a {newPreset}. Las personalizaciones existentes se conservan."; s_statusType = MessageType.Info; } public static void StagePlayerDamage(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.PlayerDamageOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEnemyDamage(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.EnemyDamageOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEnemySpeedSize(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.EnemySpeedSizeOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.5f, 2f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEnemyBaseHealth(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.EnemyBaseHealthOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.5f, 3f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageStarHealthMultiplier(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.StarHealthMultiplierOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.2f, 2.5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageStarDamageMultiplier(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.StarDamageMultiplierOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 1.5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageStaminaRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.StaminaRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.25f, 2f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageMoveStaminaRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.MoveStaminaRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.25f, 2f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageStaminaRegenRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.StaminaRegenRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.25f, 2f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageResourceRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.25) * 0.25f; s_stagedProfile.ResourceRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.25f, 5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageRaidsEnabled(bool enabled) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.RaidsEnabledOverride = enabled; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageRaidRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.5) * 0.5f; s_stagedProfile.RaidRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.5f, 2f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StagePortalMode(PortalMode mode) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.PortalModeOverride = mode; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageDeathPenalty(DeathPenaltyMode mode) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.DeathPenaltyOverride = mode; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageFreeBuild(bool free) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.FreeBuildOverride = free; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageFreeCraft(bool free) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.FreeCraftOverride = free; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageStarFrequency(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.StarCreatureRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.05f, 0.9f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageBiomeStarCap(string biome, int starCap) { if (!string.IsNullOrEmpty(biome)) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } int value = Mathf.Clamp(starCap, 0, 16); s_stagedProfile.BiomeStarCapOverrides[biome] = value; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } } public static void StageEpicMmoExpRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.EpicMmoExpRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicMmoMaxLevel(int maxLevel) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.EpicMmoMaxLevelOverride = Mathf.Clamp(maxLevel, 10, 200); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicMmoFreePoints(int freePoints) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.EpicMmoFreePointsOverride = Mathf.Clamp(freePoints, 1, 20); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicMmoLowDamageLevel(bool enabled) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } s_stagedProfile.EpicMmoLowDamageLevelOverride = enabled; s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicMmoPhysicDamage(float dmg) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)dmg / 0.05) * 0.05f; s_stagedProfile.EpicMmoPhysicDamageOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 3f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicMmoPhysicArmor(float armor) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)armor / 0.05) * 0.05f; s_stagedProfile.EpicMmoPhysicArmorOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.05f, 2f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicMmoHealthPerPoint(float hp) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)hp / 0.1) * 0.1f; s_stagedProfile.EpicMmoHealthPerPointOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 10f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicLootDropRate(float rate) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)rate / 0.05) * 0.05f; s_stagedProfile.EpicLootDropRateOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.1f, 5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicLootStarScaling(float scaling) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)scaling / 0.05) * 0.05f; s_stagedProfile.EpicLootStarScalingOverride = Mathf.Clamp((float)Math.Round(num, 2), 0f, 3f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicLootItemRatio(float ratio) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)ratio / 0.05) * 0.05f; s_stagedProfile.EpicLootItemRatioOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.05f, 1f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static void StageEpicLootSetChance(float chance) { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } float num = (float)Math.Round((double)chance / 0.01) * 0.01f; s_stagedProfile.EpicLootSetChanceOverride = Mathf.Clamp((float)Math.Round(num, 2), 0.01f, 0.5f); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); } public static string GetBiomeDisplayName(string internalBiomeName) { if (string.IsNullOrEmpty(internalBiomeName)) { return string.Empty; } if (s_biomeDisplayNames.TryGetValue(internalBiomeName.Trim(), out var value)) { return value; } return internalBiomeName; } public static int GetGlobalPresetCeiling(DifficultyPreset preset) { return preset switch { DifficultyPreset.Facil => 3, DifficultyPreset.Normal => 5, DifficultyPreset.Dificil => 8, DifficultyPreset.Supreme => 10, _ => 5, }; } public static float StepDown(float val, float step, float min) { float num = (float)Math.Round(val / step, 4); float num2 = (float)Math.Floor(num - 0.001f); float num3 = num2 * step; if (num3 < min) { num3 = min; } return (float)Math.Round(num3, 2); } public static float StepUp(float val, float step, float max) { float num = (float)Math.Round(val / step, 4); float num2 = (float)Math.Ceiling(num + 0.001f); float num3 = num2 * step; if (num3 > max) { num3 = max; } return (float)Math.Round(num3, 2); } public static bool ClearStagedOverride(string settingName) { if (s_stagedProfile == null) { return false; } bool result = s_stagedProfile.ClearOverride(settingName); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); s_statusMessage = $"Ajuste '{settingName}' restablecido al valor del preset."; s_statusType = MessageType.Info; return result; } public static void ClearAllStagedOverrides() { if (s_stagedProfile != null) { s_stagedProfile.ClearAllOverrides(); s_resolvedState = DifficultyCoordinator.ResolveState(s_stagedProfile); s_statusMessage = "Todas las personalizaciones fueron restablecidas a los valores del preset base."; s_statusType = MessageType.Info; } } public static CoordinatorResult ApplyStagedChanges() { if (!IsOperational) { s_statusMessage = "Error de subsistema: El configurador avanzado está deshabilitado por fallo de inicialización."; s_statusType = MessageType.Error; return CoordinatorResult.Fail(CoordinatorStatus.InvalidRequest, s_statusMessage, null); } if (s_stagedProfile == null) { s_statusMessage = "No hay perfil preparado para aplicar."; s_statusType = MessageType.Error; return CoordinatorResult.Fail(CoordinatorStatus.InvalidRequest, s_statusMessage, null); } if (!VanillaWorldAdapter.HasAuthority()) { s_statusMessage = "Error de autorización: Solo el servidor o anfitrión puede aplicar cambios de dificultad."; s_statusType = MessageType.Error; return CoordinatorResult.Fail(CoordinatorStatus.Unauthorized, s_statusMessage, s_resolvedState); } CoordinatorResult coordinatorResult = DifficultyCoordinator.ApplyConfiguration(s_stagedProfile); if (coordinatorResult.Success) { s_statusMessage = "✔ Configuración aplicada y verificada exitosamente en el mundo y adaptadores."; s_statusType = MessageType.Success; SyncTameMateConfigPreset(s_stagedProfile.BasePreset); NotifyPlayerIfPresent(s_stagedProfile.BasePreset); ReloadStagedProfileFromActiveWorld(); } else { s_statusMessage = $"✖ Error al aplicar: {coordinatorResult.Message}"; s_statusType = ((coordinatorResult.Status == CoordinatorStatus.PartialFailureRecovered) ? MessageType.Warning : MessageType.Error); } return coordinatorResult; } private static void NotifyPlayerIfPresent(DifficultyPreset preset) { try { Type type = AccessTools.TypeByName("Player") ?? AccessTools.TypeByName("Player, assembly_valheim"); if (type == null) { return; } FieldInfo fieldInfo = AccessTools.Field(type, "m_localPlayer"); object obj = ((fieldInfo != null) ? fieldInfo.GetValue(null) : null); if (obj != null) { MethodInfo methodInfo = AccessTools.Method(obj.GetType(), "Message", new Type[2] { typeof(MessageType), typeof(string) }, (Type[])null); if (methodInfo != null) { string text = $"\ud83d\udee1 TameMate: Dificultad '{preset}' aplicada con éxito."; methodInfo.Invoke(obj, new object[2] { (object)(MessageType)2, text }); } } } catch { } } public static void CancelStagedChanges() { ReloadStagedProfileFromActiveWorld(); s_statusMessage = "Cambios preparados descartados. Valores restaurados desde el perfil del mundo."; s_statusType = MessageType.Info; Close(); } public static void SyncTameMateConfigPreset(DifficultyPreset preset) { try { if (s_coreAssembly == null) { return; } Type type = s_coreAssembly.GetType("TameMate.TameMateConfig"); if (type == null) { return; } FieldInfo field = type.GetField("DifficultyPreset", BindingFlags.Static | BindingFlags.Public); if (field == null) { return; } object value = field.GetValue(null); if (value == null) { return; } Type type2 = s_coreAssembly.GetType("TameMate.GameDifficulty"); if (type2 == null) { return; } object value2 = Enum.ToObject(type2, (int)preset); PropertyInfo property = value.GetType().GetProperty("Value"); if (!(property != null)) { return; } DifficultyCodexPatches.SuppressLegacyApply = true; try { property.SetValue(value, value2, null); } finally { DifficultyCodexPatches.SuppressLegacyApply = false; } } catch (Exception ex) { if (Log != null) { Log.LogWarning((object)("[DifficultyCodexGui] SyncTameMateConfigPreset warning: " + ex.Message)); } } } public static void Draw() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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_002e: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) if (s_isOpen) { EnsureStyles(); Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; GUI.depth = -200; Color color = GUI.color; Color backgroundColor = GUI.backgroundColor; GUI.color = new Color(0f, 0f, 0f, 0.75f); GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)Texture2D.whiteTexture); GUI.color = color; float num = Mathf.Min(820f, (float)Screen.width - 40f); float num2 = Mathf.Min(640f, (float)Screen.height - 40f); float num3 = ((float)Screen.width - num) * 0.5f; float num4 = ((float)Screen.height - num2) * 0.5f; GUI.backgroundColor = new Color(0.08f, 0.1f, 0.12f, 0.98f); Rect val = default(Rect); ((Rect)(ref val))..ctor(num3, num4, num, num2); GUI.Box(val, GUIContent.none, s_windowStyle); GUILayout.BeginArea(new Rect(num3 + 14f, num4 + 14f, num - 28f, num2 - 28f)); DrawHeader(); GUILayout.Space(6f); DrawCategoryTabs(); GUILayout.Space(6f); s_scrollPosition = GUILayout.BeginScrollView(s_scrollPosition, false, true, (GUILayoutOption[])(object)new GUILayoutOption[0]); switch (s_currentCategory) { case CodexCategory.Combat: DrawCombatCategory(); break; case CodexCategory.Creatures: DrawCreaturesCategory(); break; case CodexCategory.World: DrawWorldCategory(); break; case CodexCategory.TameMate: DrawTameMateCategory(); break; case CodexCategory.RpgProgression: DrawRpgProgressionCategory(); break; case CodexCategory.ModCompatibility: DrawModCompatibilityCategory(); break; } GUILayout.EndScrollView(); GUILayout.Space(6f); DrawStatusBanner(); GUILayout.Space(6f); DrawFooterActions(); GUILayout.EndArea(); GUI.backgroundColor = backgroundColor; } } private static void DrawHeader() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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) GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("\ud83d\udcdc CÓDICE DE DIFICULTAD Y EXPERIENCIA v0.8.0", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.FlexibleSpace(); if (VanillaWorldAdapter.HasAuthority()) { GUI.color = new Color(0.35f, 1f, 0.55f); GUILayout.Label("[\ud83d\udc51 Servidor / Host - Edición Habilitada]", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } else { GUI.color = new Color(1f, 0.65f, 0.35f); GUILayout.Label("[\ud83d\udc41\ufe0f Cliente Remoto - Solo Lectura]", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUI.color = Color.white; GUILayout.Space(10f); if (GUILayout.Button("✕", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(28f), GUILayout.Height(24f) })) { Close(); } GUILayout.EndHorizontal(); } private static void DrawCategoryTabs() { //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_0083: 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) GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); string[] array = new string[6] { "⚔\ufe0f Combate", "\ud83d\udc3a Criaturas y Estrellas", "\ud83c\udf0d Mundo y Supervivencia", "\ud83d\udee1\ufe0f TameMate y Estado", "✨ RPG y Progresión", "\ud83e\udde9 Compatibilidad" }; for (int i = 0; i < array.Length; i++) { CodexCategory codexCategory = (CodexCategory)i; bool flag = s_currentCategory == codexCategory; GUI.backgroundColor = (flag ? new Color(0.9f, 0.65f, 0.15f) : new Color(0.18f, 0.22f, 0.25f)); GUIStyle val = (flag ? s_activeTabStyle : s_tabStyle); if (GUILayout.Button(array[i], val, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(28f) })) { s_currentCategory = codexCategory; } } GUI.backgroundColor = Color.white; GUILayout.EndHorizontal(); } private static void DrawCombatCategory() { //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_04c4: Unknown result type (might be due to invalid IL or missing references) //IL_04fd: Unknown result type (might be due to invalid IL or missing references) if (s_stagedProfile == null || s_resolvedState == null) { ReloadStagedProfileFromActiveWorld(); } bool enabled = VanillaWorldAdapter.HasAuthority(); GUILayout.Label("Categoría: Combate y Escalado de Daño", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Preset Base:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) }); DifficultyPreset[] array = new DifficultyPreset[4] { DifficultyPreset.Facil, DifficultyPreset.Normal, DifficultyPreset.Dificil, DifficultyPreset.Supreme }; DifficultyPreset[] array2 = array; foreach (DifficultyPreset difficultyPreset in array2) { bool flag = s_stagedProfile.BasePreset == difficultyPreset; GUI.backgroundColor = (flag ? new Color(0.95f, 0.7f, 0.15f) : new Color(0.16f, 0.2f, 0.24f)); GUIStyle val = (flag ? s_activeButtonStyle : s_buttonStyle); GUI.enabled = enabled; if (GUILayout.Button(difficultyPreset.ToString(), val, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(25f) })) { StagePreset(difficultyPreset); } GUI.enabled = true; } GUI.backgroundColor = Color.white; GUILayout.EndHorizontal(); GUILayout.Space(10f); DrawSliderRow("Daño del Jugador:", "Multiplicador de daño saliente infligido por el jugador a criaturas y jefes.", s_resolvedState.PlayerDamage.EffectiveValue, 0.1f, 3f, 0.05f, "{0:F2}x", s_resolvedState.PlayerDamage.Origin, "Valheim Vanilla (GlobalKeys.PlayerDamage)", enabled, delegate(float rate) { StagePlayerDamage(rate); }, delegate { ClearStagedOverride("PlayerDamage"); }); GUILayout.Space(6f); DrawSliderRow("Daño de Enemigos:", "Multiplicador de daño entrante recibido de criaturas y jefes.", s_resolvedState.EnemyDamage.EffectiveValue, 0.1f, 5f, 0.05f, "{0:F2}x", s_resolvedState.EnemyDamage.Origin, "Valheim Vanilla (GlobalKeys.EnemyDamage)", enabled, delegate(float rate) { StageEnemyDamage(rate); }, delegate { ClearStagedOverride("EnemyDamage"); }); GUILayout.Space(6f); DrawSliderRow("Velocidad y Tamaño Nativo:", "Modificador nativo de Valheim (GlobalKeys.EnemySpeedSize). Escala conjuntamente la velocidad de marcha y el tamaño exterior de criaturas no-jugador.", s_resolvedState.EnemySpeedSize.EffectiveValue, 0.5f, 2f, 0.05f, "{0:F2}x", s_resolvedState.EnemySpeedSize.Origin, "Valheim Vanilla (GlobalKeys.EnemySpeedSize)", enabled, delegate(float rate) { StageEnemySpeedSize(rate); }, delegate { ClearStagedOverride("EnemySpeedSize"); }); GUILayout.Space(12f); GUILayout.Label("Escalado Avanzado de Criaturas y Salud (StarLevelSystem):", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); if (StarLevelSystemAdapter.IsConfigFileAvailable) { DrawSliderRow("Salud Base de Enemigos:", "Multiplicador aplicado a la salud base (nivel 1 / 0★) de todas las criaturas antes del escalado por estrellas.", s_resolvedState.EnemyBaseHealth.EffectiveValue, 0.5f, 3f, 0.05f, "{0:F2}x", s_resolvedState.EnemyBaseHealth.Origin, "StarLevelSystem (BaseHealth)", enabled, delegate(float rate) { StageEnemyBaseHealth(rate); }, delegate { ClearStagedOverride("EnemyBaseHealth"); }); GUILayout.Space(6f); DrawSliderRow("Escalado Salud por Estrella:", "Salud adicional por cada estrella por encima del nivel 1 (Vanilla equivale a +100% / 1.00x por estrella).", s_resolvedState.StarHealthMultiplier.EffectiveValue, 0.2f, 2.5f, 0.05f, "{0:F2}x", s_resolvedState.StarHealthMultiplier.Origin, "StarLevelSystem (HealthPerLevel)", enabled, delegate(float rate) { StageStarHealthMultiplier(rate); }, delegate { ClearStagedOverride("StarHealthMultiplier"); }); GUILayout.Space(6f); DrawSliderRow("Escalado Daño por Estrella:", "Daño adicional por cada estrella por encima del nivel 1 (Vanilla equivale a +50% / 0.50x por estrella).", s_resolvedState.StarDamageMultiplier.EffectiveValue, 0.1f, 1.5f, 0.05f, "{0:F2}x", s_resolvedState.StarDamageMultiplier.Origin, "StarLevelSystem (DamagePerLevel)", enabled, delegate(float rate) { StageStarDamageMultiplier(rate); }, delegate { ClearStagedOverride("StarDamageMultiplier"); }); } else { GUI.color = new Color(0.85f, 0.85f, 0.85f); GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("⚪ StarLevelSystem no detectado. El escalado de criaturas utiliza las fórmulas fijas de Valheim (+100% HP y +50% Daño por estrella).", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); GUI.color = Color.white; } GUILayout.Space(12f); GUILayout.Label("Estamina y resistencia física:", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); DrawSliderRow("Consumo en Ataque:", "Modificador nativo de Valheim (GlobalKeys.StaminaRate). Multiplica el coste de estamina de ataques con armas y herramientas de combate.", s_resolvedState.StaminaRate.EffectiveValue, 0.25f, 2f, 0.05f, "{0:F2}x", s_resolvedState.StaminaRate.Origin, "Valheim Vanilla (GlobalKeys.StaminaRate)", enabled, delegate(float rate) { StageStaminaRate(rate); }, delegate { ClearStagedOverride("StaminaRate"); }); GUILayout.Space(6f); DrawSliderRow("Consumo en Movimiento:", "Modificador nativo de Valheim (GlobalKeys.MoveStaminaRate). Multiplica el coste de estamina al correr, saltar y nadar.", s_resolvedState.MoveStaminaRate.EffectiveValue, 0.25f, 2f, 0.05f, "{0:F2}x", s_resolvedState.MoveStaminaRate.Origin, "Valheim Vanilla (GlobalKeys.MoveStaminaRate)", enabled, delegate(float rate) { StageMoveStaminaRate(rate); }, delegate { ClearStagedOverride("MoveStaminaRate"); }); GUILayout.Space(6f); DrawSliderRow("Regeneración de Estamina:", "Modificador nativo de Valheim (GlobalKeys.StaminaRegenRate). Multiplica la tasa de recuperación de estamina del jugador.", s_resolvedState.StaminaRegenRate.EffectiveValue, 0.25f, 2f, 0.05f, "{0:F2}x", s_resolvedState.StaminaRegenRate.Origin, "Valheim Vanilla (GlobalKeys.StaminaRegenRate)", enabled, delegate(float rate) { StageStaminaRegenRate(rate); }, delegate { ClearStagedOverride("StaminaRegenRate"); }); } private static void DrawCreaturesCategory() { //IL_0080: 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_009f: Unknown result type (might be due to invalid IL or missing references) if (s_stagedProfile == null || s_resolvedState == null) { ReloadStagedProfileFromActiveWorld(); } bool enabled = VanillaWorldAdapter.HasAuthority(); bool isConfigFileAvailable = StarLevelSystemAdapter.IsConfigFileAvailable; GUILayout.Label("Categoría: Criaturas, Estrellas y Biomas", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); if (isConfigFileAvailable) { GUI.color = new Color(0.35f, 1f, 0.55f); GUILayout.Label("\ud83d\udfe2 StarLevelSystem detectado y activo. Los topes de estrellas por bioma son gobernados en tiempo real.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } else { GUI.color = new Color(0.85f, 0.85f, 0.85f); GUILayout.Label("⚪ StarLevelSystem no detectado. Los límites de estrellas permanecerán en los valores nativos de Valheim.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUI.color = Color.white; int globalPresetCeiling = GetGlobalPresetCeiling(s_stagedProfile.BasePreset); GUILayout.Space(4f); GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Límites Globales de Estrellas por Preset en TameMate:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("• Fácil: 3★ máx | Normal: 5★ máx | Difícil: 8★ máx | Supreme: 10★ máx", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"• Preset Base Activo: {s_stagedProfile.BasePreset} — Techo global efectivo del motor: {globalPresetCeiling}★", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("• Distribución Progresiva Activa: Cada estrella superior es exponencialmente más rara que la anterior (P(0★) > P(1★) > P(2★) > ...).", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); GUILayout.Space(6f); if (isConfigFileAvailable && s_resolvedState.StarCreatureRate != null) { DrawSliderRow("Frecuencia Criaturas con Estrellas:", "Probabilidad base de que una criatura aparezca con estrellas al spawnear (Fácil 10%, Normal 15%, Difícil 25%, Supreme 35%).", s_resolvedState.StarCreatureRate.EffectiveValue, 0.05f, 0.5f, 0.05f, "{0:P0}", s_resolvedState.StarCreatureRate.Origin, "StarLevelSystem (DefaultLevelupGenerators)", enabled, delegate(float val) { StageStarFrequency(val); }, delegate { ClearStagedOverride("StarCreatureRate"); }); GUILayout.Space(8f); } GUILayout.Label("⚠\ufe0f Nota de motor: Los nuevos límites de estrellas aplicarán a las criaturas que aparezcan a partir del momento de aplicación. Las criaturas ya instanciadas conservan su nivel.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(8f); if (!isConfigFileAvailable) { return; } foreach (KeyValuePair> biomeStarCap in s_resolvedState.BiomeStarCaps) { string key = biomeStarCap.Key; ResolvedSetting value = biomeStarCap.Value; string biomeDisplayName = GetBiomeDisplayName(key); int effectiveValue = value.EffectiveValue; int effectiveGameCap = Math.Min(effectiveValue, globalPresetCeiling); DrawBiomeStarCapRow(key, biomeDisplayName, effectiveValue, effectiveGameCap, globalPresetCeiling, value.Origin, enabled); GUILayout.Space(4f); } } private static void DrawWorldCategory() { //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: 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_0355: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_04f4: Unknown result type (might be due to invalid IL or missing references) //IL_055c: Unknown result type (might be due to invalid IL or missing references) //IL_0603: Unknown result type (might be due to invalid IL or missing references) //IL_05ed: Unknown result type (might be due to invalid IL or missing references) //IL_0657: Unknown result type (might be due to invalid IL or missing references) //IL_074f: Unknown result type (might be due to invalid IL or missing references) //IL_0739: Unknown result type (might be due to invalid IL or missing references) //IL_07a3: Unknown result type (might be due to invalid IL or missing references) if (s_stagedProfile == null || s_resolvedState == null) { ReloadStagedProfileFromActiveWorld(); } bool flag = VanillaWorldAdapter.HasAuthority(); GUILayout.Label("Categoría: Mundo, Incursiones y Supervivencia", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Incursiones a Base:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); bool effectiveValue = s_resolvedState.RaidsEnabled.EffectiveValue; float effectiveValue2 = s_resolvedState.RaidRate.EffectiveValue; string text = (effectiveValue ? string.Format(CultureInfo.InvariantCulture, "\ud83d\udfe2 Habilitadas ({0:F1}x)", effectiveValue2) : "\ud83d\udd34 Desactivadas (0.0x)"); GUI.backgroundColor = (effectiveValue ? new Color(0.2f, 0.6f, 0.25f) : new Color(0.6f, 0.2f, 0.2f)); GUI.enabled = flag; if (GUILayout.Button(text, s_activeButtonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(180f), GUILayout.Height(24f) })) { StageRaidsEnabled(!effectiveValue); } GUI.enabled = true; GUI.backgroundColor = Color.white; DrawOriginTag(s_resolvedState.RaidsEnabled.Origin); if (s_resolvedState.RaidsEnabled.Origin == ValueOrigin.CustomOverride && flag && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride("Raids"); } GUILayout.EndHorizontal(); DrawSliderRow("Frecuencia Incursiones:", effectiveValue ? "Multiplicador de intervalo y probabilidad de asedios nativos." : "Frecuencia memorizada; se aplicará al reactivar las incursiones.", effectiveValue2, 0.5f, 2f, 0.5f, "{0:F1}x", s_resolvedState.RaidRate.Origin, "Valheim Vanilla (GlobalKeys.EventRate)", flag && effectiveValue, delegate(float val) { StageRaidRate(val); }, delegate { ClearStagedOverride("RaidRate"); }); GUILayout.EndVertical(); GUILayout.Space(6f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Restricción Portales:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); PortalMode effectiveValue3 = s_resolvedState.PortalMode.EffectiveValue; DrawPortalOptionButton("Original", PortalMode.Normal, effectiveValue3, flag); DrawPortalOptionButton("Metales", PortalMode.TeleportAll, effectiveValue3, flag); DrawPortalOptionButton("Sin Portales", PortalMode.NoPortals, effectiveValue3, flag); DrawPortalOptionButton("Bloq. Jefes", PortalMode.NoBossPortals, effectiveValue3, flag); DrawOriginTag(s_resolvedState.PortalMode.Origin); if (s_resolvedState.PortalMode.Origin == ValueOrigin.CustomOverride && flag && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride("Portals"); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(20f); GUI.color = new Color(0.72f, 0.72f, 0.72f); GUILayout.Label(effectiveValue3 switch { PortalMode.TeleportAll => "Permite transportar metales, minerales y cualquier objeto a través de portales.", PortalMode.NoPortals => "Portales completamente desactivados en el mundo (estilo inmersivo).", PortalMode.NoBossPortals => "Portales operativos normalmente, pero bloqueados durante asedios o peleas de jefes.", _ => "Restricciones vanilla estándar: metales y minerales no pueden atravesar portales.", }, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.Space(6f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Penalización Muerte:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); DeathPenaltyMode effectiveValue4 = s_resolvedState.DeathPenalty.EffectiveValue; DrawDeathOptionButton("Casual", DeathPenaltyMode.Casual, effectiveValue4, flag); DrawDeathOptionButton("Eq. Seguro", DeathPenaltyMode.VeryEasy, effectiveValue4, flag); DrawDeathOptionButton("Estándar", DeathPenaltyMode.Normal, effectiveValue4, flag); DrawDeathOptionButton("Severa", DeathPenaltyMode.Hard, effectiveValue4, flag); DrawDeathOptionButton("Hardcore", DeathPenaltyMode.Hardcore, effectiveValue4, flag); DrawOriginTag(s_resolvedState.DeathPenalty.Origin); if (s_resolvedState.DeathPenalty.Origin == ValueOrigin.CustomOverride && flag && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride("DeathPenalty"); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(20f); GUI.color = new Color(0.72f, 0.72f, 0.72f); GUILayout.Label(effectiveValue4 switch { DeathPenaltyMode.Casual => "Conserva todo el inventario al morir. Pérdida de habilidades: 0%.", DeathPenaltyMode.VeryEasy => "Conserva el equipo equipado puesto. Resto en tumba. Pérdida hab.: 1.25%.", DeathPenaltyMode.Hard => "Inventario a la tumba. Pérdida severa de habilidades: 10% (x2 vanilla).", DeathPenaltyMode.Hardcore => "Destrucción total de objetos (sin tumba) y reseteo de todas las habilidades a 0.", _ => "Estándar vanilla: todo el inventario va a la tumba. Pérdida de habilidades: 5%.", }, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.Space(6f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Construcción Libre:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); bool effectiveValue5 = s_resolvedState.FreeBuild.EffectiveValue; string text2 = (effectiveValue5 ? "\ud83d\udfe2 Gratuita (Sin coste de piezas)" : "⚪ Costos normales"); GUI.backgroundColor = (effectiveValue5 ? new Color(0.2f, 0.6f, 0.25f) : new Color(0.35f, 0.35f, 0.35f)); GUI.enabled = flag; if (GUILayout.Button(text2, s_activeButtonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(220f), GUILayout.Height(22f) })) { StageFreeBuild(!effectiveValue5); } GUI.enabled = true; GUI.backgroundColor = Color.white; DrawOriginTag(s_resolvedState.FreeBuild.Origin); if (s_resolvedState.FreeBuild.Origin == ValueOrigin.CustomOverride && flag && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride("FreeBuild"); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Fabricación Libre:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); bool effectiveValue6 = s_resolvedState.FreeCraft.EffectiveValue; string text3 = (effectiveValue6 ? "\ud83d\udfe2 Gratuita (Sin coste de recetas)" : "⚪ Costos normales"); GUI.backgroundColor = (effectiveValue6 ? new Color(0.2f, 0.6f, 0.25f) : new Color(0.35f, 0.35f, 0.35f)); GUI.enabled = flag; if (GUILayout.Button(text3, s_activeButtonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(220f), GUILayout.Height(22f) })) { StageFreeCraft(!effectiveValue6); } GUI.enabled = true; GUI.backgroundColor = Color.white; DrawOriginTag(s_resolvedState.FreeCraft.Origin); if (s_resolvedState.FreeCraft.Origin == ValueOrigin.CustomOverride && flag && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride("FreeCraft"); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.Space(6f); DrawSliderRow("Multiplicador Recursos:", "Tasa global de recolección, drop y recompensas en el mundo.", s_resolvedState.ResourceRate.EffectiveValue, 0.25f, 5f, 0.25f, "{0:F2}x", s_resolvedState.ResourceRate.Origin, "Valheim Vanilla (GlobalKeys.ResourceRate)", flag, delegate(float val) { StageResourceRate(val); }, delegate { ClearStagedOverride("Resources"); }); } private static void DrawPortalOptionButton(string label, PortalMode mode, PortalMode current, bool hasAuth) { //IL_002d: 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_0082: Unknown result type (might be due to invalid IL or missing references) bool flag = current == mode; GUI.backgroundColor = (flag ? new Color(0.2f, 0.65f, 0.3f) : new Color(0.3f, 0.3f, 0.3f)); GUI.enabled = hasAuth; if (GUILayout.Button(label, flag ? s_activeButtonStyle : s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(88f), GUILayout.Height(22f) })) { StagePortalMode(mode); } GUI.enabled = true; GUI.backgroundColor = Color.white; } private static void DrawDeathOptionButton(string label, DeathPenaltyMode mode, DeathPenaltyMode current, bool hasAuth) { //IL_002d: 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_0082: Unknown result type (might be due to invalid IL or missing references) bool flag = current == mode; GUI.backgroundColor = (flag ? new Color(0.2f, 0.65f, 0.3f) : new Color(0.3f, 0.3f, 0.3f)); GUI.enabled = hasAuth; if (GUILayout.Button(label, flag ? s_activeButtonStyle : s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(72f), GUILayout.Height(22f) })) { StageDeathPenalty(mode); } GUI.enabled = true; GUI.backgroundColor = Color.white; } private static void DrawTameMateCategory() { if (s_stagedProfile == null) { ReloadStagedProfileFromActiveWorld(); } GUILayout.Label("Categoría: Estado de TameMate y Persistencia", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); GUILayout.Label($"Mundo Activo: {s_stagedProfile.WorldName} (ID: {s_stagedProfile.WorldId})", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"Preset Activo: {s_stagedProfile.BasePreset}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(string.Format("Última Actualización UTC: {0}", s_stagedProfile.LastModifiedUtc.ToString("yyyy-MM-dd HH:mm:ss")), s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"Archivo de Guardado Sidecar: world_{s_stagedProfile.WorldId}.json", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(8f); GUILayout.Label("Arquitectura de No Destructividad:", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("• Cero modificaciones automáticas al cargar el juego o abrir el códice.\n• Persistencia en archivo JSON aislado sin alterar archivos de guardado binarios de Valheim (.db / .fwl).\n• Modificación de LevelSettings.yaml con preservación absoluta de comentarios y claves externas.\n• Detección criptográfica SHA-256 de modificaciones externas antes de aplicar escrituras.\n• Reversión atómica automática en caso de fallos parciales en cualquiera de los adaptadores.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } private static void DrawRpgProgressionCategory() { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_071c: Unknown result type (might be due to invalid IL or missing references) //IL_0721: Unknown result type (might be due to invalid IL or missing references) //IL_0737: Unknown result type (might be due to invalid IL or missing references) //IL_0760: Unknown result type (might be due to invalid IL or missing references) //IL_077f: Unknown result type (might be due to invalid IL or missing references) //IL_07ad: 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_05b2: Unknown result type (might be due to invalid IL or missing references) //IL_061c: 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_06d9: Unknown result type (might be due to invalid IL or missing references) if (s_stagedProfile == null || s_resolvedState == null) { ReloadStagedProfileFromActiveWorld(); } bool flag = VanillaWorldAdapter.HasAuthority() && EpicMMOAdapter.HasAuthority() && EpicLootAdapter.HasAuthority(); bool isConfigFileAvailable = EpicMMOAdapter.IsConfigFileAvailable; bool isConfigFileAvailable2 = EpicLootAdapter.IsConfigFileAvailable; GUILayout.Label("Categoría: Progresión RPG, Atributos y Botín Mágico", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.backgroundColor = new Color(0.95f, 0.75f, 0.2f); if (GUILayout.Button("[+] Abrir Códice del Personaje (F10)", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(28f) })) { RpgCharacterCodexGui.Open(); } GUI.backgroundColor = Color.white; GUILayout.EndHorizontal(); GUILayout.Space(8f); GUILayout.Label("⚔\ufe0f Progresión de Personaje y Atributos (EpicMMO):", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); if (!isConfigFileAvailable) { Color backgroundColor = GUI.backgroundColor; GUI.backgroundColor = new Color(0.18f, 0.22f, 0.28f, 0.95f); GUILayout.BeginVertical(s_windowStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = new Color(1f, 0.85f, 0.35f); GUILayout.Label("⚔\ufe0f EpicMMOSystem no detectado en el perfil de mods activo", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.Space(4f); GUILayout.Label("TameMate opera de forma 100% autónoma en modo nativo/SLS sin dependencias obligatorias hacia EpicMMO.\n\nSi decides instalar WackyMole-EpicMMOSystem:\n• Podrás gobernar la tasa de XP, nivel máximo, puntos por nivel y fórmulas de combate desde este configurador.\n• Los presets de dificultad (Fácil, Normal, Difícil, Supreme) coordinarán dinámicamente tanto la supervivencia como la progresión RPG.\n• Cero descalibración: TameMate sincronizará automáticamente los atributos con compañeros y monturas.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); GUI.backgroundColor = backgroundColor; } else { GUILayout.Label("Configuración coordinada con WackyMole.EpicMMOSystem.cfg y memoria viva.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(8f); GUILayout.Label("1. Experiencia y Nivel Máximo:", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); DrawSliderRow("Multiplicador de XP:", "Tasa global de experiencia obtenida por monstruos derrotados y actividades.", s_resolvedState.EpicMmoExpRate.EffectiveValue, 0.1f, 3f, 0.05f, "{0:F2}x", s_resolvedState.EpicMmoExpRate.Origin, "EpicMMO (RateExp)", flag, delegate(float val) { StageEpicMmoExpRate(val); }, delegate { ClearStagedOverride("EpicMmoExpRate"); }); GUILayout.Space(6f); DrawIntSliderRow("Nivel Máximo:", s_resolvedState.EpicMmoMaxLevel.EffectiveValue, 10, 200, "{0}", s_resolvedState.EpicMmoMaxLevel.Origin, "EpicMMO (MaxLevel)", flag, delegate(int val) { StageEpicMmoMaxLevel(val); }, delegate { ClearStagedOverride("EpicMmoMaxLevel"); }); GUILayout.Space(12f); GUILayout.Label("2. Atributos y Desarrollo del Personaje:", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); DrawIntSliderRow("Puntos por Nivel:", s_resolvedState.EpicMmoFreePoints.EffectiveValue, 1, 20, "{0}", s_resolvedState.EpicMmoFreePoints.Origin, "EpicMMO (FreePointForLevel)", flag, delegate(int val) { StageEpicMmoFreePoints(val); }, delegate { ClearStagedOverride("EpicMmoFreePoints"); }); GUILayout.Space(6f); DrawSliderRow("Salud por Pto. (Vigor):", "Cantidad de HP máxima otorgada por cada punto asignado al atributo Vigor (Body).", s_resolvedState.EpicMmoHealthPerPoint.EffectiveValue, 0.2f, 5f, 0.1f, "{0:F2}", s_resolvedState.EpicMmoHealthPerPoint.Origin, "EpicMMO (AddHp)", flag, delegate(float val) { StageEpicMmoHealthPerPoint(val); }, delegate { ClearStagedOverride("EpicMmoHealthPerPoint"); }); GUILayout.Space(12f); GUILayout.Label("3. Fórmulas de Combate y Escalado:", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); DrawSliderRow("Daño Físico por Pto.:", "Bonificación porcentual de daño físico infligido por cada punto asignado a Fuerza (Strength).", s_resolvedState.EpicMmoPhysicDamage.EffectiveValue, 0.1f, 2f, 0.05f, "{0:F2}x", s_resolvedState.EpicMmoPhysicDamage.Origin, "EpicMMO (PhysicDamage)", flag, delegate(float val) { StageEpicMmoPhysicDamage(val); }, delegate { ClearStagedOverride("EpicMmoPhysicDamage"); }); GUILayout.Space(6f); DrawSliderRow("Armadura por Pto.:", "Bonificación de armadura física otorgada por cada punto asignado a Aguante (Endurance).", s_resolvedState.EpicMmoPhysicArmor.EffectiveValue, 0.05f, 1f, 0.05f, "{0:F2}x", s_resolvedState.EpicMmoPhysicArmor.Origin, "EpicMMO (PhysicArmor)", flag, delegate(float val) { StageEpicMmoPhysicArmor(val); }, delegate { ClearStagedOverride("EpicMmoPhysicArmor"); }); GUILayout.Space(12f); GUILayout.Label("4. Control de Criaturas y Restricción por Nivel:", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("Penalización por Nivel:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); bool effectiveValue = s_resolvedState.EpicMmoLowDamageLevel.EffectiveValue; string text = (effectiveValue ? "✔ Habilitada (Supreme)" : "✕ Deshabilitada"); GUI.backgroundColor = (effectiveValue ? new Color(0.75f, 0.25f, 0.25f) : new Color(0.2f, 0.65f, 0.3f)); GUI.enabled = flag; if (GUILayout.Button(text, s_activeButtonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(220f), GUILayout.Height(22f) })) { StageEpicMmoLowDamageLevel(!effectiveValue); } GUI.enabled = true; GUI.backgroundColor = Color.white; DrawOriginTag(s_resolvedState.EpicMmoLowDamageLevel.Origin); if (s_resolvedState.EpicMmoLowDamageLevel.Origin == ValueOrigin.CustomOverride && flag && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride("EpicMmoLowDamageLevel"); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(20f); GUI.color = new Color(0.72f, 0.72f, 0.72f); GUILayout.Label("Reduce drásticamente el daño a criaturas si la diferencia de nivel supera el umbral configurado (estilo Souls-like en Supreme).", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndHorizontal(); GUILayout.EndVertical(); } GUILayout.Space(16f); GUILayout.Label("✨ Equipamiento Mágico y Botín (EpicLoot):", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); if (!isConfigFileAvailable2) { Color backgroundColor2 = GUI.backgroundColor; GUI.backgroundColor = new Color(0.18f, 0.22f, 0.28f, 0.95f); GUILayout.BeginVertical(s_windowStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = new Color(1f, 0.85f, 0.35f); GUILayout.Label("✨ EpicLoot no detectado en el perfil de mods activo", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.Space(4f); GUILayout.Label("TameMate opera de forma 100% autónoma en modo nativo/SLS sin dependencias obligatorias hacia EpicLoot.\n\nSi decides instalar RandyKnapp-EpicLoot:\n• Podrás gobernar la tasa global de botín mágico, el escalado por estrellas de criaturas y las proporciones de equipamiento.\n• Los presets coordinarán de manera equilibrada el balance de progresión RPG y los encantamientos de equipo.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); GUI.backgroundColor = backgroundColor2; return; } GUILayout.Label("Configuración coordinada con randyknapp.mods.epicloot.cfg y memoria viva.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(8f); DrawSliderRow("Multiplicador de Botín:", "Multiplicador global de probabilidad de caída de objetos mágicos por criaturas.", s_resolvedState.EpicLootDropRate.EffectiveValue, 0.2f, 3f, 0.05f, "{0:F2}x", s_resolvedState.EpicLootDropRate.Origin, "EpicLoot (Global Drop Rate Modifier)", flag, delegate(float val) { StageEpicLootDropRate(val); }, delegate { ClearStagedOverride("EpicLootDropRate"); }); GUILayout.Space(6f); DrawSliderRow("Escalado por Estrellas:", "Multiplicador de probabilidad de botín mágico por cada estrella de criatura SLS.", s_resolvedState.EpicLootStarScaling.EffectiveValue, 0f, 2.5f, 0.05f, "{0:F2}x", s_resolvedState.EpicLootStarScaling.Origin, "EpicLoot (Star Loot Scaling)", flag, delegate(float val) { StageEpicLootStarScaling(val); }, delegate { ClearStagedOverride("EpicLootStarScaling"); }); GUILayout.Space(6f); DrawSliderRow("Proporción de Equipos:", "Proporción de objetos equipables (armas/armaduras) respecto a esquirlas y materiales.", s_resolvedState.EpicLootItemRatio.EffectiveValue, 0.1f, 1f, 0.05f, "{0:F2}", s_resolvedState.EpicLootItemRatio.Origin, "EpicLoot (Item Drop Ratio)", flag, delegate(float val) { StageEpicLootItemRatio(val); }, delegate { ClearStagedOverride("EpicLootItemRatio"); }); GUILayout.Space(6f); DrawSliderRow("Probabilidad de Set:", "Probabilidad de que un objeto legendario dropeado pertenezca a un set de equipamiento.", s_resolvedState.EpicLootSetChance.EffectiveValue, 0.01f, 0.5f, 0.01f, "{0:F2}", s_resolvedState.EpicLootSetChance.Origin, "EpicLoot (Set Item Drop Chance)", flag, delegate(float val) { StageEpicLootSetChance(val); }, delegate { ClearStagedOverride("EpicLootSetChance"); }); } private static void DrawModCompatibilityCategory() { //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) GUILayout.Space(4f); GUILayout.Label("\ud83e\udde9 Gobernanza de Compatibilidad y Ecosistema de Mods", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("TameMate actúa como el Director Central de Dificultad y Balance RPG. Los mods externos suministran afijos, escalado o prefabs sin sobrescrituras destructivas ni duplicación de multiplicadores.", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(8f); GUILayout.Label("Catálogo de Proveedores de Estadísticas (ExternalStatCatalog)", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); List allProviders = ExternalStatCatalog.GetAllProviders(); for (int i = 0; i < allProviders.Count; i++) { IExternalStatProvider externalStatProvider = allProviders[i]; bool isActive = externalStatProvider.IsActive; GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); string arg = (isActive ? "#66FF66" : "#AAAAAA"); string arg2 = (isActive ? "[ACTIVO]" : "[NO DETECTADO]"); GUILayout.Label($"{arg2} {externalStatProvider.DisplayName}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); string empty = string.Empty; GUILayout.Label(string.Format("{0}", externalStatProvider.Responsibility switch { ProviderResponsibility.ConfigurableByTameMate => "Gobernado en F11 (Escritura segura y Staging)", ProviderResponsibility.ReadOnlyDataProvider => "Proveedor de Datos (Solo Lectura)", ProviderResponsibility.PassiveCoexistence => "Coexistencia Pasiva (Sin conflicto de combate)", ProviderResponsibility.Exclusive => "Autoridad Exclusiva de Prefab", ProviderResponsibility.Cumulative => "Multiplicador Acumulativo de Jefes", ProviderResponsibility.ConflictDetected => "⚠\ufe0f Conflicto de Multiplicador Detectado", _ => "No administrado", }), s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(15f); GUI.color = new Color(0.7f, 0.7f, 0.7f); GUILayout.Label($"Capacidades: {externalStatProvider.Capabilities} | ID: {externalStatProvider.ProviderId}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.Space(2f); } GUILayout.Space(8f); GUILayout.Label("Análisis de Coexistencia y Prevención de Duplicación", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); CombatCalculationContext combatCalculationContext = ExternalStatCatalog.BuildUnifiedContext(); if (combatCalculationContext.DetectMultiplierConflict(out var conflictDescription)) { GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = new Color(1f, 0.65f, 0.15f); GUILayout.Label($"⚠\ufe0f ADVERTENCIA DE COEXISTENCIA MULTIPLICATIVA:\n{conflictDescription}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.Label("Recomendación: Modera los multiplicadores de vida en el Códice F11 o en la configuración externa para evitar un escalado insostenible.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); } else { GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = new Color(0.4f, 1f, 0.4f); GUILayout.Label("✅ CERO CONFLICTOS DETECTADOS", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.Label("La canalización de combate aplica multiplicadores en orden canónico estricto: Base -> Dificultad de Mundo -> Atributos RPG -> Afijos de Botín -> Modificadores de Jefe. Ningún gancho de multiplicación opera duplicado en runtime.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); } GUILayout.Space(8f); GUILayout.Label("Simulador de Combate Unificado en Memoria", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"• Daño Efectivo Jugador: {combatCalculationContext.CalculateEffectivePlayerDamage():F1} (Base 50)", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.Label($"• Salud Efectiva Criatura (0★): {combatCalculationContext.CalculateEffectiveCreatureHealth():F1} (Base 100)", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"• Salud Efectiva Jefe: {combatCalculationContext.CalculateEffectiveBossHealth(isBoss: true):F1} (Base 1000)", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.Label($"• TTK Criatura: {combatCalculationContext.SimulateTimeToKill(1f, isBoss: false):F1}s | TTK Jefe: {combatCalculationContext.SimulateTimeToKill(1f, isBoss: true):F1}s (1 atk/s)", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private static void DrawSliderRow(string label, string description, float currentValue, float min, float max, float step, string format, ValueOrigin origin, string provider, bool enabled, Action onNewValue, Action onReset) { //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"{label}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUI.enabled = enabled && currentValue > min; if (GUILayout.Button("-", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(24f), GUILayout.Height(22f) })) { float obj = StepDown(currentValue, step, min); onNewValue(obj); } GUI.enabled = enabled; float num = GUILayout.HorizontalSlider(currentValue, min, max, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) }); if (Math.Abs(num - currentValue) > 0.001f) { float num2 = (float)Math.Round(num / step) * step; num2 = Mathf.Clamp((float)Math.Round(num2, 2), min, max); if (Math.Abs(num2 - currentValue) > 0.0001f) { onNewValue(num2); } } GUI.enabled = enabled && currentValue < max; if (GUILayout.Button("+", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(24f), GUILayout.Height(22f) })) { float obj2 = StepUp(currentValue, step, max); onNewValue(obj2); } GUI.enabled = true; GUILayout.Label(string.Format(CultureInfo.InvariantCulture, format, currentValue), s_valueStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); DrawOriginTag(origin); if (origin == ValueOrigin.CustomOverride && enabled && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { onReset(); } GUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(description)) { GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(20f); GUI.color = new Color(0.72f, 0.72f, 0.72f); GUILayout.Label(description, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndHorizontal(); } GUILayout.Space(4f); GUILayout.EndVertical(); } private static void DrawBiomeStarCapRow(string internalBiome, string displayName, int configuredCap, int effectiveGameCap, int globalCeiling, ValueOrigin origin, bool enabled) { //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"{displayName}:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) }); GUI.enabled = enabled && configuredCap > 0; if (GUILayout.Button("-", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(24f), GUILayout.Height(22f) })) { StageBiomeStarCap(internalBiome, configuredCap - 1); } GUI.enabled = enabled; float num = GUILayout.HorizontalSlider((float)configuredCap, 0f, 16f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) }); int num2 = Mathf.RoundToInt(num); if (num2 != configuredCap) { StageBiomeStarCap(internalBiome, num2); } GUI.enabled = enabled && configuredCap < 16; if (GUILayout.Button("+", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(24f), GUILayout.Height(22f) })) { StageBiomeStarCap(internalBiome, configuredCap + 1); } GUI.enabled = true; GUILayout.Label($"{configuredCap}★", s_valueStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }); DrawOriginTag(origin); if (origin == ValueOrigin.CustomOverride && enabled && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { ClearStagedOverride(internalBiome); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(20f); if (configuredCap > globalCeiling) { GUI.color = new Color(1f, 0.7f, 0.2f); GUILayout.Label(string.Format("⚠\ufe0f {0}★ configuradas / {1}★ efectivas — Acotado por el tope de {2} ({1}★)", configuredCap, effectiveGameCap, s_stagedProfile.BasePreset), s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } else { GUI.color = new Color(0.7f, 0.85f, 0.7f); GUILayout.Label($"{configuredCap}★ configuradas / {effectiveGameCap}★ efectivas — Dentro del rango de {s_stagedProfile.BasePreset}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUI.color = Color.white; GUILayout.EndHorizontal(); GUILayout.EndVertical(); } private static void DrawIntSliderRow(string label, int currentValue, int min, int max, string format, ValueOrigin origin, string provider, bool enabled, Action onNewValue, Action onReset) { GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"{label}", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUI.enabled = enabled && currentValue > min; if (GUILayout.Button("-", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(24f), GUILayout.Height(22f) })) { onNewValue(currentValue - 1); } GUI.enabled = enabled; float num = GUILayout.HorizontalSlider((float)currentValue, (float)min, (float)max, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) }); int num2 = Mathf.RoundToInt(num); if (num2 != currentValue) { onNewValue(num2); } GUI.enabled = enabled && currentValue < max; if (GUILayout.Button("+", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(24f), GUILayout.Height(22f) })) { onNewValue(currentValue + 1); } GUI.enabled = true; GUILayout.Label(string.Format(format, currentValue), s_valueStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); DrawOriginTag(origin); if (origin == ValueOrigin.CustomOverride && enabled && GUILayout.Button("↺ Preset", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(70f), GUILayout.Height(22f) })) { onReset(); } GUILayout.EndHorizontal(); } private static void DrawOriginTag(ValueOrigin origin) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) switch (origin) { case ValueOrigin.CustomOverride: GUI.color = new Color(1f, 0.85f, 0.35f); GUILayout.Label("[Personalizado]", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); break; case ValueOrigin.InheritedFromPreset: GUI.color = new Color(0.65f, 0.85f, 1f); GUILayout.Label("[Preset Base]", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); break; default: GUI.color = new Color(0.8f, 0.8f, 0.8f); GUILayout.Label($"[{origin}]", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); break; } GUI.color = Color.white; } private static void DrawStatusBanner() { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(s_statusMessage)) { Color backgroundColor = default(Color); switch (s_statusType) { case MessageType.Success: ((Color)(ref backgroundColor))..ctor(0.2f, 0.55f, 0.3f, 0.95f); break; case MessageType.Warning: ((Color)(ref backgroundColor))..ctor(0.7f, 0.55f, 0.15f, 0.95f); break; case MessageType.Error: ((Color)(ref backgroundColor))..ctor(0.65f, 0.2f, 0.2f, 0.95f); break; default: ((Color)(ref backgroundColor))..ctor(0.18f, 0.24f, 0.3f, 0.95f); break; } Color backgroundColor2 = GUI.backgroundColor; GUI.backgroundColor = backgroundColor; GUILayout.BeginVertical(s_statusBannerStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(s_statusMessage, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); GUI.backgroundColor = backgroundColor2; } } private static void DrawFooterActions() { //IL_00bd: 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) GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); bool flag = VanillaWorldAdapter.HasAuthority(); GUI.enabled = flag && s_stagedProfile != null && s_stagedProfile.HasAnyOverrides(); if (GUILayout.Button("↺ Restablecer Todo", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(140f), GUILayout.Height(26f) })) { ClearAllStagedOverrides(); } GUI.enabled = true; if (GUILayout.Button("✖ Cancelar", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(100f), GUILayout.Height(26f) })) { CancelStagedChanges(); } GUILayout.FlexibleSpace(); GUI.enabled = flag; GUI.backgroundColor = new Color(0.2f, 0.65f, 0.35f); if (GUILayout.Button("✔ Aplicar Cambios", s_activeButtonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(150f), GUILayout.Height(26f) })) { ApplyStagedChanges(); } GUI.backgroundColor = Color.white; GUI.enabled = true; if (GUILayout.Button("Cerrar Códice", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(110f), GUILayout.Height(26f) })) { Close(); } GUILayout.EndHorizontal(); } private static Font GetSafeFont() { if ((Object)(object)s_safeFont == (Object)null) { try { s_safeFont = Font.CreateDynamicFontFromOSFont(new string[4] { "Arial", "Segoe UI", "Tahoma", "Lucida Sans Unicode" }, 12); } catch { } } return s_safeFont; } private static void EnsureStyles() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Expected O, but got Unknown //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected O, but got Unknown //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Expected O, but got Unknown //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Expected O, but got Unknown //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Expected O, but got Unknown //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Expected O, but got Unknown //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Expected O, but got Unknown //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_02fe: Expected O, but got Unknown if (!s_stylesInitialized || s_windowStyle == null) { Font safeFont = GetSafeFont(); s_windowStyle = new GUIStyle(GUI.skin.box); s_windowStyle.normal.background = Texture2D.whiteTexture; GUIStyle val = new GUIStyle(GUI.skin.label); val.fontSize = 15; val.fontStyle = (FontStyle)1; s_titleStyle = val; s_titleStyle.normal.textColor = new Color(1f, 0.85f, 0.35f); if ((Object)(object)safeFont != (Object)null) { s_titleStyle.font = safeFont; } GUIStyle val2 = new GUIStyle(GUI.skin.label); val2.fontSize = 12; val2.fontStyle = (FontStyle)1; s_subtitleStyle = val2; if ((Object)(object)safeFont != (Object)null) { s_subtitleStyle.font = safeFont; } GUIStyle val3 = new GUIStyle(GUI.skin.label); val3.fontSize = 13; val3.fontStyle = (FontStyle)1; s_sectionHeaderStyle = val3; s_sectionHeaderStyle.normal.textColor = new Color(0.75f, 0.9f, 1f); if ((Object)(object)safeFont != (Object)null) { s_sectionHeaderStyle.font = safeFont; } GUIStyle val4 = new GUIStyle(GUI.skin.label); val4.fontSize = 12; s_labelStyle = val4; s_labelStyle.normal.textColor = Color.white; if ((Object)(object)safeFont != (Object)null) { s_labelStyle.font = safeFont; } GUIStyle val5 = new GUIStyle(GUI.skin.label); val5.fontSize = 12; val5.fontStyle = (FontStyle)1; val5.alignment = (TextAnchor)5; s_valueStyle = val5; s_valueStyle.normal.textColor = new Color(1f, 0.85f, 0.35f); if ((Object)(object)safeFont != (Object)null) { s_valueStyle.font = safeFont; } GUIStyle val6 = new GUIStyle(GUI.skin.button); val6.fontSize = 11; s_buttonStyle = val6; if ((Object)(object)safeFont != (Object)null) { s_buttonStyle.font = safeFont; } GUIStyle val7 = new GUIStyle(GUI.skin.button); val7.fontSize = 11; val7.fontStyle = (FontStyle)1; s_activeButtonStyle = val7; if ((Object)(object)safeFont != (Object)null) { s_activeButtonStyle.font = safeFont; } GUIStyle val8 = new GUIStyle(GUI.skin.button); val8.fontSize = 12; s_tabStyle = val8; if ((Object)(object)safeFont != (Object)null) { s_tabStyle.font = safeFont; } GUIStyle val9 = new GUIStyle(GUI.skin.button); val9.fontSize = 12; val9.fontStyle = (FontStyle)1; s_activeTabStyle = val9; if ((Object)(object)safeFont != (Object)null) { s_activeTabStyle.font = safeFont; } s_statusBannerStyle = new GUIStyle(GUI.skin.box); s_statusBannerStyle.normal.background = Texture2D.whiteTexture; s_statusBannerStyle.padding = new RectOffset(6, 6, 4, 4); s_stylesInitialized = true; } } } public class DifficultyCodexComponent : MonoBehaviour { private void Update() { if (!DifficultyCodexGui.IsOpen) { return; } try { Type type = AccessTools.TypeByName("Character"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "SetTakeInputDelay", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo != null) { methodInfo.Invoke(null, new object[1] { 0.15f }); } } } catch { } try { Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; } catch { } try { if (Input.GetKeyDown((KeyCode)27)) { DifficultyCodexGui.Close(); } } catch { } } private void OnGUI() { if (DifficultyCodexGui.IsOpen) { DifficultyCodexGui.Draw(); } } } public static class DifficultyCodexPatches { public static class GlobalBalanceMayWriteExternalPatch { public static void Postfix(ref bool __result) { GlobalBalanceMayWriteExternalPostfix(ref __result); } } public static bool SuppressLegacyApply; private static bool s_isFullyInstalled; private static MethodInfo s_guidebookCloseMethod; public static bool IsFullyInstalled { get { return s_isFullyInstalled; } private set { s_isFullyInstalled = value; } } public static void Install(Harmony harmony, Assembly coreAssembly) { //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Expected O, but got Unknown //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Expected O, but got Unknown //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Expected O, but got Unknown //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Expected O, but got Unknown //IL_0312: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Expected O, but got Unknown IsFullyInstalled = false; if (harmony == null) { throw new ArgumentNullException("harmony"); } if (coreAssembly == null) { throw new ArgumentNullException("coreAssembly"); } bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; try { Type type = coreAssembly.GetType("TameMate.DifficultyManager"); if (type == null) { throw new InvalidOperationException("Type 'TameMate.DifficultyManager' not found in core assembly."); } Type type2 = coreAssembly.GetType("TameMate.GameDifficulty") ?? AccessTools.TypeByName("TameMate.GameDifficulty"); if (type2 == null) { throw new InvalidOperationException("Type 'TameMate.GameDifficulty' not found."); } MethodInfo methodInfo = AccessTools.Method(type, "SetDifficulty", new Type[2] { type2, typeof(bool) }, (Type[])null); if (methodInfo == null) { throw new MissingMethodException("Method 'DifficultyManager.SetDifficulty(GameDifficulty, bool)' not found."); } MethodInfo methodInfo2 = AccessTools.Method(typeof(DifficultyCodexPatches), "SetDifficultyPrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); flag = true; if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)"[DifficultyCodexPatches] SetDifficultyPrefix patched successfully with exact signature (preset, notifyPlayer)."); } MethodInfo methodInfo3 = AccessTools.Method(type, "ApplyDifficultyPreset", new Type[2] { type2, typeof(bool) }, (Type[])null); if (methodInfo3 == null) { throw new MissingMethodException("Method 'DifficultyManager.ApplyDifficultyPreset(GameDifficulty, bool)' not found."); } MethodInfo methodInfo4 = AccessTools.Method(typeof(DifficultyCodexPatches), "ApplyDifficultyPresetPrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); flag2 = true; if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)"[DifficultyCodexPatches] ApplyDifficultyPresetPrefix patched successfully with exact signature (preset, notifyPlayer)."); } MethodInfo methodInfo5 = AccessTools.PropertyGetter(type, "Current") ?? AccessTools.Method(type, "get_Current", (Type[])null, (Type[])null); if (methodInfo5 != null) { MethodInfo methodInfo6 = AccessTools.Method(typeof(DifficultyCodexPatches), "GetCurrentDifficultyPrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)"[DifficultyCodexPatches] DifficultyManager.get_Current patched successfully (DifficultyCoordinator authority)."); } } Type type3 = coreAssembly.GetType("TameMate.TameMateGuidebook"); if (type3 != null) { s_guidebookCloseMethod = AccessTools.Method(type3, "Close", (Type[])null, (Type[])null); MethodInfo methodInfo7 = AccessTools.Method(type3, "Update", (Type[])null, (Type[])null); if (methodInfo7 != null) { MethodInfo methodInfo8 = AccessTools.Method(typeof(DifficultyCodexPatches), "GuidebookUpdatePrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); flag3 = true; if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)"[DifficultyCodexPatches] GuidebookUpdatePrefix patched successfully."); } } else if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogWarning((object)"[DifficultyCodexPatches] Guidebook.Update method not found."); } } else if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogWarning((object)"[DifficultyCodexPatches] TameMateGuidebook type not found."); } Type type4 = AccessTools.TypeByName("TameMate.OceanHorn.GlobalBalance") ?? coreAssembly.GetType("TameMate.OceanHorn.GlobalBalance"); if (type4 != null) { MethodInfo methodInfo9 = AccessTools.Method(type4, "MayWriteExternal", (Type[])null, (Type[])null); if (methodInfo9 != null) { MethodInfo methodInfo10 = AccessTools.Method(typeof(DifficultyCodexPatches), "GlobalBalanceMayWriteExternalPostfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo10), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); flag4 = true; if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)"[DifficultyCodexPatches] GlobalBalanceMayWriteExternalPostfix patched successfully."); } } } MethodInfo methodInfo11 = AccessTools.Method(type, "SyncZoneSystemWithCurrentDifficulty", Type.EmptyTypes, (Type[])null); if (methodInfo11 != null) { try { MethodInfo methodInfo12 = AccessTools.Method(typeof(DifficultyCodexPatches), "SyncZoneSystemWithCurrentDifficultyPostfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)"[DifficultyCodexPatches] SyncZoneSystemWithCurrentDifficultyPostfix patched successfully."); } } catch (Exception ex) { if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogWarning((object)("[DifficultyCodexPatches] Optional SyncZoneSystem hook warning: " + ex.Message)); } } } if (!flag || !flag2) { throw new InvalidOperationException($"Critical patches missing: SetDifficulty={flag}, ApplyDifficultyPreset={flag2}"); } IsFullyInstalled = true; if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogInfo((object)$"[DifficultyCodexPatches] All patches verified and active (SetDifficulty={flag}, ApplyDifficultyPreset={flag2}, GuidebookUpdate={flag3}, MayWriteExternal={flag4}). Advanced difficulty codex enabled."); } } catch (Exception ex2) { IsFullyInstalled = false; try { harmony.UnpatchSelf(); } catch { } if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogError((object)("[DifficultyCodexPatches] Installation failed. Rolling back subsystem patches: " + ex2.ToString())); } throw; } } public static bool GetCurrentDifficultyPrefix(ref GameDifficulty __result) { if (!IsFullyInstalled) { return true; } try { DifficultyPreset activePreset = DifficultyCoordinator.GetActivePreset(); __result = (GameDifficulty)activePreset; return false; } catch { return true; } } public static bool SetDifficultyPrefix(GameDifficulty preset, bool notifyPlayer) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected I4, but got Unknown if (!IsFullyInstalled) { return true; } try { DifficultyPreset difficultyPreset = (int)preset switch { 0 => DifficultyPreset.Facil, 1 => DifficultyPreset.Normal, 2 => DifficultyPreset.Dificil, 3 => DifficultyPreset.Supreme, _ => DifficultyPreset.Normal, }; string activeWorldId = DifficultyCoordinator.GetActiveWorldId(); WorldDifficultyProfile worldDifficultyProfile = DifficultyCoordinator.LoadWorldProfile(activeWorldId); if (worldDifficultyProfile != null) { worldDifficultyProfile.BasePreset = difficultyPreset; DifficultyCoordinator.ApplyConfiguration(worldDifficultyProfile); } DifficultyCodexGui.OpenWithPreset(difficultyPreset); return false; } catch (Exception ex) { if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogError((object)("[DifficultyCodexPatches] SetDifficultyPrefix error: " + ex.Message)); } return false; } } public static bool ApplyDifficultyPresetPrefix(GameDifficulty preset, bool notifyPlayer) { if (!IsFullyInstalled) { return true; } return false; } public static bool GuidebookUpdatePrefix() { if (!IsFullyInstalled) { return true; } try { if (DifficultyCodexGui.IsOpen) { if (SafeIsEscapePressed()) { DifficultyCodexGui.Close(); return false; } if (SafeIsF11Pressed()) { DifficultyCodexGui.Close(); if (s_guidebookCloseMethod != null) { try { s_guidebookCloseMethod.Invoke(null, null); } catch { } } return false; } return false; } } catch { } return true; } private static bool SafeIsEscapePressed() { try { Type type = AccessTools.TypeByName("UnityEngine.Input") ?? typeof(Input); MethodInfo methodInfo = AccessTools.Method(type, "GetKeyDown", new Type[1] { typeof(KeyCode) }, (Type[])null); if (methodInfo != null) { return (bool)methodInfo.Invoke(null, new object[1] { (object)(KeyCode)27 }); } } catch { } return false; } private static bool SafeIsF11Pressed() { try { Type type = AccessTools.TypeByName("UnityEngine.Input") ?? typeof(Input); MethodInfo methodInfo = AccessTools.Method(type, "GetKeyDown", new Type[1] { typeof(KeyCode) }, (Type[])null); if (methodInfo != null) { return (bool)methodInfo.Invoke(null, new object[1] { (object)(KeyCode)292 }); } } catch { } return false; } public static void GlobalBalanceMayWriteExternalPostfix(ref bool __result) { if (IsFullyInstalled) { __result = false; } } public static void SyncZoneSystemWithCurrentDifficultyPostfix() { if (!IsFullyInstalled) { return; } try { if (VanillaWorldAdapter.HasAuthority() && StarLevelSystemAdapter.HasAuthority()) { string activeWorldId = DifficultyCoordinator.GetActiveWorldId(); DifficultyCoordinator.EnsureWorldDifficultySynchronized(activeWorldId); } AutonomousDifficultyBalance.InvalidateCache(); } catch (Exception ex) { if (DifficultyCodexGui.Log != null) { DifficultyCodexGui.Log.LogWarning((object)("[DifficultyCodexPatches] SyncZoneSystemWithCurrentDifficultyPostfix warning: " + ex.Message)); } } } } public enum DifficultyPreset { Facil, Normal, Dificil, Supreme } public enum ValueOrigin { InheritedFromPreset, CustomOverride, ExternalUnmanaged, Unavailable } public enum CoordinatorStatus { Success, PartialFailureRecovered, PartialFailureUnrecovered, Unauthorized, ConcurrentModificationConflict, InvalidRequest } public sealed class PresetDefinition { public DifficultyPreset Preset { get; private set; } public string DisplayName { get; private set; } public float PlayerDamageRate { get; private set; } public float EnemyDamageRate { get; private set; } public float ResourceRate { get; private set; } public bool RaidsEnabled { get; private set; } public float EventRate { get; private set; } public float RaidRate => EventRate; public float StarCreatureRate { get; private set; } public int GlobalCeilingStars { get; private set; } public Dictionary DefaultStarCaps { get; private set; } public PortalMode PortalMode { get; private set; } public DeathPenaltyMode DeathPenalty { get; private set; } public bool FreeBuild { get; private set; } public bool FreeCraft { get; private set; } public float EnemySpeedSize { get; private set; } public float EnemyBaseHealth { get; private set; } public float StarHealthMultiplier { get; private set; } public float StarDamageMultiplier { get; private set; } public float EpicMmoExpRate { get; private set; } public int EpicMmoMaxLevel { get; private set; } public int EpicMmoFreePoints { get; private set; } public bool EpicMmoLowDamageLevel { get; private set; } public float EpicMmoPhysicDamage { get; private set; } public float EpicMmoPhysicArmor { get; private set; } public float EpicMmoHealthPerPoint { get; private set; } public float EpicLootDropRate { get; private set; } public float EpicLootStarScaling { get; private set; } public float EpicLootItemRatio { get; private set; } public float EpicLootSetChance { get; private set; } public float StaminaRate { get; private set; } public float MoveStaminaRate { get; private set; } public float StaminaRegenRate { get; private set; } public PresetDefinition(DifficultyPreset preset, string displayName, float playerDmg, float enemyDmg, float resourceRate, bool raidsEnabled, float eventRate, float starCreatureRate, int globalCeilingStars, Dictionary defaultStarCaps, PortalMode portalMode = PortalMode.Normal, DeathPenaltyMode deathPenalty = DeathPenaltyMode.Normal, bool freeBuild = false, bool freeCraft = false, float enemySpeedSize = 1f, float enemyBaseHealth = 1f, float starHealthMultiplier = 1f, float starDamageMultiplier = 0.5f, float epicMmoExpRate = 1f, int epicMmoMaxLevel = 100, int epicMmoFreePoints = 5, bool epicMmoLowDamageLevel = false, float epicMmoPhysicDamage = 0.7f, float epicMmoPhysicArmor = 0.25f, float epicMmoHealthPerPoint = 1f, float epicLootDropRate = 1f, float epicLootStarScaling = 1f, float epicLootItemRatio = 0.7f, float epicLootSetChance = 0.15f, float staminaRate = 1f, float moveStaminaRate = 1f, float staminaRegenRate = 1f) { Preset = preset; DisplayName = displayName; PlayerDamageRate = playerDmg; EnemyDamageRate = enemyDmg; ResourceRate = resourceRate; RaidsEnabled = raidsEnabled; EventRate = eventRate; StarCreatureRate = starCreatureRate; GlobalCeilingStars = globalCeilingStars; DefaultStarCaps = new Dictionary(defaultStarCaps, StringComparer.OrdinalIgnoreCase); PortalMode = portalMode; DeathPenalty = deathPenalty; FreeBuild = freeBuild; FreeCraft = freeCraft; EnemySpeedSize = enemySpeedSize; EnemyBaseHealth = enemyBaseHealth; StarHealthMultiplier = starHealthMultiplier; StarDamageMultiplier = starDamageMultiplier; EpicMmoExpRate = epicMmoExpRate; EpicMmoMaxLevel = epicMmoMaxLevel; EpicMmoFreePoints = epicMmoFreePoints; EpicMmoLowDamageLevel = epicMmoLowDamageLevel; EpicMmoPhysicDamage = epicMmoPhysicDamage; EpicMmoPhysicArmor = epicMmoPhysicArmor; EpicMmoHealthPerPoint = epicMmoHealthPerPoint; EpicLootDropRate = epicLootDropRate; EpicLootStarScaling = epicLootStarScaling; EpicLootItemRatio = epicLootItemRatio; EpicLootSetChance = epicLootSetChance; StaminaRate = staminaRate; MoveStaminaRate = moveStaminaRate; StaminaRegenRate = staminaRegenRate; } public PresetDefinition(DifficultyPreset preset, string displayName, float playerDmg, float enemyDmg, float resourceRate, bool raidsEnabled, float eventRate, float starCreatureRate, int globalCeilingStars, Dictionary defaultStarCaps) : this(preset, displayName, playerDmg, enemyDmg, resourceRate, raidsEnabled, eventRate, starCreatureRate, globalCeilingStars, defaultStarCaps, PortalMode.Normal, DeathPenaltyMode.Normal, freeBuild: false, freeCraft: false, 1f, 1f, 1f, 0.5f, 1f, 100, 5, epicMmoLowDamageLevel: false, 0.7f, 0.25f, 1f, 1f, 1f, 0.7f, 0.15f, 1f, 1f, 1f) { } public PresetDefinition(DifficultyPreset preset, string displayName, float playerDmg, float enemyDmg, float resourceRate, bool raidsEnabled, float eventRate, Dictionary defaultStarCaps) : this(preset, displayName, playerDmg, enemyDmg, resourceRate, raidsEnabled, eventRate, 0.15f, 5, defaultStarCaps, PortalMode.Normal, DeathPenaltyMode.Normal, freeBuild: false, freeCraft: false, 1f, 1f, 1f, 0.5f, 1f, 100, 5, epicMmoLowDamageLevel: false, 0.7f, 0.25f, 1f, 1f, 1f, 0.7f, 0.15f, 1f, 1f, 1f) { } public static PresetDefinition Get(DifficultyPreset preset) { switch (preset) { case DifficultyPreset.Facil: { Dictionary dictionary4 = new Dictionary(StringComparer.OrdinalIgnoreCase); dictionary4.Add("Meadows", 1); dictionary4.Add("BlackForest", 1); dictionary4.Add("Swamp", 2); dictionary4.Add("Mountain", 2); dictionary4.Add("Plains", 3); dictionary4.Add("Mistlands", 3); dictionary4.Add("Ashlands", 3); dictionary4.Add("DeepNorth", 3); Dictionary defaultStarCaps4 = dictionary4; return new PresetDefinition(DifficultyPreset.Facil, "Fácil", 0.9f, 0.9f, 2f, raidsEnabled: true, 1f, 0.1f, 3, defaultStarCaps4, PortalMode.Normal, DeathPenaltyMode.Normal, freeBuild: false, freeCraft: false, 1f, 1f, 0.8f, 0.35f, 1.5f, 100, 5, epicMmoLowDamageLevel: false, 0.8f, 0.3f, 1.5f, 1.25f, 1f, 0.7f, 0.2f); } case DifficultyPreset.Normal: { Dictionary dictionary3 = new Dictionary(StringComparer.OrdinalIgnoreCase); dictionary3.Add("Meadows", 1); dictionary3.Add("BlackForest", 2); dictionary3.Add("Swamp", 3); dictionary3.Add("Mountain", 3); dictionary3.Add("Plains", 4); dictionary3.Add("Mistlands", 4); dictionary3.Add("Ashlands", 5); dictionary3.Add("DeepNorth", 5); Dictionary defaultStarCaps3 = dictionary3; return new PresetDefinition(DifficultyPreset.Normal, "Normal", 0.88f, 1.15f, 1.5f, raidsEnabled: true, 1f, 0.15f, 5, defaultStarCaps3, PortalMode.Normal, DeathPenaltyMode.Normal, freeBuild: false, freeCraft: false, 1f, 1f, 1f, 0.5f, 1f, 100, 5, epicMmoLowDamageLevel: false, 0.7f, 0.25f, 1f, 1f, 1f, 0.7f, 0.15f, 1f, 1f, 1f); } case DifficultyPreset.Dificil: { Dictionary dictionary2 = new Dictionary(StringComparer.OrdinalIgnoreCase); dictionary2.Add("Meadows", 2); dictionary2.Add("BlackForest", 3); dictionary2.Add("Swamp", 4); dictionary2.Add("Mountain", 5); dictionary2.Add("Plains", 6); dictionary2.Add("Mistlands", 7); dictionary2.Add("Ashlands", 8); dictionary2.Add("DeepNorth", 8); Dictionary defaultStarCaps2 = dictionary2; return new PresetDefinition(DifficultyPreset.Dificil, "Difícil", 0.8f, 1.65f, 1.25f, raidsEnabled: true, 1f, 0.25f, 8, defaultStarCaps2, PortalMode.Normal, DeathPenaltyMode.Normal, freeBuild: false, freeCraft: false, 1.05f, 1.1f, 1.1f, 0.6f, 0.85f, 100, 4, epicMmoLowDamageLevel: false, 0.6f, 0.2f, 1f, 0.85f, 0.8f, 0.6f, 0.1f); } case DifficultyPreset.Supreme: { Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); dictionary.Add("Meadows", 2); dictionary.Add("BlackForest", 4); dictionary.Add("Swamp", 6); dictionary.Add("Mountain", 8); dictionary.Add("Plains", 10); dictionary.Add("Mistlands", 10); dictionary.Add("Ashlands", 10); dictionary.Add("DeepNorth", 10); Dictionary defaultStarCaps = dictionary; return new PresetDefinition(DifficultyPreset.Supreme, "Supreme", 0.65f, 2.15f, 1.75f, raidsEnabled: true, 1f, 0.35f, 10, defaultStarCaps, PortalMode.Normal, DeathPenaltyMode.Normal, freeBuild: false, freeCraft: false, 1.1f, 1.2f, 1.15f, 0.7f, 0.75f, 100, 4, epicMmoLowDamageLevel: false, 0.5f, 0.2f, 0.8f, 0.7f, 0.7f, 0.5f, 0.1f); } default: return Get(DifficultyPreset.Normal); } } } public sealed class WorldDifficultyProfile { public string WorldId { get; set; } public string WorldName { get; set; } public DifficultyPreset BasePreset { get; set; } public float? PlayerDamageOverride { get; set; } public float? EnemyDamageOverride { get; set; } public float? ResourceRateOverride { get; set; } public bool? RaidsEnabledOverride { get; set; } public float? RaidRateOverride { get; set; } public float? StarCreatureRateOverride { get; set; } public PortalMode? PortalModeOverride { get; set; } public DeathPenaltyMode? DeathPenaltyOverride { get; set; } public bool? FreeBuildOverride { get; set; } public bool? FreeCraftOverride { get; set; } public float? EnemySpeedSizeOverride { get; set; } public float? EnemyBaseHealthOverride { get; set; } public float? StarHealthMultiplierOverride { get; set; } public float? StarDamageMultiplierOverride { get; set; } public float? EpicMmoExpRateOverride { get; set; } public int? EpicMmoMaxLevelOverride { get; set; } public int? EpicMmoFreePointsOverride { get; set; } public bool? EpicMmoLowDamageLevelOverride { get; set; } public float? EpicMmoPhysicDamageOverride { get; set; } public float? EpicMmoPhysicArmorOverride { get; set; } public float? EpicMmoHealthPerPointOverride { get; set; } public float? EpicLootDropRateOverride { get; set; } public float? EpicLootStarScalingOverride { get; set; } public float? EpicLootItemRatioOverride { get; set; } public float? EpicLootSetChanceOverride { get; set; } public float? StaminaRateOverride { get; set; } public float? MoveStaminaRateOverride { get; set; } public float? StaminaRegenRateOverride { get; set; } public Dictionary BiomeStarCapOverrides { get; private set; } public DateTime LastModifiedUtc { get; set; } public WorldDifficultyProfile() { WorldId = string.Empty; WorldName = string.Empty; BasePreset = DifficultyPreset.Normal; BiomeStarCapOverrides = new Dictionary(StringComparer.OrdinalIgnoreCase); LastModifiedUtc = DateTime.UtcNow; } public WorldDifficultyProfile(string worldId, string worldName, DifficultyPreset basePreset) : this() { WorldId = worldId ?? string.Empty; WorldName = worldName ?? string.Empty; BasePreset = basePreset; } public bool HasAnyOverrides() { if (!PlayerDamageOverride.HasValue && !EnemyDamageOverride.HasValue && !ResourceRateOverride.HasValue && !RaidsEnabledOverride.HasValue && !RaidRateOverride.HasValue && !StarCreatureRateOverride.HasValue && !PortalModeOverride.HasValue && !DeathPenaltyOverride.HasValue && !FreeBuildOverride.HasValue && !FreeCraftOverride.HasValue && !EnemySpeedSizeOverride.HasValue && !EnemyBaseHealthOverride.HasValue && !StarHealthMultiplierOverride.HasValue && !StarDamageMultiplierOverride.HasValue && !EpicMmoExpRateOverride.HasValue && !EpicMmoMaxLevelOverride.HasValue && !EpicMmoFreePointsOverride.HasValue && !EpicMmoLowDamageLevelOverride.HasValue && !EpicMmoPhysicDamageOverride.HasValue && !EpicMmoPhysicArmorOverride.HasValue && !EpicMmoHealthPerPointOverride.HasValue && !EpicLootDropRateOverride.HasValue && !EpicLootStarScalingOverride.HasValue && !EpicLootItemRatioOverride.HasValue && !EpicLootSetChanceOverride.HasValue) { if (BiomeStarCapOverrides != null) { return BiomeStarCapOverrides.Count > 0; } return false; } return true; } public bool ClearOverride(string settingName) { if (string.IsNullOrEmpty(settingName)) { return false; } string text = settingName.Trim(); if (text.Equals("PlayerDamage", StringComparison.OrdinalIgnoreCase)) { bool hasValue = PlayerDamageOverride.HasValue; PlayerDamageOverride = null; return hasValue; } if (text.Equals("EnemyDamage", StringComparison.OrdinalIgnoreCase)) { bool hasValue2 = EnemyDamageOverride.HasValue; EnemyDamageOverride = null; return hasValue2; } if (text.Equals("ResourceRate", StringComparison.OrdinalIgnoreCase) || text.Equals("Resources", StringComparison.OrdinalIgnoreCase)) { bool hasValue3 = ResourceRateOverride.HasValue; ResourceRateOverride = null; return hasValue3; } if (text.Equals("Raids", StringComparison.OrdinalIgnoreCase) || text.Equals("RaidsEnabled", StringComparison.OrdinalIgnoreCase)) { bool hasValue4 = RaidsEnabledOverride.HasValue; RaidsEnabledOverride = null; return hasValue4; } if (text.Equals("RaidRate", StringComparison.OrdinalIgnoreCase) || text.Equals("EventRate", StringComparison.OrdinalIgnoreCase)) { bool hasValue5 = RaidRateOverride.HasValue; RaidRateOverride = null; return hasValue5; } if (text.Equals("StarCreatureRate", StringComparison.OrdinalIgnoreCase) || text.Equals("StarFrequency", StringComparison.OrdinalIgnoreCase) || text.Equals("StarRate", StringComparison.OrdinalIgnoreCase)) { bool hasValue6 = StarCreatureRateOverride.HasValue; StarCreatureRateOverride = null; return hasValue6; } if (text.Equals("PortalMode", StringComparison.OrdinalIgnoreCase) || text.Equals("Portals", StringComparison.OrdinalIgnoreCase)) { bool hasValue7 = PortalModeOverride.HasValue; PortalModeOverride = null; return hasValue7; } if (text.Equals("DeathPenalty", StringComparison.OrdinalIgnoreCase) || text.Equals("DeathPenaltyMode", StringComparison.OrdinalIgnoreCase)) { bool hasValue8 = DeathPenaltyOverride.HasValue; DeathPenaltyOverride = null; return hasValue8; } if (text.Equals("FreeBuild", StringComparison.OrdinalIgnoreCase) || text.Equals("NoBuildCost", StringComparison.OrdinalIgnoreCase)) { bool hasValue9 = FreeBuildOverride.HasValue; FreeBuildOverride = null; return hasValue9; } if (text.Equals("FreeCraft", StringComparison.OrdinalIgnoreCase) || text.Equals("NoCraftCost", StringComparison.OrdinalIgnoreCase)) { bool hasValue10 = FreeCraftOverride.HasValue; FreeCraftOverride = null; return hasValue10; } if (text.Equals("EnemySpeedSize", StringComparison.OrdinalIgnoreCase) || text.Equals("EnemySpeed", StringComparison.OrdinalIgnoreCase)) { bool hasValue11 = EnemySpeedSizeOverride.HasValue; EnemySpeedSizeOverride = null; return hasValue11; } if (text.Equals("EnemyBaseHealth", StringComparison.OrdinalIgnoreCase) || text.Equals("BaseHealth", StringComparison.OrdinalIgnoreCase)) { bool hasValue12 = EnemyBaseHealthOverride.HasValue; EnemyBaseHealthOverride = null; return hasValue12; } if (text.Equals("StarHealthMultiplier", StringComparison.OrdinalIgnoreCase) || text.Equals("HealthPerLevel", StringComparison.OrdinalIgnoreCase) || text.Equals("StarHealth", StringComparison.OrdinalIgnoreCase)) { bool hasValue13 = StarHealthMultiplierOverride.HasValue; StarHealthMultiplierOverride = null; return hasValue13; } if (text.Equals("StarDamageMultiplier", StringComparison.OrdinalIgnoreCase) || text.Equals("DamagePerLevel", StringComparison.OrdinalIgnoreCase) || text.Equals("StarDamage", StringComparison.OrdinalIgnoreCase)) { bool hasValue14 = StarDamageMultiplierOverride.HasValue; StarDamageMultiplierOverride = null; return hasValue14; } if (text.Equals("EpicMmoExpRate", StringComparison.OrdinalIgnoreCase) || text.Equals("ExpRate", StringComparison.OrdinalIgnoreCase) || text.Equals("RateExp", StringComparison.OrdinalIgnoreCase)) { bool hasValue15 = EpicMmoExpRateOverride.HasValue; EpicMmoExpRateOverride = null; return hasValue15; } if (text.Equals("EpicMmoMaxLevel", StringComparison.OrdinalIgnoreCase) || text.Equals("MaxLevel", StringComparison.OrdinalIgnoreCase)) { bool hasValue16 = EpicMmoMaxLevelOverride.HasValue; EpicMmoMaxLevelOverride = null; return hasValue16; } if (text.Equals("EpicMmoFreePoints", StringComparison.OrdinalIgnoreCase) || text.Equals("FreePoints", StringComparison.OrdinalIgnoreCase) || text.Equals("FreePointForLevel", StringComparison.OrdinalIgnoreCase)) { bool hasValue17 = EpicMmoFreePointsOverride.HasValue; EpicMmoFreePointsOverride = null; return hasValue17; } if (text.Equals("EpicMmoLowDamageLevel", StringComparison.OrdinalIgnoreCase) || text.Equals("LowDamageLevel", StringComparison.OrdinalIgnoreCase) || text.Equals("Low_damage_level", StringComparison.OrdinalIgnoreCase)) { bool hasValue18 = EpicMmoLowDamageLevelOverride.HasValue; EpicMmoLowDamageLevelOverride = null; return hasValue18; } if (text.Equals("EpicMmoPhysicDamage", StringComparison.OrdinalIgnoreCase) || text.Equals("PhysicDamage", StringComparison.OrdinalIgnoreCase)) { bool hasValue19 = EpicMmoPhysicDamageOverride.HasValue; EpicMmoPhysicDamageOverride = null; return hasValue19; } if (text.Equals("EpicMmoPhysicArmor", StringComparison.OrdinalIgnoreCase) || text.Equals("PhysicArmor", StringComparison.OrdinalIgnoreCase)) { bool hasValue20 = EpicMmoPhysicArmorOverride.HasValue; EpicMmoPhysicArmorOverride = null; return hasValue20; } if (text.Equals("EpicMmoHealthPerPoint", StringComparison.OrdinalIgnoreCase) || text.Equals("HealthPerPoint", StringComparison.OrdinalIgnoreCase) || text.Equals("AddHp", StringComparison.OrdinalIgnoreCase)) { bool hasValue21 = EpicMmoHealthPerPointOverride.HasValue; EpicMmoHealthPerPointOverride = null; return hasValue21; } if (text.Equals("EpicLootDropRate", StringComparison.OrdinalIgnoreCase) || text.Equals("DropRate", StringComparison.OrdinalIgnoreCase) || text.Equals("GlobalDropRateModifier", StringComparison.OrdinalIgnoreCase)) { bool hasValue22 = EpicLootDropRateOverride.HasValue; EpicLootDropRateOverride = null; return hasValue22; } if (text.Equals("EpicLootStarScaling", StringComparison.OrdinalIgnoreCase) || text.Equals("StarLootScaling", StringComparison.OrdinalIgnoreCase) || text.Equals("StarScaling", StringComparison.OrdinalIgnoreCase)) { bool hasValue23 = EpicLootStarScalingOverride.HasValue; EpicLootStarScalingOverride = null; return hasValue23; } if (text.Equals("EpicLootItemRatio", StringComparison.OrdinalIgnoreCase) || text.Equals("ItemDropRatio", StringComparison.OrdinalIgnoreCase) || text.Equals("ItemRatio", StringComparison.OrdinalIgnoreCase)) { bool hasValue24 = EpicLootItemRatioOverride.HasValue; EpicLootItemRatioOverride = null; return hasValue24; } if (text.Equals("EpicLootSetChance", StringComparison.OrdinalIgnoreCase) || text.Equals("SetItemDropChance", StringComparison.OrdinalIgnoreCase) || text.Equals("SetChance", StringComparison.OrdinalIgnoreCase)) { bool hasValue25 = EpicLootSetChanceOverride.HasValue; EpicLootSetChanceOverride = null; return hasValue25; } if (text.Equals("StaminaRate", StringComparison.OrdinalIgnoreCase) || text.Equals("Stamina", StringComparison.OrdinalIgnoreCase)) { bool hasValue26 = StaminaRateOverride.HasValue; StaminaRateOverride = null; return hasValue26; } if (text.Equals("MoveStaminaRate", StringComparison.OrdinalIgnoreCase) || text.Equals("MoveStamina", StringComparison.OrdinalIgnoreCase)) { bool hasValue27 = MoveStaminaRateOverride.HasValue; MoveStaminaRateOverride = null; return hasValue27; } if (text.Equals("StaminaRegenRate", StringComparison.OrdinalIgnoreCase) || text.Equals("StaminaRegen", StringComparison.OrdinalIgnoreCase)) { bool hasValue28 = StaminaRegenRateOverride.HasValue; StaminaRegenRateOverride = null; return hasValue28; } if (BiomeStarCapOverrides.ContainsKey(text)) { BiomeStarCapOverrides.Remove(text); return true; } return false; } public void ClearAllOverrides() { PlayerDamageOverride = null; EnemyDamageOverride = null; ResourceRateOverride = null; RaidsEnabledOverride = null; RaidRateOverride = null; StarCreatureRateOverride = null; PortalModeOverride = null; DeathPenaltyOverride = null; FreeBuildOverride = null; FreeCraftOverride = null; EnemySpeedSizeOverride = null; EnemyBaseHealthOverride = null; StarHealthMultiplierOverride = null; StarDamageMultiplierOverride = null; EpicMmoExpRateOverride = null; EpicMmoMaxLevelOverride = null; EpicMmoFreePointsOverride = null; EpicMmoLowDamageLevelOverride = null; EpicMmoPhysicDamageOverride = null; EpicMmoPhysicArmorOverride = null; EpicMmoHealthPerPointOverride = null; EpicLootDropRateOverride = null; EpicLootStarScalingOverride = null; EpicLootItemRatioOverride = null; EpicLootSetChanceOverride = null; StaminaRateOverride = null; MoveStaminaRateOverride = null; StaminaRegenRateOverride = null; BiomeStarCapOverrides.Clear(); } public WorldDifficultyProfile Clone() { WorldDifficultyProfile worldDifficultyProfile = new WorldDifficultyProfile(); worldDifficultyProfile.WorldId = WorldId; worldDifficultyProfile.WorldName = WorldName; worldDifficultyProfile.BasePreset = BasePreset; worldDifficultyProfile.PlayerDamageOverride = PlayerDamageOverride; worldDifficultyProfile.EnemyDamageOverride = EnemyDamageOverride; worldDifficultyProfile.ResourceRateOverride = ResourceRateOverride; worldDifficultyProfile.RaidsEnabledOverride = RaidsEnabledOverride; worldDifficultyProfile.RaidRateOverride = RaidRateOverride; worldDifficultyProfile.StarCreatureRateOverride = StarCreatureRateOverride; worldDifficultyProfile.PortalModeOverride = PortalModeOverride; worldDifficultyProfile.DeathPenaltyOverride = DeathPenaltyOverride; worldDifficultyProfile.FreeBuildOverride = FreeBuildOverride; worldDifficultyProfile.FreeCraftOverride = FreeCraftOverride; worldDifficultyProfile.EnemySpeedSizeOverride = EnemySpeedSizeOverride; worldDifficultyProfile.EnemyBaseHealthOverride = EnemyBaseHealthOverride; worldDifficultyProfile.StarHealthMultiplierOverride = StarHealthMultiplierOverride; worldDifficultyProfile.StarDamageMultiplierOverride = StarDamageMultiplierOverride; worldDifficultyProfile.EpicMmoExpRateOverride = EpicMmoExpRateOverride; worldDifficultyProfile.EpicMmoMaxLevelOverride = EpicMmoMaxLevelOverride; worldDifficultyProfile.EpicMmoFreePointsOverride = EpicMmoFreePointsOverride; worldDifficultyProfile.EpicMmoLowDamageLevelOverride = EpicMmoLowDamageLevelOverride; worldDifficultyProfile.EpicMmoPhysicDamageOverride = EpicMmoPhysicDamageOverride; worldDifficultyProfile.EpicMmoPhysicArmorOverride = EpicMmoPhysicArmorOverride; worldDifficultyProfile.EpicMmoHealthPerPointOverride = EpicMmoHealthPerPointOverride; worldDifficultyProfile.EpicLootDropRateOverride = EpicLootDropRateOverride; worldDifficultyProfile.EpicLootStarScalingOverride = EpicLootStarScalingOverride; worldDifficultyProfile.EpicLootItemRatioOverride = EpicLootItemRatioOverride; worldDifficultyProfile.EpicLootSetChanceOverride = EpicLootSetChanceOverride; worldDifficultyProfile.StaminaRateOverride = StaminaRateOverride; worldDifficultyProfile.MoveStaminaRateOverride = MoveStaminaRateOverride; worldDifficultyProfile.StaminaRegenRateOverride = StaminaRegenRateOverride; worldDifficultyProfile.LastModifiedUtc = LastModifiedUtc; WorldDifficultyProfile worldDifficultyProfile2 = worldDifficultyProfile; foreach (KeyValuePair biomeStarCapOverride in BiomeStarCapOverrides) { worldDifficultyProfile2.BiomeStarCapOverrides[biomeStarCapOverride.Key] = biomeStarCapOverride.Value; } return worldDifficultyProfile2; } public string ToJson() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{"); stringBuilder.AppendFormat(" \"WorldId\": \"{0}\",\n", EscapeJson(WorldId)); stringBuilder.AppendFormat(" \"WorldName\": \"{0}\",\n", EscapeJson(WorldName)); stringBuilder.AppendFormat(" \"BasePreset\": \"{0}\",\n", BasePreset.ToString()); stringBuilder.AppendFormat(" \"PlayerDamageOverride\": {0},\n", PlayerDamageOverride.HasValue ? PlayerDamageOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EnemyDamageOverride\": {0},\n", EnemyDamageOverride.HasValue ? EnemyDamageOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"ResourceRateOverride\": {0},\n", ResourceRateOverride.HasValue ? ResourceRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"RaidsEnabledOverride\": {0},\n", (!RaidsEnabledOverride.HasValue) ? "null" : (RaidsEnabledOverride.Value ? "true" : "false")); stringBuilder.AppendFormat(" \"RaidRateOverride\": {0},\n", RaidRateOverride.HasValue ? RaidRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"StarCreatureRateOverride\": {0},\n", StarCreatureRateOverride.HasValue ? StarCreatureRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"PortalModeOverride\": {0},\n", PortalModeOverride.HasValue ? ("\"" + PortalModeOverride.Value.ToString() + "\"") : "null"); stringBuilder.AppendFormat(" \"DeathPenaltyOverride\": {0},\n", DeathPenaltyOverride.HasValue ? ("\"" + DeathPenaltyOverride.Value.ToString() + "\"") : "null"); stringBuilder.AppendFormat(" \"FreeBuildOverride\": {0},\n", (!FreeBuildOverride.HasValue) ? "null" : (FreeBuildOverride.Value ? "true" : "false")); stringBuilder.AppendFormat(" \"FreeCraftOverride\": {0},\n", (!FreeCraftOverride.HasValue) ? "null" : (FreeCraftOverride.Value ? "true" : "false")); stringBuilder.AppendFormat(" \"EnemySpeedSizeOverride\": {0},\n", EnemySpeedSizeOverride.HasValue ? EnemySpeedSizeOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EnemyBaseHealthOverride\": {0},\n", EnemyBaseHealthOverride.HasValue ? EnemyBaseHealthOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"StarHealthMultiplierOverride\": {0},\n", StarHealthMultiplierOverride.HasValue ? StarHealthMultiplierOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"StarDamageMultiplierOverride\": {0},\n", StarDamageMultiplierOverride.HasValue ? StarDamageMultiplierOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicMmoExpRateOverride\": {0},\n", EpicMmoExpRateOverride.HasValue ? EpicMmoExpRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicMmoMaxLevelOverride\": {0},\n", EpicMmoMaxLevelOverride.HasValue ? EpicMmoMaxLevelOverride.Value.ToString(CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicMmoFreePointsOverride\": {0},\n", EpicMmoFreePointsOverride.HasValue ? EpicMmoFreePointsOverride.Value.ToString(CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicMmoLowDamageLevelOverride\": {0},\n", (!EpicMmoLowDamageLevelOverride.HasValue) ? "null" : (EpicMmoLowDamageLevelOverride.Value ? "true" : "false")); stringBuilder.AppendFormat(" \"EpicMmoPhysicDamageOverride\": {0},\n", EpicMmoPhysicDamageOverride.HasValue ? EpicMmoPhysicDamageOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicMmoPhysicArmorOverride\": {0},\n", EpicMmoPhysicArmorOverride.HasValue ? EpicMmoPhysicArmorOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicMmoHealthPerPointOverride\": {0},\n", EpicMmoHealthPerPointOverride.HasValue ? EpicMmoHealthPerPointOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicLootDropRateOverride\": {0},\n", EpicLootDropRateOverride.HasValue ? EpicLootDropRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicLootStarScalingOverride\": {0},\n", EpicLootStarScalingOverride.HasValue ? EpicLootStarScalingOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicLootItemRatioOverride\": {0},\n", EpicLootItemRatioOverride.HasValue ? EpicLootItemRatioOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"EpicLootSetChanceOverride\": {0},\n", EpicLootSetChanceOverride.HasValue ? EpicLootSetChanceOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"StaminaRateOverride\": {0},\n", StaminaRateOverride.HasValue ? StaminaRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"MoveStaminaRateOverride\": {0},\n", MoveStaminaRateOverride.HasValue ? MoveStaminaRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"StaminaRegenRateOverride\": {0},\n", StaminaRegenRateOverride.HasValue ? StaminaRegenRateOverride.Value.ToString("F2", CultureInfo.InvariantCulture) : "null"); stringBuilder.AppendFormat(" \"LastModifiedUtc\": \"{0}\",\n", LastModifiedUtc.ToString("o", CultureInfo.InvariantCulture)); stringBuilder.AppendLine(" \"BiomeStarCapOverrides\": {"); int num = 0; foreach (KeyValuePair biomeStarCapOverride in BiomeStarCapOverrides) { stringBuilder.AppendFormat(" \"{0}\": {1}{2}\n", EscapeJson(biomeStarCapOverride.Key), biomeStarCapOverride.Value, (num < BiomeStarCapOverrides.Count - 1) ? "," : ""); num++; } stringBuilder.AppendLine(" }"); stringBuilder.AppendLine("}"); return stringBuilder.ToString(); } public static WorldDifficultyProfile FromJson(string json) { if (string.IsNullOrEmpty(json)) { return null; } WorldDifficultyProfile worldDifficultyProfile = new WorldDifficultyProfile(); Match match = Regex.Match(json, "\"WorldId\"\\s*:\\s*\"([^\"]*)\""); if (match.Success) { worldDifficultyProfile.WorldId = match.Groups[1].Value; } match = Regex.Match(json, "\"WorldName\"\\s*:\\s*\"([^\"]*)\""); if (match.Success) { worldDifficultyProfile.WorldName = match.Groups[1].Value; } Match match2 = Regex.Match(json, "\"BasePreset\"\\s*:\\s*\"([^\"]*)\""); if (match2.Success) { try { worldDifficultyProfile.BasePreset = (DifficultyPreset)Enum.Parse(typeof(DifficultyPreset), match2.Groups[1].Value, ignoreCase: true); } catch { worldDifficultyProfile.BasePreset = DifficultyPreset.Normal; } } worldDifficultyProfile.PlayerDamageOverride = ParseNullableFloat(json, "PlayerDamageOverride"); worldDifficultyProfile.EnemyDamageOverride = ParseNullableFloat(json, "EnemyDamageOverride"); worldDifficultyProfile.ResourceRateOverride = ParseNullableFloat(json, "ResourceRateOverride"); worldDifficultyProfile.RaidsEnabledOverride = ParseNullableBool(json, "RaidsEnabledOverride"); worldDifficultyProfile.RaidRateOverride = ParseNullableFloat(json, "RaidRateOverride"); worldDifficultyProfile.StarCreatureRateOverride = ParseNullableFloat(json, "StarCreatureRateOverride"); worldDifficultyProfile.PortalModeOverride = ParseNullableEnum(json, "PortalModeOverride"); worldDifficultyProfile.DeathPenaltyOverride = ParseNullableEnum(json, "DeathPenaltyOverride"); worldDifficultyProfile.FreeBuildOverride = ParseNullableBool(json, "FreeBuildOverride"); worldDifficultyProfile.FreeCraftOverride = ParseNullableBool(json, "FreeCraftOverride"); worldDifficultyProfile.EnemySpeedSizeOverride = ParseNullableFloat(json, "EnemySpeedSizeOverride"); worldDifficultyProfile.EnemyBaseHealthOverride = ParseNullableFloat(json, "EnemyBaseHealthOverride"); worldDifficultyProfile.StarHealthMultiplierOverride = ParseNullableFloat(json, "StarHealthMultiplierOverride"); worldDifficultyProfile.StarDamageMultiplierOverride = ParseNullableFloat(json, "StarDamageMultiplierOverride"); worldDifficultyProfile.EpicMmoExpRateOverride = ParseNullableFloat(json, "EpicMmoExpRateOverride"); worldDifficultyProfile.EpicMmoMaxLevelOverride = ParseNullableInt(json, "EpicMmoMaxLevelOverride"); worldDifficultyProfile.EpicMmoFreePointsOverride = ParseNullableInt(json, "EpicMmoFreePointsOverride"); worldDifficultyProfile.EpicMmoLowDamageLevelOverride = ParseNullableBool(json, "EpicMmoLowDamageLevelOverride"); worldDifficultyProfile.EpicMmoPhysicDamageOverride = ParseNullableFloat(json, "EpicMmoPhysicDamageOverride"); worldDifficultyProfile.EpicMmoPhysicArmorOverride = ParseNullableFloat(json, "EpicMmoPhysicArmorOverride"); worldDifficultyProfile.EpicMmoHealthPerPointOverride = ParseNullableFloat(json, "EpicMmoHealthPerPointOverride"); worldDifficultyProfile.EpicLootDropRateOverride = ParseNullableFloat(json, "EpicLootDropRateOverride"); worldDifficultyProfile.EpicLootStarScalingOverride = ParseNullableFloat(json, "EpicLootStarScalingOverride"); worldDifficultyProfile.EpicLootItemRatioOverride = ParseNullableFloat(json, "EpicLootItemRatioOverride"); worldDifficultyProfile.EpicLootSetChanceOverride = ParseNullableFloat(json, "EpicLootSetChanceOverride"); worldDifficultyProfile.StaminaRateOverride = ParseNullableFloat(json, "StaminaRateOverride"); worldDifficultyProfile.MoveStaminaRateOverride = ParseNullableFloat(json, "MoveStaminaRateOverride"); worldDifficultyProfile.StaminaRegenRateOverride = ParseNullableFloat(json, "StaminaRegenRateOverride"); Match match3 = Regex.Match(json, "\"BiomeStarCapOverrides\"\\s*:\\s*\\{([^\\}]*)\\}"); if (match3.Success) { string value = match3.Groups[1].Value; MatchCollection matchCollection = Regex.Matches(value, "\"([^\"]+)\"\\s*:\\s*(\\d+)"); foreach (Match item in matchCollection) { string value2 = item.Groups[1].Value; if (int.TryParse(item.Groups[2].Value, out var result)) { worldDifficultyProfile.BiomeStarCapOverrides[value2] = result; } } } return worldDifficultyProfile; } private static int? ParseNullableInt(string json, string propName) { Match match = Regex.Match(json, "\"" + propName + "\"\\s*:\\s*([0-9\\-]+|null)"); if (match.Success) { string text = match.Groups[1].Value.Trim(); if (text.Equals("null", StringComparison.OrdinalIgnoreCase)) { return null; } if (int.TryParse(text, out var result)) { return result; } } return null; } private static float? ParseNullableFloat(string json, string propName) { Match match = Regex.Match(json, "\"" + propName + "\"\\s*:\\s*([0-9\\.]+|null)"); if (match.Success) { string text = match.Groups[1].Value.Trim(); if (text.Equals("null", StringComparison.OrdinalIgnoreCase)) { return null; } if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } } return null; } private static bool? ParseNullableBool(string json, string propName) { Match match = Regex.Match(json, "\"" + propName + "\"\\s*:\\s*(true|false|null)"); if (match.Success) { string text = match.Groups[1].Value.Trim().ToLowerInvariant(); if (text == "true") { return true; } if (text == "false") { return false; } } return null; } private static T? ParseNullableEnum(string json, string propName) where T : struct { Match match = Regex.Match(json, "\"" + propName + "\"\\s*:\\s*(?:\"([^\"]*)\"|null)"); if (match.Success && match.Groups[1].Success) { string text = match.Groups[1].Value.Trim(); if (string.IsNullOrEmpty(text) || text.Equals("null", StringComparison.OrdinalIgnoreCase)) { return null; } try { return (T)Enum.Parse(typeof(T), text, ignoreCase: true); } catch { return null; } } return null; } private static string EscapeJson(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } return s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") .Replace("\r", "\\r"); } } public sealed class ResolvedSetting { public T EffectiveValue { get; set; } public T PresetValue { get; set; } public ValueOrigin Origin { get; set; } public string SourceDescription { get; set; } public ResolvedSetting(T effective, T preset, ValueOrigin origin, string desc) { EffectiveValue = effective; PresetValue = preset; Origin = origin; SourceDescription = desc; } } public sealed class ResolvedDifficultyState { public string WorldId { get; set; } public DifficultyPreset BasePreset { get; set; } public ResolvedSetting PlayerDamage { get; set; } public ResolvedSetting EnemyDamage { get; set; } public ResolvedSetting ResourceRate { get; set; } public ResolvedSetting RaidsEnabled { get; set; } public ResolvedSetting RaidRate { get; set; } public ResolvedSetting StarCreatureRate { get; set; } public ResolvedSetting PortalMode { get; set; } public ResolvedSetting DeathPenalty { get; set; } public ResolvedSetting FreeBuild { get; set; } public ResolvedSetting FreeCraft { get; set; } public ResolvedSetting EnemySpeedSize { get; set; } public ResolvedSetting EnemyBaseHealth { get; set; } public ResolvedSetting StarHealthMultiplier { get; set; } public ResolvedSetting StarDamageMultiplier { get; set; } public ResolvedSetting EpicMmoExpRate { get; set; } public ResolvedSetting EpicMmoMaxLevel { get; set; } public ResolvedSetting EpicMmoFreePoints { get; set; } public ResolvedSetting EpicMmoLowDamageLevel { get; set; } public ResolvedSetting EpicMmoPhysicDamage { get; set; } public ResolvedSetting EpicMmoPhysicArmor { get; set; } public ResolvedSetting EpicMmoHealthPerPoint { get; set; } public ResolvedSetting EpicLootDropRate { get; set; } public ResolvedSetting EpicLootStarScaling { get; set; } public ResolvedSetting EpicLootItemRatio { get; set; } public ResolvedSetting EpicLootSetChance { get; set; } public ResolvedSetting StaminaRate { get; set; } public ResolvedSetting MoveStaminaRate { get; set; } public ResolvedSetting StaminaRegenRate { get; set; } public int GlobalCeilingStars { get; set; } public Dictionary> BiomeStarCaps { get; private set; } public bool VanillaAdapterAvailable { get; set; } public bool SlsAdapterAvailable { get; set; } public bool EpicMmoAdapterAvailable { get; set; } public bool EpicLootAdapterAvailable { get; set; } public bool HasAuthority { get; set; } public List Warnings { get; private set; } public List Errors { get; private set; } public ResolvedDifficultyState() { WorldId = string.Empty; BasePreset = DifficultyPreset.Normal; BiomeStarCaps = new Dictionary>(StringComparer.OrdinalIgnoreCase); Warnings = new List(); Errors = new List(); } } public sealed class CoordinatorResult { public CoordinatorStatus Status { get; set; } public bool Success => Status == CoordinatorStatus.Success; public string Message { get; set; } public ResolvedDifficultyState State { get; set; } public List AppliedActions { get; private set; } public List RollbackActions { get; private set; } public List Errors { get; private set; } public CoordinatorResult() { Status = CoordinatorStatus.Success; Message = string.Empty; AppliedActions = new List(); RollbackActions = new List(); Errors = new List(); } public static CoordinatorResult Ok(string message, ResolvedDifficultyState state, List applied = null) { CoordinatorResult coordinatorResult = new CoordinatorResult(); coordinatorResult.Status = CoordinatorStatus.Success; coordinatorResult.Message = message; coordinatorResult.State = state; CoordinatorResult coordinatorResult2 = coordinatorResult; if (applied != null) { coordinatorResult2.AppliedActions.AddRange(applied); } return coordinatorResult2; } public static CoordinatorResult Fail(CoordinatorStatus status, string message, ResolvedDifficultyState state, List errors = null, List rollbacks = null) { CoordinatorResult coordinatorResult = new CoordinatorResult(); coordinatorResult.Status = status; coordinatorResult.Message = message; coordinatorResult.State = state; CoordinatorResult coordinatorResult2 = coordinatorResult; if (errors != null) { coordinatorResult2.Errors.AddRange(errors); } if (rollbacks != null) { coordinatorResult2.RollbackActions.AddRange(rollbacks); } return coordinatorResult2; } } public static class DifficultyCoordinator { private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.DifficultyCoordinator"); private static string s_customStoragePath = null; private static string s_customTamemateCfgPath = null; private static readonly object s_lock = new object(); private static WorldDifficultyProfile s_activeProfile = null; public static DifficultyPreset CurrentPreset => GetActivePreset(); public static DifficultyPreset GetActivePreset() { lock (s_lock) { if (s_activeProfile != null) { return s_activeProfile.BasePreset; } string activeWorldId = GetActiveWorldId(); s_activeProfile = LoadWorldProfile(activeWorldId); return (s_activeProfile == null) ? DifficultyPreset.Normal : s_activeProfile.BasePreset; } } public static void SetActiveProfile(WorldDifficultyProfile profile) { lock (s_lock) { s_activeProfile = profile; } } public static void ResetActiveProfile() { lock (s_lock) { s_activeProfile = null; } AutonomousDifficultyBalance.ResetCache(); } public static void SyncInMemoryTameMateState(DifficultyPreset preset, ResolvedDifficultyState resolved = null) { try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType("TameMate.TameMateConfig"); if (type != null) { FieldInfo field = type.GetField("DifficultyPreset", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(null); if (value != null) { PropertyInfo property = value.GetType().GetProperty("Value"); if (property != null) { Type type2 = assemblies[i].GetType("TameMate.GameDifficulty"); if (type2 != null) { object value2 = Enum.ToObject(type2, (int)preset); property.SetValue(value, value2, null); } } } } } Type type3 = assemblies[i].GetType("TameMate.DifficultyManager"); if (type3 != null && resolved != null) { PropertyInfo property2 = type3.GetProperty("PlayerDamageDealtMultiplier", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property2 != null) { property2.SetValue(null, resolved.PlayerDamage.EffectiveValue, null); } PropertyInfo property3 = type3.GetProperty("PlayerDamageTakenMultiplier", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property3 != null) { property3.SetValue(null, resolved.EnemyDamage.EffectiveValue, null); } } } } catch { } } public static void SetCustomStoragePathForTesting(string path) { s_customStoragePath = path; } public static void SetCustomTamemateConfigPathForTesting(string cfgPath) { s_customTamemateCfgPath = cfgPath; } public static void ResetStoragePath() { s_customStoragePath = null; s_customTamemateCfgPath = null; } public static bool TryParseDifficultyPresetString(string rawValue, out DifficultyPreset preset) { preset = DifficultyPreset.Normal; if (string.IsNullOrEmpty(rawValue)) { return false; } string text = rawValue.Trim(); if (string.Equals(text, "Facil", StringComparison.OrdinalIgnoreCase) || string.Equals(text, "Fácil", StringComparison.OrdinalIgnoreCase) || string.Equals(text, "Easy", StringComparison.OrdinalIgnoreCase) || text == "0") { preset = DifficultyPreset.Facil; return true; } if (string.Equals(text, "Normal", StringComparison.OrdinalIgnoreCase) || text == "1") { preset = DifficultyPreset.Normal; return true; } if (string.Equals(text, "Dificil", StringComparison.OrdinalIgnoreCase) || string.Equals(text, "Difícil", StringComparison.OrdinalIgnoreCase) || string.Equals(text, "Hard", StringComparison.OrdinalIgnoreCase) || text == "2") { preset = DifficultyPreset.Dificil; return true; } if (string.Equals(text, "Supreme", StringComparison.OrdinalIgnoreCase) || text == "3") { preset = DifficultyPreset.Supreme; return true; } return false; } public static bool TryReadPresetFromTamemateConfigFile(string cfgPath, out DifficultyPreset preset) { preset = DifficultyPreset.Normal; if (string.IsNullOrEmpty(cfgPath) || !File.Exists(cfgPath)) { return false; } try { string[] array = File.ReadAllLines(cfgPath, Encoding.UTF8); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0 || text.StartsWith("#", StringComparison.Ordinal) || text.StartsWith("[", StringComparison.Ordinal)) { continue; } Match match = Regex.Match(text, "^(?:Difficulty\\s+preset|DifficultyPreset)\\s*=\\s*(.+)$", RegexOptions.IgnoreCase); if (match.Success) { string text2 = match.Groups[1].Value.Trim(); int num = text2.IndexOf('#'); if (num >= 0) { text2 = text2.Substring(0, num).Trim(); } if (TryParseDifficultyPresetString(text2, out preset)) { return true; } } } } catch { } return false; } public static DifficultyPreset ResolveConfiguredBasePresetForWorldWithoutSidecar() { if (!string.IsNullOrEmpty(s_customTamemateCfgPath) && TryReadPresetFromTamemateConfigFile(s_customTamemateCfgPath, out var preset)) { return preset; } if (!string.IsNullOrEmpty(s_customStoragePath)) { try { string directoryName = Path.GetDirectoryName(s_customStoragePath); if (!string.IsNullOrEmpty(directoryName)) { string cfgPath = Path.Combine(directoryName, "mitsu.tamemate.cfg"); if (TryReadPresetFromTamemateConfigFile(cfgPath, out preset)) { return preset; } string directoryName2 = Path.GetDirectoryName(directoryName); if (!string.IsNullOrEmpty(directoryName2)) { string cfgPath2 = Path.Combine(directoryName2, "mitsu.tamemate.cfg"); if (TryReadPresetFromTamemateConfigFile(cfgPath2, out preset)) { return preset; } } } } catch { } return DifficultyPreset.Normal; } try { PropertyInfo property = typeof(Paths).GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public); string text = ((property != null) ? ((string)property.GetValue(null, null)) : Path.Combine(Directory.GetCurrentDirectory(), "BepInEx", "config")); if (!string.IsNullOrEmpty(text)) { string cfgPath3 = Path.Combine(text, "mitsu.tamemate.cfg"); if (TryReadPresetFromTamemateConfigFile(cfgPath3, out preset)) { return preset; } } } catch { } try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType("TameMate.TameMateConfig"); if (type != null) { FieldInfo field = type.GetField("DifficultyPreset", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(null); if (value != null) { PropertyInfo property2 = value.GetType().GetProperty("Value"); if (property2 != null) { object value2 = property2.GetValue(value, null); if (value2 != null && TryParseDifficultyPresetString(value2.ToString(), out preset)) { return preset; } break; } break; } break; } break; } } } catch { } return DifficultyPreset.Normal; } public static string GetStorageDirectory() { if (!string.IsNullOrEmpty(s_customStoragePath)) { if (!Directory.Exists(s_customStoragePath)) { Directory.CreateDirectory(s_customStoragePath); } return s_customStoragePath; } string path; try { PropertyInfo property = typeof(Paths).GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public); path = ((property != null) ? ((string)property.GetValue(null, null)) : Path.Combine(Directory.GetCurrentDirectory(), "BepInEx", "config")); } catch { path = Path.Combine(Directory.GetCurrentDirectory(), "BepInEx", "config"); } string text = Path.Combine(Path.Combine(path, "TameMate"), "difficulty_worlds"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } return text; } public static string GetActiveWorldId() { try { Type type = Type.GetType("ZNet, assembly_valheim"); if (type != null) { FieldInfo field = type.GetField("m_instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object obj = ((field != null) ? field.GetValue(null) : null); if (obj != null) { MethodInfo method = type.GetMethod("GetWorld", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); object obj2 = ((method != null) ? method.Invoke(obj, null) : null); if (obj2 != null) { FieldInfo field2 = obj2.GetType().GetField("m_uid", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); long num = ((field2 != null) ? ((long)field2.GetValue(obj2)) : 0); if (num != 0) { return num.ToString("D", CultureInfo.InvariantCulture); } FieldInfo field3 = obj2.GetType().GetField("m_name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); string text = ((field3 != null) ? ((string)field3.GetValue(obj2)) : null); if (!string.IsNullOrEmpty(text)) { return text; } FieldInfo field4 = obj2.GetType().GetField("m_worldName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); string text2 = ((field4 != null) ? ((string)field4.GetValue(obj2)) : null); if (!string.IsNullOrEmpty(text2)) { return text2; } } } } } catch { } return "default_world"; } public static string GetProfileFilePath(string worldId) { if (string.IsNullOrEmpty(worldId)) { worldId = "default_world"; } string arg = Regex.Replace(worldId, "[^a-zA-Z0-9_\\-]", "_"); return Path.Combine(GetStorageDirectory(), $"world_{arg}.json"); } public static WorldDifficultyProfile LoadWorldProfile(string worldId) { lock (s_lock) { if (string.IsNullOrEmpty(worldId)) { worldId = GetActiveWorldId(); } string profileFilePath = GetProfileFilePath(worldId); if (File.Exists(profileFilePath)) { try { string json = File.ReadAllText(profileFilePath, Encoding.UTF8); WorldDifficultyProfile worldDifficultyProfile = WorldDifficultyProfile.FromJson(json); if (worldDifficultyProfile != null) { return worldDifficultyProfile; } } catch (Exception ex) { if (Log != null) { Log.LogWarning((object)$"[TameMate] Error leyendo perfil para mundo {worldId}: {ex.Message}"); } } } DifficultyPreset basePreset = ResolveConfiguredBasePresetForWorldWithoutSidecar(); return new WorldDifficultyProfile(worldId, worldId, basePreset); } } public static bool SaveWorldProfile(WorldDifficultyProfile profile) { if (profile == null) { return false; } lock (s_lock) { try { string profileFilePath = GetProfileFilePath(profile.WorldId); profile.LastModifiedUtc = DateTime.UtcNow; string contents = profile.ToJson(); string text = profileFilePath + ".tmp"; File.WriteAllText(text, contents, Encoding.UTF8); if (File.Exists(profileFilePath)) { File.Delete(profileFilePath); } File.Move(text, profileFilePath); return true; } catch (Exception ex) { if (Log != null) { Log.LogError((object)$"[TameMate] Error guardando perfil para mundo {profile.WorldId}: {ex.Message}"); } return false; } } } public static ResolvedDifficultyState ResolveState(WorldDifficultyProfile profile) { if (profile == null) { profile = LoadWorldProfile(GetActiveWorldId()); } ResolvedDifficultyState resolvedDifficultyState = new ResolvedDifficultyState(); resolvedDifficultyState.WorldId = profile.WorldId; resolvedDifficultyState.BasePreset = profile.BasePreset; resolvedDifficultyState.VanillaAdapterAvailable = VanillaWorldAdapter.IsAvailable; resolvedDifficultyState.SlsAdapterAvailable = StarLevelSystemAdapter.IsConfigFileAvailable; resolvedDifficultyState.EpicMmoAdapterAvailable = EpicMMOAdapter.IsConfigFileAvailable; resolvedDifficultyState.EpicLootAdapterAvailable = EpicLootAdapter.IsConfigFileAvailable; resolvedDifficultyState.HasAuthority = VanillaWorldAdapter.HasAuthority(); ResolvedDifficultyState resolvedDifficultyState2 = resolvedDifficultyState; PresetDefinition presetDefinition = PresetDefinition.Get(profile.BasePreset); resolvedDifficultyState2.GlobalCeilingStars = presetDefinition.GlobalCeilingStars; if (profile.PlayerDamageOverride.HasValue) { resolvedDifficultyState2.PlayerDamage = new ResolvedSetting(profile.PlayerDamageOverride.Value, presetDefinition.PlayerDamageRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.PlayerDamage = new ResolvedSetting(presetDefinition.PlayerDamageRate, presetDefinition.PlayerDamageRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EnemyDamageOverride.HasValue) { resolvedDifficultyState2.EnemyDamage = new ResolvedSetting(profile.EnemyDamageOverride.Value, presetDefinition.EnemyDamageRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EnemyDamage = new ResolvedSetting(presetDefinition.EnemyDamageRate, presetDefinition.EnemyDamageRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.ResourceRateOverride.HasValue) { resolvedDifficultyState2.ResourceRate = new ResolvedSetting(profile.ResourceRateOverride.Value, presetDefinition.ResourceRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.ResourceRate = new ResolvedSetting(presetDefinition.ResourceRate, presetDefinition.ResourceRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.RaidsEnabledOverride.HasValue) { resolvedDifficultyState2.RaidsEnabled = new ResolvedSetting(profile.RaidsEnabledOverride.Value, presetDefinition.RaidsEnabled, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.RaidsEnabled = new ResolvedSetting(presetDefinition.RaidsEnabled, presetDefinition.RaidsEnabled, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.RaidRateOverride.HasValue) { resolvedDifficultyState2.RaidRate = new ResolvedSetting(profile.RaidRateOverride.Value, presetDefinition.EventRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.RaidRate = new ResolvedSetting(presetDefinition.EventRate, presetDefinition.EventRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.StarCreatureRateOverride.HasValue) { resolvedDifficultyState2.StarCreatureRate = new ResolvedSetting(profile.StarCreatureRateOverride.Value, presetDefinition.StarCreatureRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.StarCreatureRate = new ResolvedSetting(presetDefinition.StarCreatureRate, presetDefinition.StarCreatureRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.PortalModeOverride.HasValue) { resolvedDifficultyState2.PortalMode = new ResolvedSetting(profile.PortalModeOverride.Value, presetDefinition.PortalMode, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.PortalMode = new ResolvedSetting(presetDefinition.PortalMode, presetDefinition.PortalMode, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.DeathPenaltyOverride.HasValue) { resolvedDifficultyState2.DeathPenalty = new ResolvedSetting(profile.DeathPenaltyOverride.Value, presetDefinition.DeathPenalty, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.DeathPenalty = new ResolvedSetting(presetDefinition.DeathPenalty, presetDefinition.DeathPenalty, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.FreeBuildOverride.HasValue) { resolvedDifficultyState2.FreeBuild = new ResolvedSetting(profile.FreeBuildOverride.Value, presetDefinition.FreeBuild, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.FreeBuild = new ResolvedSetting(presetDefinition.FreeBuild, presetDefinition.FreeBuild, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.FreeCraftOverride.HasValue) { resolvedDifficultyState2.FreeCraft = new ResolvedSetting(profile.FreeCraftOverride.Value, presetDefinition.FreeCraft, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.FreeCraft = new ResolvedSetting(presetDefinition.FreeCraft, presetDefinition.FreeCraft, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EnemySpeedSizeOverride.HasValue) { resolvedDifficultyState2.EnemySpeedSize = new ResolvedSetting(profile.EnemySpeedSizeOverride.Value, presetDefinition.EnemySpeedSize, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EnemySpeedSize = new ResolvedSetting(presetDefinition.EnemySpeedSize, presetDefinition.EnemySpeedSize, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EnemyBaseHealthOverride.HasValue) { resolvedDifficultyState2.EnemyBaseHealth = new ResolvedSetting(profile.EnemyBaseHealthOverride.Value, presetDefinition.EnemyBaseHealth, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EnemyBaseHealth = new ResolvedSetting(presetDefinition.EnemyBaseHealth, presetDefinition.EnemyBaseHealth, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.StarHealthMultiplierOverride.HasValue) { resolvedDifficultyState2.StarHealthMultiplier = new ResolvedSetting(profile.StarHealthMultiplierOverride.Value, presetDefinition.StarHealthMultiplier, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.StarHealthMultiplier = new ResolvedSetting(presetDefinition.StarHealthMultiplier, presetDefinition.StarHealthMultiplier, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.StarDamageMultiplierOverride.HasValue) { resolvedDifficultyState2.StarDamageMultiplier = new ResolvedSetting(profile.StarDamageMultiplierOverride.Value, presetDefinition.StarDamageMultiplier, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.StarDamageMultiplier = new ResolvedSetting(presetDefinition.StarDamageMultiplier, presetDefinition.StarDamageMultiplier, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } foreach (KeyValuePair defaultStarCap in presetDefinition.DefaultStarCaps) { string key = defaultStarCap.Key; int value = defaultStarCap.Value; if (profile.BiomeStarCapOverrides != null && profile.BiomeStarCapOverrides.ContainsKey(key)) { resolvedDifficultyState2.BiomeStarCaps[key] = new ResolvedSetting(profile.BiomeStarCapOverrides[key], value, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.BiomeStarCaps[key] = new ResolvedSetting(value, value, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } } if (profile.EpicMmoExpRateOverride.HasValue) { resolvedDifficultyState2.EpicMmoExpRate = new ResolvedSetting(profile.EpicMmoExpRateOverride.Value, presetDefinition.EpicMmoExpRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoExpRate = new ResolvedSetting(presetDefinition.EpicMmoExpRate, presetDefinition.EpicMmoExpRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicMmoMaxLevelOverride.HasValue) { resolvedDifficultyState2.EpicMmoMaxLevel = new ResolvedSetting(profile.EpicMmoMaxLevelOverride.Value, presetDefinition.EpicMmoMaxLevel, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoMaxLevel = new ResolvedSetting(presetDefinition.EpicMmoMaxLevel, presetDefinition.EpicMmoMaxLevel, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicMmoFreePointsOverride.HasValue) { resolvedDifficultyState2.EpicMmoFreePoints = new ResolvedSetting(profile.EpicMmoFreePointsOverride.Value, presetDefinition.EpicMmoFreePoints, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoFreePoints = new ResolvedSetting(presetDefinition.EpicMmoFreePoints, presetDefinition.EpicMmoFreePoints, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicMmoLowDamageLevelOverride.HasValue) { resolvedDifficultyState2.EpicMmoLowDamageLevel = new ResolvedSetting(profile.EpicMmoLowDamageLevelOverride.Value, presetDefinition.EpicMmoLowDamageLevel, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoLowDamageLevel = new ResolvedSetting(presetDefinition.EpicMmoLowDamageLevel, presetDefinition.EpicMmoLowDamageLevel, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicMmoPhysicDamageOverride.HasValue) { resolvedDifficultyState2.EpicMmoPhysicDamage = new ResolvedSetting(profile.EpicMmoPhysicDamageOverride.Value, presetDefinition.EpicMmoPhysicDamage, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoPhysicDamage = new ResolvedSetting(presetDefinition.EpicMmoPhysicDamage, presetDefinition.EpicMmoPhysicDamage, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicMmoPhysicArmorOverride.HasValue) { resolvedDifficultyState2.EpicMmoPhysicArmor = new ResolvedSetting(profile.EpicMmoPhysicArmorOverride.Value, presetDefinition.EpicMmoPhysicArmor, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoPhysicArmor = new ResolvedSetting(presetDefinition.EpicMmoPhysicArmor, presetDefinition.EpicMmoPhysicArmor, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicMmoHealthPerPointOverride.HasValue) { resolvedDifficultyState2.EpicMmoHealthPerPoint = new ResolvedSetting(profile.EpicMmoHealthPerPointOverride.Value, presetDefinition.EpicMmoHealthPerPoint, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicMmoHealthPerPoint = new ResolvedSetting(presetDefinition.EpicMmoHealthPerPoint, presetDefinition.EpicMmoHealthPerPoint, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicLootDropRateOverride.HasValue) { resolvedDifficultyState2.EpicLootDropRate = new ResolvedSetting(profile.EpicLootDropRateOverride.Value, presetDefinition.EpicLootDropRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicLootDropRate = new ResolvedSetting(presetDefinition.EpicLootDropRate, presetDefinition.EpicLootDropRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicLootStarScalingOverride.HasValue) { resolvedDifficultyState2.EpicLootStarScaling = new ResolvedSetting(profile.EpicLootStarScalingOverride.Value, presetDefinition.EpicLootStarScaling, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicLootStarScaling = new ResolvedSetting(presetDefinition.EpicLootStarScaling, presetDefinition.EpicLootStarScaling, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicLootItemRatioOverride.HasValue) { resolvedDifficultyState2.EpicLootItemRatio = new ResolvedSetting(profile.EpicLootItemRatioOverride.Value, presetDefinition.EpicLootItemRatio, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicLootItemRatio = new ResolvedSetting(presetDefinition.EpicLootItemRatio, presetDefinition.EpicLootItemRatio, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.EpicLootSetChanceOverride.HasValue) { resolvedDifficultyState2.EpicLootSetChance = new ResolvedSetting(profile.EpicLootSetChanceOverride.Value, presetDefinition.EpicLootSetChance, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.EpicLootSetChance = new ResolvedSetting(presetDefinition.EpicLootSetChance, presetDefinition.EpicLootSetChance, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.StaminaRateOverride.HasValue) { resolvedDifficultyState2.StaminaRate = new ResolvedSetting(profile.StaminaRateOverride.Value, presetDefinition.StaminaRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.StaminaRate = new ResolvedSetting(presetDefinition.StaminaRate, presetDefinition.StaminaRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.MoveStaminaRateOverride.HasValue) { resolvedDifficultyState2.MoveStaminaRate = new ResolvedSetting(profile.MoveStaminaRateOverride.Value, presetDefinition.MoveStaminaRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.MoveStaminaRate = new ResolvedSetting(presetDefinition.MoveStaminaRate, presetDefinition.MoveStaminaRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } if (profile.StaminaRegenRateOverride.HasValue) { resolvedDifficultyState2.StaminaRegenRate = new ResolvedSetting(profile.StaminaRegenRateOverride.Value, presetDefinition.StaminaRegenRate, ValueOrigin.CustomOverride, "Personalizado por usuario"); } else { resolvedDifficultyState2.StaminaRegenRate = new ResolvedSetting(presetDefinition.StaminaRegenRate, presetDefinition.StaminaRegenRate, ValueOrigin.InheritedFromPreset, $"Heredado de preset {presetDefinition.DisplayName}"); } return resolvedDifficultyState2; } public static CoordinatorResult ApplyConfiguration(WorldDifficultyProfile profile, bool rollbackOnPartialFailure = true) { if (profile == null) { return CoordinatorResult.Fail(CoordinatorStatus.InvalidRequest, "Perfil nulo", null); } if (!VanillaWorldAdapter.HasAuthority() || !StarLevelSystemAdapter.HasAuthority() || !EpicMMOAdapter.HasAuthority() || !EpicLootAdapter.HasAuthority()) { ResolvedDifficultyState state = ResolveState(profile); return CoordinatorResult.Fail(CoordinatorStatus.Unauthorized, "Unauthorized: Solo el host/servidor puede aplicar cambios de dificultad y mundo.", state); } ResolvedDifficultyState resolvedDifficultyState = ResolveState(profile); List list = new List(); List list2 = new List(); List list3 = new List(); VanillaWorldSnapshot vanillaWorldSnapshot = null; if (VanillaWorldAdapter.IsAvailable) { vanillaWorldSnapshot = VanillaWorldAdapter.CaptureCurrentState(); } SlsConfigSnapshot slsConfigSnapshot = null; if (StarLevelSystemAdapter.IsConfigFileAvailable) { slsConfigSnapshot = StarLevelSystemAdapter.CaptureCurrentState(); } EpicMmoSnapshot epicMmoSnapshot = null; if (EpicMMOAdapter.IsConfigFileAvailable) { epicMmoSnapshot = EpicMMOAdapter.CaptureCurrentState(); } EpicLootSnapshot epicLootSnapshot = null; if (EpicLootAdapter.IsConfigFileAvailable) { epicLootSnapshot = EpicLootAdapter.CaptureCurrentState(); } bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; try { if (VanillaWorldAdapter.IsAvailable) { float effectiveValue = resolvedDifficultyState.PlayerDamage.EffectiveValue; float effectiveValue2 = resolvedDifficultyState.EnemyDamage.EffectiveValue; float effectiveValue3 = resolvedDifficultyState.ResourceRate.EffectiveValue; bool effectiveValue4 = resolvedDifficultyState.RaidsEnabled.EffectiveValue; float effectiveValue5 = resolvedDifficultyState.RaidRate.EffectiveValue; PortalMode effectiveValue6 = resolvedDifficultyState.PortalMode.EffectiveValue; DeathPenaltyMode effectiveValue7 = resolvedDifficultyState.DeathPenalty.EffectiveValue; bool effectiveValue8 = resolvedDifficultyState.FreeBuild.EffectiveValue; bool effectiveValue9 = resolvedDifficultyState.FreeCraft.EffectiveValue; float effectiveValue10 = resolvedDifficultyState.EnemySpeedSize.EffectiveValue; WorldAdapterResult worldAdapterResult = VanillaWorldAdapter.SetCombatRates(effectiveValue, effectiveValue2, effectiveValue10); if (!worldAdapterResult.Success) { list3.Add($"VanillaWorldAdapter Combat falló: {worldAdapterResult.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar combate vanilla: " + worldAdapterResult.ErrorMessage); } WorldAdapterResult worldAdapterResult2 = VanillaWorldAdapter.SetResourceRate(effectiveValue3); if (!worldAdapterResult2.Success) { list3.Add($"VanillaWorldAdapter Recursos falló: {worldAdapterResult2.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar recursos vanilla: " + worldAdapterResult2.ErrorMessage); } WorldAdapterResult worldAdapterResult3 = VanillaWorldAdapter.SetRaidsEnabled(effectiveValue4, effectiveValue5); if (!worldAdapterResult3.Success) { list3.Add($"VanillaWorldAdapter Incursiones falló: {worldAdapterResult3.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar incursiones vanilla: " + worldAdapterResult3.ErrorMessage); } WorldAdapterResult worldAdapterResult4 = VanillaWorldAdapter.SetPortalMode(effectiveValue6); if (!worldAdapterResult4.Success) { list3.Add($"VanillaWorldAdapter Portales falló: {worldAdapterResult4.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar portales vanilla: " + worldAdapterResult4.ErrorMessage); } WorldAdapterResult worldAdapterResult5 = VanillaWorldAdapter.SetDeathPenaltyMode(effectiveValue7); if (!worldAdapterResult5.Success) { list3.Add($"VanillaWorldAdapter Penalizaciones de muerte falló: {worldAdapterResult5.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar penalización de muerte vanilla: " + worldAdapterResult5.ErrorMessage); } WorldAdapterResult worldAdapterResult6 = VanillaWorldAdapter.SetFreeBuild(effectiveValue8); if (!worldAdapterResult6.Success) { list3.Add($"VanillaWorldAdapter Construcción libre falló: {worldAdapterResult6.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar construcción libre vanilla: " + worldAdapterResult6.ErrorMessage); } WorldAdapterResult worldAdapterResult7 = VanillaWorldAdapter.SetFreeCraft(effectiveValue9); if (!worldAdapterResult7.Success) { list3.Add($"VanillaWorldAdapter Fabricación libre falló: {worldAdapterResult7.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar fabricación libre vanilla: " + worldAdapterResult7.ErrorMessage); } float effectiveValue11 = resolvedDifficultyState.StaminaRate.EffectiveValue; float effectiveValue12 = resolvedDifficultyState.MoveStaminaRate.EffectiveValue; float effectiveValue13 = resolvedDifficultyState.StaminaRegenRate.EffectiveValue; WorldAdapterResult worldAdapterResult8 = VanillaWorldAdapter.SetStaminaRates(effectiveValue11, effectiveValue12, effectiveValue13); if (!worldAdapterResult8.Success) { list3.Add($"VanillaWorldAdapter Estamina falló: {worldAdapterResult8.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar estamina vanilla: " + worldAdapterResult8.ErrorMessage); } flag = true; list.Add($"Vanilla aplicado: PlayerDmg={effectiveValue:F2}, EnemyDmg={effectiveValue2:F2}, Resources={effectiveValue3:F2}, Raids={effectiveValue4} (x{effectiveValue5:F2}), Portals={effectiveValue6}, Death={effectiveValue7}, FreeBuild={effectiveValue8}, FreeCraft={effectiveValue9}, Stamina={effectiveValue11:F2}, MoveStamina={effectiveValue12:F2}, StaminaRegen={effectiveValue13:F2}"); } if (StarLevelSystemAdapter.IsConfigFileAvailable) { string expectedBaseHash = slsConfigSnapshot?.ContentHashSha256; foreach (KeyValuePair> biomeStarCap in resolvedDifficultyState.BiomeStarCaps) { string key = biomeStarCap.Key; int effectiveValue14 = biomeStarCap.Value.EffectiveValue; int num = StarLevelSystemAdapter.ReadBiomeStarCap(key); if (num != effectiveValue14) { SlsAdapterResult slsAdapterResult = StarLevelSystemAdapter.SetBiomeMaxLevelOverride(key, effectiveValue14, expectedBaseHash); if (!slsAdapterResult.Success) { list3.Add($"StarLevelSystemAdapter falló en {key}: {slsAdapterResult.ErrorMessage}"); throw new InvalidOperationException($"Fallo al actualizar estrella en {key}: {slsAdapterResult.ErrorMessage}"); } flag2 = true; expectedBaseHash = StarLevelSystemAdapter.CaptureCurrentState()?.ContentHashSha256; list.Add($"SLS aplicado: {key} = {effectiveValue14}★"); } } float effectiveValue15 = resolvedDifficultyState.StarCreatureRate.EffectiveValue; int globalCeilingStars = resolvedDifficultyState.GlobalCeilingStars; if (!StarLevelSystemAdapter.HasValidExponentialStarDistribution(effectiveValue15, globalCeilingStars, out var _)) { SlsAdapterResult slsAdapterResult2 = StarLevelSystemAdapter.SetDefaultStarDistribution(effectiveValue15, globalCeilingStars, expectedBaseHash); if (!slsAdapterResult2.Success) { list3.Add($"StarLevelSystemAdapter falló en distribución de estrellas: {slsAdapterResult2.ErrorMessage}"); throw new InvalidOperationException($"Fallo al actualizar distribución de estrellas: {slsAdapterResult2.ErrorMessage}"); } flag2 = true; expectedBaseHash = StarLevelSystemAdapter.CaptureCurrentState()?.ContentHashSha256; list.Add($"SLS distribución aplicada: Frecuencia={effectiveValue15:P0}, Techo={globalCeilingStars}★"); } float effectiveValue16 = resolvedDifficultyState.EnemyBaseHealth.EffectiveValue; float effectiveValue17 = resolvedDifficultyState.StarHealthMultiplier.EffectiveValue; float effectiveValue18 = resolvedDifficultyState.StarDamageMultiplier.EffectiveValue; bool flag5 = true; if (StarLevelSystemAdapter.ReadCreatureScalingRates(out var baseHealth, out var starHealth, out var starDamage) && Math.Abs(baseHealth - effectiveValue16) < 0.005f && Math.Abs(starHealth - effectiveValue17) < 0.005f && Math.Abs(starDamage - effectiveValue18) < 0.005f) { flag5 = false; } if (flag5) { SlsAdapterResult slsAdapterResult3 = StarLevelSystemAdapter.SetCreatureScalingRates(effectiveValue16, effectiveValue17, effectiveValue18, expectedBaseHash); if (!slsAdapterResult3.Success) { list3.Add($"StarLevelSystemAdapter falló en escalado de criaturas: {slsAdapterResult3.ErrorMessage}"); throw new InvalidOperationException($"Fallo al actualizar escalado de criaturas SLS: {slsAdapterResult3.ErrorMessage}"); } flag2 = true; expectedBaseHash = StarLevelSystemAdapter.CaptureCurrentState()?.ContentHashSha256; list.Add($"SLS escalado aplicado: BaseHealth={effectiveValue16:F2}x, Health/lvl={effectiveValue17:F2}x, Dmg/lvl={effectiveValue18:F2}x"); } } if (EpicMMOAdapter.IsConfigFileAvailable) { float effectiveValue19 = resolvedDifficultyState.EpicMmoExpRate.EffectiveValue; int effectiveValue20 = resolvedDifficultyState.EpicMmoMaxLevel.EffectiveValue; int effectiveValue21 = resolvedDifficultyState.EpicMmoFreePoints.EffectiveValue; bool effectiveValue22 = resolvedDifficultyState.EpicMmoLowDamageLevel.EffectiveValue; float effectiveValue23 = resolvedDifficultyState.EpicMmoPhysicDamage.EffectiveValue; float effectiveValue24 = resolvedDifficultyState.EpicMmoPhysicArmor.EffectiveValue; float effectiveValue25 = resolvedDifficultyState.EpicMmoHealthPerPoint.EffectiveValue; bool flag6 = true; if (epicMmoSnapshot != null && Math.Abs(epicMmoSnapshot.ExpRate - effectiveValue19) < 0.005f && epicMmoSnapshot.MaxLevel == effectiveValue20 && epicMmoSnapshot.FreePointsPerLevel == effectiveValue21 && epicMmoSnapshot.LowDamageLevel == effectiveValue22 && Math.Abs(epicMmoSnapshot.PhysicDamage - effectiveValue23) < 0.005f && Math.Abs(epicMmoSnapshot.PhysicArmor - effectiveValue24) < 0.005f && Math.Abs(epicMmoSnapshot.AddHp - effectiveValue25) < 0.005f) { flag6 = false; } if (flag6) { string expectedHash = epicMmoSnapshot?.ContentHashSha256; EpicMmoResult epicMmoResult = EpicMMOAdapter.SetConfiguration(effectiveValue19, effectiveValue20, effectiveValue21, effectiveValue22, effectiveValue23, effectiveValue24, effectiveValue25, expectedHash); if (!epicMmoResult.Success) { list3.Add($"EpicMMOAdapter falló: {epicMmoResult.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar configuración EpicMMO: " + epicMmoResult.ErrorMessage); } flag3 = true; list.Add($"EpicMMO aplicado: Exp={effectiveValue19:F2}x, MaxLvl={effectiveValue20}, Points/lvl={effectiveValue21}, LowDmg={effectiveValue22}, PhysDmg={effectiveValue23:F2}x, PhysArmor={effectiveValue24:F2}x, Hp/pt={effectiveValue25:F2}"); } } if (EpicLootAdapter.IsConfigFileAvailable) { float effectiveValue26 = resolvedDifficultyState.EpicLootDropRate.EffectiveValue; float effectiveValue27 = resolvedDifficultyState.EpicLootStarScaling.EffectiveValue; float effectiveValue28 = resolvedDifficultyState.EpicLootItemRatio.EffectiveValue; float effectiveValue29 = resolvedDifficultyState.EpicLootSetChance.EffectiveValue; bool flag7 = true; if (epicLootSnapshot != null && Math.Abs(epicLootSnapshot.GlobalDropRateModifier - effectiveValue26) < 0.005f && Math.Abs(epicLootSnapshot.StarLootScaling - effectiveValue27) < 0.005f && Math.Abs(epicLootSnapshot.ItemDropRatio - effectiveValue28) < 0.005f && Math.Abs(epicLootSnapshot.SetItemDropChance - effectiveValue29) < 0.005f) { flag7 = false; } if (flag7) { string expectedHash2 = epicLootSnapshot?.ContentHashSha256; EpicLootResult epicLootResult = EpicLootAdapter.ApplyConfiguration(effectiveValue26, effectiveValue27, effectiveValue28, effectiveValue29, expectedHash2); if (!epicLootResult.Success) { list3.Add($"EpicLootAdapter falló: {epicLootResult.ErrorMessage}"); throw new InvalidOperationException("Fallo al aplicar configuración EpicLoot: " + epicLootResult.ErrorMessage); } flag4 = true; list.Add($"EpicLoot aplicado: DropRate={effectiveValue26:F2}x, StarScaling={effectiveValue27:F2}x, ItemRatio={effectiveValue28:F2}, SetChance={effectiveValue29:F2}"); } } if (VanillaWorldAdapter.IsAvailable) { float num2 = VanillaWorldAdapter.ReadEffectiveResourceRate(); bool flag8 = VanillaWorldAdapter.ReadAreRaidsEnabled(); VanillaWorldAdapter.ReadEffectivePlayerDamage(); VanillaWorldAdapter.ReadEffectiveEnemyDamage(); float num3 = VanillaWorldAdapter.ReadEffectiveEnemySpeedSize(); if (Math.Abs(num2 - resolvedDifficultyState.ResourceRate.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en Recursos: esperado {resolvedDifficultyState.ResourceRate.EffectiveValue}, efectivo {num2}"); } if (flag8 != resolvedDifficultyState.RaidsEnabled.EffectiveValue) { list3.Add($"Discrepancia en Incursiones: esperado {resolvedDifficultyState.RaidsEnabled.EffectiveValue}, efectivo {flag8}"); } if (Math.Abs(num3 - resolvedDifficultyState.EnemySpeedSize.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en EnemySpeedSize: esperado {resolvedDifficultyState.EnemySpeedSize.EffectiveValue}, efectivo {num3}"); } float num4 = VanillaWorldAdapter.ReadEffectiveStaminaRate(); float num5 = VanillaWorldAdapter.ReadEffectiveMoveStaminaRate(); float num6 = VanillaWorldAdapter.ReadEffectiveStaminaRegenRate(); if (Math.Abs(num4 - resolvedDifficultyState.StaminaRate.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en StaminaRate: esperado {resolvedDifficultyState.StaminaRate.EffectiveValue}, efectivo {num4}"); } if (Math.Abs(num5 - resolvedDifficultyState.MoveStaminaRate.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en MoveStaminaRate: esperado {resolvedDifficultyState.MoveStaminaRate.EffectiveValue}, efectivo {num5}"); } if (Math.Abs(num6 - resolvedDifficultyState.StaminaRegenRate.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en StaminaRegenRate: esperado {resolvedDifficultyState.StaminaRegenRate.EffectiveValue}, efectivo {num6}"); } } if (StarLevelSystemAdapter.IsConfigFileAvailable) { foreach (KeyValuePair> biomeStarCap2 in resolvedDifficultyState.BiomeStarCaps) { int num7 = StarLevelSystemAdapter.ReadBiomeStarCap(biomeStarCap2.Key); if (num7 != -1 && num7 != biomeStarCap2.Value.EffectiveValue) { list3.Add($"Discrepancia en SLS {biomeStarCap2.Key}: esperado {biomeStarCap2.Value.EffectiveValue}★, efectivo {num7}★"); } } if (StarLevelSystemAdapter.ReadDefaultStarFrequency(out var frequency, out var _) && Math.Abs(frequency - resolvedDifficultyState.StarCreatureRate.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en SLS Frecuencia: esperado {resolvedDifficultyState.StarCreatureRate.EffectiveValue:P0}, efectivo {frequency:P0}"); } if (StarLevelSystemAdapter.ReadCreatureScalingRates(out var baseHealth2, out var starHealth2, out var starDamage2)) { if (Math.Abs(baseHealth2 - resolvedDifficultyState.EnemyBaseHealth.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en SLS BaseHealth: esperado {resolvedDifficultyState.EnemyBaseHealth.EffectiveValue:F2}, efectivo {baseHealth2:F2}"); } if (Math.Abs(starHealth2 - resolvedDifficultyState.StarHealthMultiplier.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en SLS StarHealthMultiplier: esperado {resolvedDifficultyState.StarHealthMultiplier.EffectiveValue:F2}, efectivo {starHealth2:F2}"); } if (Math.Abs(starDamage2 - resolvedDifficultyState.StarDamageMultiplier.EffectiveValue) > 0.05f) { list3.Add($"Discrepancia en SLS StarDamageMultiplier: esperado {resolvedDifficultyState.StarDamageMultiplier.EffectiveValue:F2}, efectivo {starDamage2:F2}"); } } } if (EpicMMOAdapter.IsConfigFileAvailable) { EpicMmoSnapshot epicMmoSnapshot2 = EpicMMOAdapter.CaptureCurrentState(); if (epicMmoSnapshot2 != null) { if (Math.Abs(epicMmoSnapshot2.ExpRate - resolvedDifficultyState.EpicMmoExpRate.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicMMO ExpRate: esperado {resolvedDifficultyState.EpicMmoExpRate.EffectiveValue:F2}, efectivo {epicMmoSnapshot2.ExpRate:F2}"); } if (epicMmoSnapshot2.MaxLevel != resolvedDifficultyState.EpicMmoMaxLevel.EffectiveValue) { list3.Add($"Discrepancia en EpicMMO MaxLevel: esperado {resolvedDifficultyState.EpicMmoMaxLevel.EffectiveValue}, efectivo {epicMmoSnapshot2.MaxLevel}"); } if (epicMmoSnapshot2.FreePointsPerLevel != resolvedDifficultyState.EpicMmoFreePoints.EffectiveValue) { list3.Add($"Discrepancia en EpicMMO FreePoints: esperado {resolvedDifficultyState.EpicMmoFreePoints.EffectiveValue}, efectivo {epicMmoSnapshot2.FreePointsPerLevel}"); } if (epicMmoSnapshot2.LowDamageLevel != resolvedDifficultyState.EpicMmoLowDamageLevel.EffectiveValue) { list3.Add($"Discrepancia en EpicMMO LowDamageLevel: esperado {resolvedDifficultyState.EpicMmoLowDamageLevel.EffectiveValue}, efectivo {epicMmoSnapshot2.LowDamageLevel}"); } if (Math.Abs(epicMmoSnapshot2.PhysicDamage - resolvedDifficultyState.EpicMmoPhysicDamage.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicMMO PhysicDamage: esperado {resolvedDifficultyState.EpicMmoPhysicDamage.EffectiveValue:F2}, efectivo {epicMmoSnapshot2.PhysicDamage:F2}"); } if (Math.Abs(epicMmoSnapshot2.PhysicArmor - resolvedDifficultyState.EpicMmoPhysicArmor.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicMMO PhysicArmor: esperado {resolvedDifficultyState.EpicMmoPhysicArmor.EffectiveValue:F2}, efectivo {epicMmoSnapshot2.PhysicArmor:F2}"); } if (Math.Abs(epicMmoSnapshot2.AddHp - resolvedDifficultyState.EpicMmoHealthPerPoint.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicMMO HealthPerPoint: esperado {resolvedDifficultyState.EpicMmoHealthPerPoint.EffectiveValue:F2}, efectivo {epicMmoSnapshot2.AddHp:F2}"); } } } if (EpicLootAdapter.IsConfigFileAvailable) { EpicLootSnapshot epicLootSnapshot2 = EpicLootAdapter.CaptureCurrentState(); if (epicLootSnapshot2 != null) { if (Math.Abs(epicLootSnapshot2.GlobalDropRateModifier - resolvedDifficultyState.EpicLootDropRate.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicLoot DropRate: esperado {resolvedDifficultyState.EpicLootDropRate.EffectiveValue:F2}, efectivo {epicLootSnapshot2.GlobalDropRateModifier:F2}"); } if (Math.Abs(epicLootSnapshot2.StarLootScaling - resolvedDifficultyState.EpicLootStarScaling.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicLoot StarScaling: esperado {resolvedDifficultyState.EpicLootStarScaling.EffectiveValue:F2}, efectivo {epicLootSnapshot2.StarLootScaling:F2}"); } if (Math.Abs(epicLootSnapshot2.ItemDropRatio - resolvedDifficultyState.EpicLootItemRatio.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicLoot ItemRatio: esperado {resolvedDifficultyState.EpicLootItemRatio.EffectiveValue:F2}, efectivo {epicLootSnapshot2.ItemDropRatio:F2}"); } if (Math.Abs(epicLootSnapshot2.SetItemDropChance - resolvedDifficultyState.EpicLootSetChance.EffectiveValue) > 0.01f) { list3.Add($"Discrepancia en EpicLoot SetChance: esperado {resolvedDifficultyState.EpicLootSetChance.EffectiveValue:F2}, efectivo {epicLootSnapshot2.SetItemDropChance:F2}"); } } } if (list3.Count > 0) { throw new InvalidOperationException("Discrepancias detectadas tras la aplicación"); } SaveWorldProfile(profile); SetActiveProfile(profile); SyncInMemoryTameMateState(profile.BasePreset, resolvedDifficultyState); AutonomousDifficultyBalance.InvalidateCache(); return CoordinatorResult.Ok("Configuración coordinada aplicada y verificada con éxito", resolvedDifficultyState, list); } catch (Exception ex) { if (rollbackOnPartialFailure) { bool flag9 = true; if (flag && vanillaWorldSnapshot != null) { if (VanillaWorldAdapter.Rollback(vanillaWorldSnapshot)) { list2.Add("VanillaWorldAdapter revertido al checkpoint previo"); } else { flag9 = false; list3.Add("Fallo al revertir VanillaWorldAdapter"); } } if (flag2 && slsConfigSnapshot != null) { if (StarLevelSystemAdapter.Rollback(slsConfigSnapshot)) { list2.Add("StarLevelSystemAdapter revertido al checkpoint previo"); } else { flag9 = false; list3.Add("Fallo al revertir StarLevelSystemAdapter"); } } if (flag3 && epicMmoSnapshot != null) { if (EpicMMOAdapter.Rollback(epicMmoSnapshot)) { list2.Add("EpicMMOAdapter revertido al checkpoint previo"); } else { flag9 = false; list3.Add("Fallo al revertir EpicMMOAdapter"); } } if (flag4 && epicLootSnapshot != null) { if (EpicLootAdapter.Rollback(epicLootSnapshot)) { list2.Add("EpicLootAdapter revertido al checkpoint previo"); } else { flag9 = false; list3.Add("Fallo al revertir EpicLootAdapter"); } } CoordinatorStatus status = (flag9 ? CoordinatorStatus.PartialFailureRecovered : CoordinatorStatus.PartialFailureUnrecovered); return CoordinatorResult.Fail(status, $"Transacción abortada: {ex.Message}", resolvedDifficultyState, list3, list2); } return CoordinatorResult.Fail(CoordinatorStatus.PartialFailureUnrecovered, $"Transacción fallida sin reversión: {ex.Message}", resolvedDifficultyState, list3); } } public static CoordinatorResult SwitchWorldContext(string newWorldId, bool autoApply = false) { if (string.IsNullOrEmpty(newWorldId)) { newWorldId = GetActiveWorldId(); } WorldDifficultyProfile worldDifficultyProfile = LoadWorldProfile(newWorldId); SetActiveProfile(worldDifficultyProfile); SyncInMemoryTameMateState(worldDifficultyProfile.BasePreset); AutonomousDifficultyBalance.InvalidateCache(); ResolvedDifficultyState state = ResolveState(worldDifficultyProfile); if (autoApply && VanillaWorldAdapter.HasAuthority()) { return ApplyConfiguration(worldDifficultyProfile); } return CoordinatorResult.Ok($"Contexto de mundo cambiado a {newWorldId}", state); } public static CoordinatorResult EnsureWorldDifficultySynchronized(string worldId = null) { if (string.IsNullOrEmpty(worldId)) { worldId = GetActiveWorldId(); } string profileFilePath = GetProfileFilePath(worldId); bool flag = File.Exists(profileFilePath); WorldDifficultyProfile worldDifficultyProfile = LoadWorldProfile(worldId); if (!VanillaWorldAdapter.HasAuthority() || !StarLevelSystemAdapter.HasAuthority()) { ResolvedDifficultyState state = ResolveState(worldDifficultyProfile); return CoordinatorResult.Fail(CoordinatorStatus.Unauthorized, "Unauthorized: Solo el servidor/host puede sincronizar la configuración del mundo y StarLevelSystem.", state); } if (!flag && StarLevelSystemAdapter.IsConfigFileAvailable) { if (!StarLevelSystemAdapter.HasDemonstratedDistributionInconsistency(out var inconsistencyReason)) { PresetDefinition presetDefinition = PresetDefinition.Get(worldDifficultyProfile.BasePreset); Dictionary dictionary = StarLevelSystemAdapter.ReadAllBiomeStarCaps(); if (dictionary != null && presetDefinition.DefaultStarCaps != null) { foreach (KeyValuePair item in dictionary) { if (presetDefinition.DefaultStarCaps.TryGetValue(item.Key, out var value) && item.Value >= 0 && item.Value <= 16 && item.Value != value) { worldDifficultyProfile.BiomeStarCapOverrides[item.Key] = item.Value; } } } if (StarLevelSystemAdapter.ReadDefaultStarFrequency(out var frequency, out var _) && frequency >= 0.01f && frequency <= 0.99f && Math.Abs(frequency - presetDefinition.StarCreatureRate) >= 0.005f) { worldDifficultyProfile.StarCreatureRateOverride = frequency; } } else if (Log != null) { Log.LogInfo((object)$"[DifficultyCoordinator] D-09.9.8 detected LevelSettings.yaml distribution inconsistency in sidecar-less world '{worldId}' (Preset={worldDifficultyProfile.BasePreset}): {inconsistencyReason} Repairing to D-09.2 matrix."); } } return ApplyConfiguration(worldDifficultyProfile); } } public struct EnhancedEditionSnapshot { public bool IsAvailable; public bool FarBuildsEnabled; public bool WholeWorldEnabled; public bool TerrainEditsEnabled; public string ConfigPath; public static EnhancedEditionSnapshot CreateDefault() { return new EnhancedEditionSnapshot { IsAvailable = false, FarBuildsEnabled = false, WholeWorldEnabled = true, TerrainEditsEnabled = true, ConfigPath = string.Empty }; } } public static class EnhancedEditionAdapter { public const string EnhancedEditionPluginGuid = "com.chase.valheimenhancededition"; private const string ConfigFileName = "com.chase.valheimenhancededition.cfg"; private static bool? s_isPluginLoadedCached = null; private static string s_customConfigPath = null; public static bool IsAvailable { get { if (!IsPluginLoaded) { return IsConfigFileAvailable; } return true; } } public static bool IsPluginLoaded { get { if (s_isPluginLoadedCached.HasValue) { return s_isPluginLoadedCached.Value; } try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("com.chase.valheimenhancededition")) { s_isPluginLoadedCached = true; return true; } } catch { } try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { string name = assemblies[i].GetName().Name; if (string.Equals(name, "ValheimEnhancedEdition", StringComparison.OrdinalIgnoreCase)) { s_isPluginLoadedCached = true; return true; } } } catch { } s_isPluginLoadedCached = false; return false; } } public static bool IsConfigFileAvailable { get { string text = ResolveConfigFilePath(); if (!string.IsNullOrEmpty(text)) { return File.Exists(text); } return false; } } public static void SetCustomConfigPathForTesting(string path) { s_customConfigPath = path; } public static string ResolveConfigFilePath() { if (!string.IsNullOrEmpty(s_customConfigPath)) { return s_customConfigPath; } try { string configPath = Paths.ConfigPath; if (!string.IsNullOrEmpty(configPath)) { string text = Path.Combine(configPath, "com.chase.valheimenhancededition.cfg"); if (File.Exists(text)) { return text; } } } catch { } string text2 = "C:\\Users\\Mitsu\\AppData\\Roaming\\Thunderstore Mod Manager\\DataFolder\\Valheim\\profiles\\Valheim Supreme\\BepInEx\\config"; if (Directory.Exists(text2)) { string text3 = Path.Combine(text2, "com.chase.valheimenhancededition.cfg"); if (File.Exists(text3)) { return text3; } } return string.Empty; } public static EnhancedEditionSnapshot CaptureCurrentState() { EnhancedEditionSnapshot result = EnhancedEditionSnapshot.CreateDefault(); string text = (result.ConfigPath = ResolveConfigFilePath()); if (string.IsNullOrEmpty(text) || !File.Exists(text)) { result.IsAvailable = IsPluginLoaded; return result; } result.IsAvailable = true; try { string[] array = File.ReadAllLines(text); string a = string.Empty; for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (string.IsNullOrEmpty(text2) || text2.StartsWith("#")) { continue; } if (text2.StartsWith("[") && text2.EndsWith("]")) { a = text2.Substring(1, text2.Length - 2).Trim(); continue; } int num = text2.IndexOf('='); if (num <= 0) { continue; } string a2 = text2.Substring(0, num).Trim(); string a3 = text2.Substring(num + 1).Trim(); if (string.Equals(a, "Far builds", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(a2, "Enabled", StringComparison.OrdinalIgnoreCase)) { result.FarBuildsEnabled = string.Equals(a3, "true", StringComparison.OrdinalIgnoreCase); } else if (string.Equals(a2, "WholeWorld", StringComparison.OrdinalIgnoreCase)) { result.WholeWorldEnabled = string.Equals(a3, "true", StringComparison.OrdinalIgnoreCase); } else if (string.Equals(a2, "TerrainEdits", StringComparison.OrdinalIgnoreCase)) { result.TerrainEditsEnabled = string.Equals(a3, "true", StringComparison.OrdinalIgnoreCase); } } } } catch { } return result; } public static void ResetCache() { s_isPluginLoadedCached = null; } } public sealed class EpicLootSnapshot { public DateTime CapturedAtUtc { get; set; } public string FilePath { get; set; } public string ContentHashSha256 { get; set; } public float GlobalDropRateModifier { get; set; } public float StarLootScaling { get; set; } public float ItemDropRatio { get; set; } public float SetItemDropChance { get; set; } public bool HealthCriticalEnchantments { get; set; } public string RawCfgContent { get; set; } public EpicLootSnapshot() { CapturedAtUtc = DateTime.UtcNow; FilePath = string.Empty; ContentHashSha256 = string.Empty; GlobalDropRateModifier = 1f; StarLootScaling = 1f; ItemDropRatio = 0.7f; SetItemDropChance = 0.15f; HealthCriticalEnchantments = true; RawCfgContent = string.Empty; } public EpicLootSnapshot Clone() { EpicLootSnapshot epicLootSnapshot = new EpicLootSnapshot(); epicLootSnapshot.CapturedAtUtc = CapturedAtUtc; epicLootSnapshot.FilePath = FilePath; epicLootSnapshot.ContentHashSha256 = ContentHashSha256; epicLootSnapshot.GlobalDropRateModifier = GlobalDropRateModifier; epicLootSnapshot.StarLootScaling = StarLootScaling; epicLootSnapshot.ItemDropRatio = ItemDropRatio; epicLootSnapshot.SetItemDropChance = SetItemDropChance; epicLootSnapshot.HealthCriticalEnchantments = HealthCriticalEnchantments; epicLootSnapshot.RawCfgContent = RawCfgContent; return epicLootSnapshot; } } public sealed class EpicLootResult { public bool Success { get; private set; } public EpicLootSnapshot Snapshot { get; private set; } public string ErrorMessage { get; private set; } private EpicLootResult(bool success, EpicLootSnapshot snapshot, string errorMessage) { Success = success; Snapshot = snapshot; ErrorMessage = errorMessage ?? string.Empty; } public static EpicLootResult Ok(EpicLootSnapshot snapshot) { return new EpicLootResult(success: true, snapshot, null); } public static EpicLootResult Fail(string error) { return new EpicLootResult(success: false, null, error); } } public static class EpicLootAdapter { public const string EpicLootPluginGuid = "randyknapp.mods.epicloot"; public const string EpicLootConfigFileName = "randyknapp.mods.epicloot.cfg"; private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.EpicLootAdapter"); private static string s_customConfigPath = null; private static EpicLootSnapshot s_baselineSnapshot = null; private static readonly object s_fileLock = new object(); public static bool IsInstalled { get { try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("randyknapp.mods.epicloot")) { return true; } } catch { } try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { string name = assemblies[i].GetName().Name; if (string.Equals(name, "EpicLoot", StringComparison.OrdinalIgnoreCase)) { return true; } } } catch { } return false; } } public static bool IsConfigFileAvailable { get { try { string configFilePath = GetConfigFilePath(); return !string.IsNullOrEmpty(configFilePath) && File.Exists(configFilePath); } catch { return false; } } } public static bool IsAvailable { get { if (!IsInstalled) { return IsConfigFileAvailable; } return true; } } public static void SetCustomConfigPathForTesting(string path) { s_customConfigPath = path; s_baselineSnapshot = null; } public static void ResetConfigPath() { s_customConfigPath = null; s_baselineSnapshot = null; } public static string GetConfigFilePath() { if (!string.IsNullOrEmpty(s_customConfigPath)) { return s_customConfigPath; } try { string configPath = Paths.ConfigPath; if (!string.IsNullOrEmpty(configPath)) { return Path.Combine(configPath, "randyknapp.mods.epicloot.cfg"); } } catch { } return Path.Combine(Directory.GetCurrentDirectory(), "randyknapp.mods.epicloot.cfg"); } private static bool HasRef(Object obj) { return !object.ReferenceEquals(obj, null); } public static bool HasAuthority() { try { if (HasRef((Object)(object)ZNet.instance)) { return ZNet.instance.IsServer(); } } catch { } return true; } public static string ComputeSha256(string content) { if (content == null) { return string.Empty; } using SHA256 sHA = SHA256.Create(); byte[] bytes = Encoding.UTF8.GetBytes(content); byte[] array = sHA.ComputeHash(bytes); StringBuilder stringBuilder = new StringBuilder(array.Length * 2); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("X2")); } return stringBuilder.ToString(); } public static EpicLootSnapshot CaptureCurrentState() { EpicLootSnapshot epicLootSnapshot = new EpicLootSnapshot(); string text = (epicLootSnapshot.FilePath = GetConfigFilePath()); lock (s_fileLock) { try { if (File.Exists(text)) { string content = (epicLootSnapshot.RawCfgContent = File.ReadAllText(text, Encoding.UTF8)); epicLootSnapshot.ContentHashSha256 = ComputeSha256(content); ParseCfgContent(content, epicLootSnapshot); } } catch (Exception ex) { if (Log != null) { Log.LogWarning((object)$"[EpicLootAdapter] Error leyendo {text}: {ex.Message}"); } } } OverlayLiveMemoryValues(epicLootSnapshot); if (s_baselineSnapshot == null) { s_baselineSnapshot = epicLootSnapshot.Clone(); } return epicLootSnapshot; } private static void ParseCfgContent(string content, EpicLootSnapshot snap) { if (string.IsNullOrEmpty(content) || snap == null) { return; } string[] array = content.Split(new string[3] { "\r\n", "\r", "\n" }, StringSplitOptions.None); string text = string.Empty; string[] array2 = array; foreach (string text2 in array2) { string text3 = text2.Trim(); if (text3.StartsWith("[") && text3.EndsWith("]")) { text = text3.Substring(1, text3.Length - 2).Trim(); } else { if (text3.StartsWith("#") || string.IsNullOrEmpty(text3) || !text3.Contains("=")) { continue; } int num = text3.IndexOf('='); string text4 = text3.Substring(0, num).Trim(); string text5 = text3.Substring(num + 1).Trim(); if (text.StartsWith("2 - Balance", StringComparison.OrdinalIgnoreCase)) { bool result2; if (text4.Equals("Global Drop Rate Modifier", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { snap.GlobalDropRateModifier = result; } else if (text4.Equals("Star Loot Scaling", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) { snap.StarLootScaling = result; } else if (text4.Equals("Item Drop Ratio", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) { snap.ItemDropRatio = result; } else if (text4.Equals("Set Item Drop Chance", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) { snap.SetItemDropChance = result; } else if (text4.Equals("Health Critical Enchantments", StringComparison.OrdinalIgnoreCase) && bool.TryParse(text5, out result2)) { snap.HealthCriticalEnchantments = result2; } } } } } private static void OverlayLiveMemoryValues(EpicLootSnapshot snap) { if (snap == null) { return; } try { Type type = Type.GetType("EpicLoot.Config.ELConfig, EpicLoot", throwOnError: false); if (!(type == null)) { snap.GlobalDropRateModifier = GetConfigEntryValue(type, "GlobalDropRateModifier", snap.GlobalDropRateModifier); snap.StarLootScaling = GetConfigEntryValue(type, "StarLootScaling", snap.StarLootScaling); snap.ItemDropRatio = GetConfigEntryValue(type, "ItemDropRatio", snap.ItemDropRatio); snap.SetItemDropChance = GetConfigEntryValue(type, "SetItemDropChance", snap.SetItemDropChance); snap.HealthCriticalEnchantments = GetConfigEntryValue(type, "HealthCriticalEffectsEnabled", snap.HealthCriticalEnchantments); } } catch { } } private static T GetConfigEntryValue(Type type, string fieldName, T fallback) { try { FieldInfo field = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(null); if (value != null) { PropertyInfo property = value.GetType().GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); if (property != null) { object value2 = property.GetValue(value, null); if (value2 != null) { return (T)Convert.ChangeType(value2, typeof(T), CultureInfo.InvariantCulture); } } } } } catch { } return fallback; } private static void SetConfigEntryValue(Type type, string fieldName, object value) { try { FieldInfo field = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (!(field != null)) { return; } object value2 = field.GetValue(null); if (value2 != null) { PropertyInfo property = value2.GetType().GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); if (property != null && property.CanWrite) { object value3 = Convert.ChangeType(value, property.PropertyType, CultureInfo.InvariantCulture); property.SetValue(value2, value3, null); } } } catch { } } public static bool TryUpdateIniContent(string originalContent, float dropRate, float starScaling, float itemRatio, float setChance, out string modifiedContent) { modifiedContent = originalContent; if (string.IsNullOrEmpty(originalContent)) { return false; } string separator = (originalContent.Contains("\r\n") ? "\r\n" : "\n"); string[] collection = originalContent.Split(new string[3] { "\r\n", "\r", "\n" }, StringSplitOptions.None); List list = new List(collection); string text = string.Empty; for (int i = 0; i < list.Count; i++) { string text2 = list[i].Trim(); if (text2.StartsWith("[") && text2.EndsWith("]")) { text = text2.Substring(1, text2.Length - 2).Trim(); } else { if (text2.StartsWith("#") || string.IsNullOrEmpty(text2) || !text2.Contains("=")) { continue; } int length = list[i].IndexOf('='); string text3 = list[i].Substring(0, length).Trim(); string arg = list[i].Substring(0, list[i].Length - list[i].TrimStart(new char[0]).Length); if (text.StartsWith("2 - Balance", StringComparison.OrdinalIgnoreCase)) { if (text3.Equals("Global Drop Rate Modifier", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, dropRate); } else if (text3.Equals("Star Loot Scaling", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, starScaling); } else if (text3.Equals("Item Drop Ratio", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, itemRatio); } else if (text3.Equals("Set Item Drop Chance", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, setChance); } } } } modifiedContent = string.Join(separator, list.ToArray()); return true; } public static EpicLootResult ApplyConfiguration(float dropRate, float starScaling, float itemRatio, float setChance, string expectedHash = null) { if (!HasAuthority()) { return EpicLootResult.Fail("Acceso denegado: solo el anfitrión/servidor posee autoridad para modificar parámetros de EpicLoot."); } lock (s_fileLock) { try { string configFilePath = GetConfigFilePath(); if (!File.Exists(configFilePath)) { return EpicLootResult.Fail($"Archivo de configuración de EpicLoot no encontrado en: {configFilePath}"); } string text = File.ReadAllText(configFilePath, Encoding.UTF8); string text2 = ComputeSha256(text); if (!string.IsNullOrEmpty(expectedHash) && !string.Equals(expectedHash, text2, StringComparison.OrdinalIgnoreCase)) { return EpicLootResult.Fail($"Conflicto de concurrencia: se esperaba hash {expectedHash}, pero el archivo tiene hash {text2}."); } if (!TryUpdateIniContent(text, dropRate, starScaling, itemRatio, setChance, out var modifiedContent)) { return EpicLootResult.Fail("Fallo al mutar quirúrgicamente el archivo randyknapp.mods.epicloot.cfg."); } string path = configFilePath + ".bak"; File.WriteAllText(path, text, Encoding.UTF8); File.WriteAllText(configFilePath, modifiedContent, Encoding.UTF8); SyncLiveMemory(dropRate, starScaling, itemRatio, setChance); EpicLootSnapshot snapshot = CaptureCurrentState(); if (Log != null) { Log.LogInfo((object)$"[EpicLootAdapter] Configuración aplicada: DropRate={dropRate:F2}x, StarScaling={starScaling:F2}x, ItemRatio={itemRatio:F2}, SetChance={setChance:F2}"); } return EpicLootResult.Ok(snapshot); } catch (Exception ex) { return EpicLootResult.Fail($"Error aplicando configuración EpicLoot: {ex.Message}"); } } } private static void SyncLiveMemory(float dropRate, float starScaling, float itemRatio, float setChance) { try { Type type = Type.GetType("EpicLoot.Config.ELConfig, EpicLoot", throwOnError: false); if (type != null) { SetConfigEntryValue(type, "GlobalDropRateModifier", dropRate); SetConfigEntryValue(type, "StarLootScaling", starScaling); SetConfigEntryValue(type, "ItemDropRatio", itemRatio); SetConfigEntryValue(type, "SetItemDropChance", setChance); } } catch { } } public static bool Rollback(EpicLootSnapshot snapshot) { if (snapshot == null) { return false; } lock (s_fileLock) { try { string configFilePath = GetConfigFilePath(); if (File.Exists(configFilePath) && !string.IsNullOrEmpty(snapshot.RawCfgContent)) { File.WriteAllText(configFilePath, snapshot.RawCfgContent, Encoding.UTF8); } SyncLiveMemory(snapshot.GlobalDropRateModifier, snapshot.StarLootScaling, snapshot.ItemDropRatio, snapshot.SetItemDropChance); if (Log != null) { Log.LogInfo((object)"[EpicLootAdapter] Rollback atómico ejecutado exitosamente."); } return true; } catch (Exception ex) { if (Log != null) { Log.LogError((object)("[EpicLootAdapter] Error en rollback: " + ex.Message)); } return false; } } } public static bool IsMagicItem(ItemData item) { if (item == null) { return false; } try { Type type = Type.GetType("EpicLoot.API, EpicLoot", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("IsMagicItem", BindingFlags.Static | BindingFlags.Public); if (method != null) { return (bool)method.Invoke(null, new object[1] { item }); } } } catch { } return false; } public static int GetItemRarity(ItemData item) { if (item == null) { return -1; } try { Type type = Type.GetType("EpicLoot.API, EpicLoot", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("TryGetRarity", BindingFlags.Static | BindingFlags.Public); if (method != null) { object[] array = new object[2] { item, 0 }; if ((bool)method.Invoke(null, array) && array[1] is int) { return (int)array[1]; } } } } catch { } return -1; } public static bool ItemHasMagicEffect(ItemData item, string effectType, bool includeSocketed = true) { if (item == null || string.IsNullOrEmpty(effectType)) { return false; } try { Type type = Type.GetType("EpicLoot.API, EpicLoot", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("ItemHasMagicEffect", BindingFlags.Static | BindingFlags.Public); if (method != null) { return (bool)method.Invoke(null, new object[3] { item, effectType, includeSocketed }); } } } catch { } return false; } } public sealed class EpicMmoSnapshot { public DateTime CapturedAtUtc { get; set; } public string FilePath { get; set; } public string ContentHashSha256 { get; set; } public float ExpRate { get; set; } public int MaxLevel { get; set; } public int FreePointsPerLevel { get; set; } public int StartFreePoints { get; set; } public int PriceResetPoints { get; set; } public bool LossExp { get; set; } public float MinLossExp { get; set; } public float MaxLossExp { get; set; } public int MaxValueStrength { get; set; } public int MaxValueDexterity { get; set; } public int MaxValueIntelligence { get; set; } public int MaxValueEndurance { get; set; } public int MaxValueVigour { get; set; } public int MaxValueSpecializing { get; set; } public float PhysicDamage { get; set; } public float PhysicArmor { get; set; } public float AddHp { get; set; } public float AddStamina { get; set; } public float MagicDamage { get; set; } public float CritChance { get; set; } public float CritDmg { get; set; } public bool EnabledLevelControl { get; set; } public bool LowDamageLevel { get; set; } public int MinLevelRange { get; set; } public int MaxLevelRange { get; set; } public string RawCfgContent { get; set; } public EpicMmoSnapshot() { CapturedAtUtc = DateTime.UtcNow; FilePath = string.Empty; ContentHashSha256 = string.Empty; ExpRate = 1f; MaxLevel = 100; FreePointsPerLevel = 5; StartFreePoints = 5; PriceResetPoints = 3; LossExp = true; MinLossExp = 0.05f; MaxLossExp = 0.25f; MaxValueStrength = 200; MaxValueDexterity = 200; MaxValueIntelligence = 200; MaxValueEndurance = 200; MaxValueVigour = 200; MaxValueSpecializing = 200; PhysicDamage = 0.7f; PhysicArmor = 0.25f; AddHp = 1f; AddStamina = 0.9f; MagicDamage = 0.4f; CritChance = 0.5f; CritDmg = 1.5f; EnabledLevelControl = true; LowDamageLevel = false; MinLevelRange = 10; MaxLevelRange = 10; RawCfgContent = string.Empty; } public EpicMmoSnapshot Clone() { EpicMmoSnapshot epicMmoSnapshot = new EpicMmoSnapshot(); epicMmoSnapshot.CapturedAtUtc = CapturedAtUtc; epicMmoSnapshot.FilePath = FilePath; epicMmoSnapshot.ContentHashSha256 = ContentHashSha256; epicMmoSnapshot.ExpRate = ExpRate; epicMmoSnapshot.MaxLevel = MaxLevel; epicMmoSnapshot.FreePointsPerLevel = FreePointsPerLevel; epicMmoSnapshot.StartFreePoints = StartFreePoints; epicMmoSnapshot.PriceResetPoints = PriceResetPoints; epicMmoSnapshot.LossExp = LossExp; epicMmoSnapshot.MinLossExp = MinLossExp; epicMmoSnapshot.MaxLossExp = MaxLossExp; epicMmoSnapshot.MaxValueStrength = MaxValueStrength; epicMmoSnapshot.MaxValueDexterity = MaxValueDexterity; epicMmoSnapshot.MaxValueIntelligence = MaxValueIntelligence; epicMmoSnapshot.MaxValueEndurance = MaxValueEndurance; epicMmoSnapshot.MaxValueVigour = MaxValueVigour; epicMmoSnapshot.MaxValueSpecializing = MaxValueSpecializing; epicMmoSnapshot.PhysicDamage = PhysicDamage; epicMmoSnapshot.PhysicArmor = PhysicArmor; epicMmoSnapshot.AddHp = AddHp; epicMmoSnapshot.AddStamina = AddStamina; epicMmoSnapshot.MagicDamage = MagicDamage; epicMmoSnapshot.CritChance = CritChance; epicMmoSnapshot.CritDmg = CritDmg; epicMmoSnapshot.EnabledLevelControl = EnabledLevelControl; epicMmoSnapshot.LowDamageLevel = LowDamageLevel; epicMmoSnapshot.MinLevelRange = MinLevelRange; epicMmoSnapshot.MaxLevelRange = MaxLevelRange; epicMmoSnapshot.RawCfgContent = RawCfgContent; return epicMmoSnapshot; } } public sealed class EpicMmoResult { public bool Success { get; private set; } public string ErrorMessage { get; private set; } public EpicMmoSnapshot Snapshot { get; private set; } private EpicMmoResult() { } public static EpicMmoResult Ok(EpicMmoSnapshot snapshot) { EpicMmoResult epicMmoResult = new EpicMmoResult(); epicMmoResult.Success = true; epicMmoResult.ErrorMessage = string.Empty; epicMmoResult.Snapshot = snapshot; return epicMmoResult; } public static EpicMmoResult Fail(string reason, EpicMmoSnapshot snapshot = null) { EpicMmoResult epicMmoResult = new EpicMmoResult(); epicMmoResult.Success = false; epicMmoResult.ErrorMessage = reason ?? "Unknown EpicMMO adapter failure"; epicMmoResult.Snapshot = snapshot; return epicMmoResult; } } public static class EpicMMOAdapter { public const string EpicMmoPluginGuid = "WackyMole.EpicMMOSystem"; public const string EpicMmoConfigFileName = "WackyMole.EpicMMOSystem.cfg"; private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.EpicMMOAdapter"); private static string s_customConfigPath = null; private static EpicMmoSnapshot s_baselineSnapshot = null; private static readonly object s_fileLock = new object(); public static bool IsInstalled { get { try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("WackyMole.EpicMMOSystem")) { return true; } } catch { } try { Type type = Type.GetType("EpicMMOSystem.EpicMMOSystem, EpicMMOSystem", throwOnError: false); if (type != null) { return true; } } catch { } return false; } } public static bool IsConfigFileAvailable { get { try { string configFilePath = GetConfigFilePath(); return !string.IsNullOrEmpty(configFilePath) && File.Exists(configFilePath); } catch { return false; } } } public static bool IsAvailable { get { if (!IsInstalled) { return IsConfigFileAvailable; } return true; } } public static void SetCustomConfigPathForTesting(string path) { s_customConfigPath = path; s_baselineSnapshot = null; } public static void ResetConfigPath() { s_customConfigPath = null; s_baselineSnapshot = null; } public static string GetConfigFilePath() { if (!string.IsNullOrEmpty(s_customConfigPath)) { return s_customConfigPath; } try { string configPath = Paths.ConfigPath; if (!string.IsNullOrEmpty(configPath)) { return Path.Combine(configPath, "WackyMole.EpicMMOSystem.cfg"); } } catch { } return Path.Combine(Directory.GetCurrentDirectory(), "WackyMole.EpicMMOSystem.cfg"); } private static bool HasRef(Object obj) { return !object.ReferenceEquals(obj, null); } public static bool HasAuthority() { if (!HasRef((Object)(object)ZNet.instance)) { return true; } try { return ZNet.instance.IsServer(); } catch { } return true; } public static string ComputeSha256(string content) { if (content == null) { return string.Empty; } using SHA256 sHA = SHA256.Create(); byte[] bytes = Encoding.UTF8.GetBytes(content); byte[] array = sHA.ComputeHash(bytes); StringBuilder stringBuilder = new StringBuilder(array.Length * 2); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("X2")); } return stringBuilder.ToString(); } public static EpicMmoSnapshot CaptureCurrentState() { lock (s_fileLock) { string configFilePath = GetConfigFilePath(); EpicMmoSnapshot epicMmoSnapshot = new EpicMmoSnapshot(); epicMmoSnapshot.FilePath = configFilePath; epicMmoSnapshot.CapturedAtUtc = DateTime.UtcNow; EpicMmoSnapshot epicMmoSnapshot2 = epicMmoSnapshot; if (File.Exists(configFilePath)) { try { string content = (epicMmoSnapshot2.RawCfgContent = File.ReadAllText(configFilePath, Encoding.UTF8)); epicMmoSnapshot2.ContentHashSha256 = ComputeSha256(content); ParseCfgContent(content, epicMmoSnapshot2); } catch (Exception ex) { if (Log != null) { Log.LogWarning((object)$"[EpicMMOAdapter] Error leyendo archivo de config {configFilePath}: {ex.Message}"); } } } OverlayLiveMemoryValues(epicMmoSnapshot2); if (s_baselineSnapshot == null) { s_baselineSnapshot = epicMmoSnapshot2.Clone(); } return epicMmoSnapshot2; } } private static void ParseCfgContent(string content, EpicMmoSnapshot snap) { if (string.IsNullOrEmpty(content) || snap == null) { return; } string[] array = content.Split(new string[3] { "\r\n", "\r", "\n" }, StringSplitOptions.None); string text = string.Empty; string[] array2 = array; foreach (string text2 in array2) { string text3 = text2.Trim(); if (text3.StartsWith("[") && text3.EndsWith("]")) { text = text3.Substring(1, text3.Length - 2).Trim(); } else { if (text3.StartsWith("#") || string.IsNullOrEmpty(text3) || !text3.Contains("=")) { continue; } int num = text3.IndexOf('='); string text4 = text3.Substring(0, num).Trim(); string text5 = text3.Substring(num + 1).Trim(); if (text.StartsWith("1.LevelSystem-----------", StringComparison.OrdinalIgnoreCase)) { float result2; bool result3; if (text4.Equals("MaxLevel", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out var result)) { snap.MaxLevel = result; } else if (text4.Equals("FreePointForLevel", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.FreePointsPerLevel = result; } else if (text4.Equals("StartFreePoint", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.StartFreePoints = result; } else if (text4.Equals("PriceResetPoints", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.PriceResetPoints = result; } else if (text4.Equals("RateExp", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result2)) { snap.ExpRate = result2; } else if (text4.Equals("LossExp", StringComparison.OrdinalIgnoreCase) && bool.TryParse(text5, out result3)) { snap.LossExp = result3; } else if (text4.Equals("MinLossExp", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result2)) { snap.MinLossExp = result2; } else if (text4.Equals("MaxLossExp", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result2)) { snap.MaxLossExp = result2; } else if (text4.Equals("maxValueStrength", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.MaxValueStrength = result; } else if (text4.Equals("maxValueDexterity", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.MaxValueDexterity = result; } else if (text4.Equals("maxValueIntelligence", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.MaxValueIntelligence = result; } else if (text4.Equals("maxValueEndurance", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.MaxValueEndurance = result; } else if (text4.Equals("maxValueVigour", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.MaxValueVigour = result; } else if (text4.Equals("maxValueSpecializing", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result)) { snap.MaxValueSpecializing = result; } } else if (text.StartsWith("1.LevelSystem Strength", StringComparison.OrdinalIgnoreCase)) { if (text4.Equals("PhysicDamage", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result4)) { snap.PhysicDamage = result4; } else if (text4.Equals("CriticalDmg", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result4)) { snap.CritDmg = result4; } } else if (text.StartsWith("1.LevelSystem Endurance", StringComparison.OrdinalIgnoreCase)) { if (text4.Equals("PhysicArmor", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result5)) { snap.PhysicArmor = result5; } else if (text4.Equals("AddStamina", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out result5)) { snap.AddStamina = result5; } } else if (text.StartsWith("1.LevelSystem Vigour", StringComparison.OrdinalIgnoreCase)) { if (text4.Equals("AddHp", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result6)) { snap.AddHp = result6; } } else if (text.StartsWith("1.LevelSystem Intellect", StringComparison.OrdinalIgnoreCase)) { if (text4.Equals("MagicAttack", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result7)) { snap.MagicDamage = result7; } } else if (text.StartsWith("1.LevelSystem Specializing", StringComparison.OrdinalIgnoreCase)) { if (text4.Equals("Critical Chance", StringComparison.OrdinalIgnoreCase) && float.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result8)) { snap.CritChance = result8; } } else if (text.StartsWith("2.Creature level control", StringComparison.OrdinalIgnoreCase)) { int result10; if (text4.Equals("Enabled_creature_level", StringComparison.OrdinalIgnoreCase) && bool.TryParse(text5, out var result9)) { snap.EnabledLevelControl = result9; } else if (text4.Equals("Low_damage_level", StringComparison.OrdinalIgnoreCase) && bool.TryParse(text5, out result9)) { snap.LowDamageLevel = result9; } else if (text4.Equals("MinLevelRange", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result10)) { snap.MinLevelRange = result10; } else if (text4.Equals("MaxLevelRange", StringComparison.OrdinalIgnoreCase) && int.TryParse(text5, out result10)) { snap.MaxLevelRange = result10; } } } } } private static void OverlayLiveMemoryValues(EpicMmoSnapshot snap) { if (snap == null) { return; } try { Type type = Type.GetType("EpicMMOSystem.EpicMMOSystem, EpicMMOSystem", throwOnError: false); if (!(type == null)) { snap.ExpRate = GetConfigEntryValue(type, "rateExp", snap.ExpRate); snap.MaxLevel = GetConfigEntryValue(type, "maxLevel", snap.MaxLevel); snap.FreePointsPerLevel = GetConfigEntryValue(type, "freePointForLevel", snap.FreePointsPerLevel); snap.StartFreePoints = GetConfigEntryValue(type, "startFreePoint", snap.StartFreePoints); snap.PriceResetPoints = GetConfigEntryValue(type, "priceResetPoints", snap.PriceResetPoints); snap.LossExp = GetConfigEntryValue(type, "lossExp", snap.LossExp); snap.MinLossExp = GetConfigEntryValue(type, "minLossExp", snap.MinLossExp); snap.MaxLossExp = GetConfigEntryValue(type, "maxLossExp", snap.MaxLossExp); snap.PhysicDamage = GetConfigEntryValue(type, "physicDamage", snap.PhysicDamage); snap.PhysicArmor = GetConfigEntryValue(type, "physicArmor", snap.PhysicArmor); snap.AddHp = GetConfigEntryValue(type, "addHp", snap.AddHp); snap.AddStamina = GetConfigEntryValue(type, "addStamina", snap.AddStamina); snap.MagicDamage = GetConfigEntryValue(type, "magicDamage", snap.MagicDamage); snap.CritChance = GetConfigEntryValue(type, "critChance", snap.CritChance); snap.CritDmg = GetConfigEntryValue(type, "critDmg", snap.CritDmg); snap.EnabledLevelControl = GetConfigEntryValue(type, "enabledLevelControl", snap.EnabledLevelControl); snap.LowDamageLevel = GetConfigEntryValue(type, "lowDamageLevel", snap.LowDamageLevel); snap.MinLevelRange = GetConfigEntryValue(type, "minLevelExp", snap.MinLevelRange); snap.MaxLevelRange = GetConfigEntryValue(type, "maxLevelExp", snap.MaxLevelRange); } } catch { } } private static T GetConfigEntryValue(Type pluginType, string fieldName, T fallback) { try { FieldInfo field = pluginType.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(null); if (value != null) { PropertyInfo property = value.GetType().GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); if (property != null) { object value2 = property.GetValue(value, null); if (value2 is T) { return (T)value2; } } } } } catch { } return fallback; } private static void SetConfigEntryValue(Type pluginType, string fieldName, T newValue) { try { FieldInfo field = pluginType.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (!(field != null)) { return; } object value = field.GetValue(null); if (value != null) { PropertyInfo property = value.GetType().GetProperty("Value", BindingFlags.Instance | BindingFlags.Public); if (property != null && property.CanWrite) { property.SetValue(value, newValue, null); } } } catch { } } public static bool TryUpdateIniContent(string originalContent, float expRate, int maxLevel, int freePoints, bool lowDamageLevel, float physicDamage, float physicArmor, float healthPerPoint, out string modifiedContent) { modifiedContent = originalContent; if (string.IsNullOrEmpty(originalContent)) { return false; } string separator = (originalContent.Contains("\r\n") ? "\r\n" : "\n"); string[] collection = originalContent.Split(new string[3] { "\r\n", "\r", "\n" }, StringSplitOptions.None); List list = new List(collection); string text = string.Empty; for (int i = 0; i < list.Count; i++) { string text2 = list[i].Trim(); if (text2.StartsWith("[") && text2.EndsWith("]")) { text = text2.Substring(1, text2.Length - 2).Trim(); } else { if (text2.StartsWith("#") || string.IsNullOrEmpty(text2) || !text2.Contains("=")) { continue; } int length = list[i].IndexOf('='); string text3 = list[i].Substring(0, length).Trim(); string arg = list[i].Substring(0, list[i].Length - list[i].TrimStart(new char[0]).Length); if (text.StartsWith("1.LevelSystem-----------", StringComparison.OrdinalIgnoreCase)) { if (text3.Equals("RateExp", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, expRate); } else if (text3.Equals("MaxLevel", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2}", arg, text3, maxLevel); } else if (text3.Equals("FreePointForLevel", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2}", arg, text3, freePoints); } } else if (text.StartsWith("1.LevelSystem Strength", StringComparison.OrdinalIgnoreCase)) { if (text3.Equals("PhysicDamage", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, physicDamage); } } else if (text.StartsWith("1.LevelSystem Endurance", StringComparison.OrdinalIgnoreCase)) { if (text3.Equals("PhysicArmor", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, physicArmor); } } else if (text.StartsWith("1.LevelSystem Vigour", StringComparison.OrdinalIgnoreCase)) { if (text3.Equals("AddHp", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2:F2}", arg, text3, healthPerPoint); } } else if (text.StartsWith("2.Creature level control", StringComparison.OrdinalIgnoreCase) && text3.Equals("Low_damage_level", StringComparison.OrdinalIgnoreCase)) { list[i] = string.Format(CultureInfo.InvariantCulture, "{0}{1} = {2}", arg, text3, lowDamageLevel ? "true" : "false"); } } } modifiedContent = string.Join(separator, list.ToArray()); return true; } public static EpicMmoResult SetConfiguration(float expRate, int maxLevel, int freePoints, bool lowDamageLevel, float physicDamage, float physicArmor, float healthPerPoint, string expectedHash = null) { if (!HasAuthority()) { return EpicMmoResult.Fail("Unauthorized: Solo el host/servidor puede modificar la configuración de EpicMMO."); } lock (s_fileLock) { string configFilePath = GetConfigFilePath(); if (!File.Exists(configFilePath)) { if (IsInstalled) { SyncLiveMemory(expRate, maxLevel, freePoints, lowDamageLevel, physicDamage, physicArmor, healthPerPoint); EpicMmoSnapshot snapshot = CaptureCurrentState(); return EpicMmoResult.Ok(snapshot); } return EpicMmoResult.Fail($"Archivo de configuración EpicMMO no encontrado en: {configFilePath}"); } try { string text = File.ReadAllText(configFilePath, Encoding.UTF8); string text2 = ComputeSha256(text); if (!string.IsNullOrEmpty(expectedHash) && !string.Equals(text2, expectedHash, StringComparison.OrdinalIgnoreCase)) { return EpicMmoResult.Fail($"Concurrent modification conflict: expected hash {expectedHash}, but file hash is {text2}."); } if (!TryUpdateIniContent(text, expRate, maxLevel, freePoints, lowDamageLevel, physicDamage, physicArmor, healthPerPoint, out var modifiedContent)) { return EpicMmoResult.Fail("Fallo al mutar quirúrgicamente el archivo WackyMole.EpicMMOSystem.cfg."); } string path = configFilePath + ".bak"; File.WriteAllText(path, text, Encoding.UTF8); File.WriteAllText(configFilePath, modifiedContent, Encoding.UTF8); SyncLiveMemory(expRate, maxLevel, freePoints, lowDamageLevel, physicDamage, physicArmor, healthPerPoint); EpicMmoSnapshot snapshot2 = CaptureCurrentState(); if (Log != null) { Log.LogInfo((object)$"[EpicMMOAdapter] Configuración aplicada: ExpRate={expRate:F2}x, MaxLvl={maxLevel}, Pts/Lvl={freePoints}, LowDmg={lowDamageLevel}, PhysDmg={physicDamage:F2}x, PhysArmor={physicArmor:F2}x, Hp/Pt={healthPerPoint:F2}"); } return EpicMmoResult.Ok(snapshot2); } catch (Exception ex) { return EpicMmoResult.Fail($"Error aplicando configuración EpicMMO: {ex.Message}"); } } } private static void SyncLiveMemory(float expRate, int maxLevel, int freePoints, bool lowDamageLevel, float physicDamage, float physicArmor, float healthPerPoint) { try { Type type = Type.GetType("EpicMMOSystem.EpicMMOSystem, EpicMMOSystem", throwOnError: false); if (type != null) { SetConfigEntryValue(type, "rateExp", expRate); SetConfigEntryValue(type, "maxLevel", maxLevel); SetConfigEntryValue(type, "freePointForLevel", freePoints); SetConfigEntryValue(type, "lowDamageLevel", lowDamageLevel); SetConfigEntryValue(type, "physicDamage", physicDamage); SetConfigEntryValue(type, "physicArmor", physicArmor); SetConfigEntryValue(type, "addHp", healthPerPoint); } } catch { } } public static bool Rollback(EpicMmoSnapshot snapshot) { if (snapshot == null) { return false; } lock (s_fileLock) { try { string configFilePath = GetConfigFilePath(); if (File.Exists(configFilePath) && !string.IsNullOrEmpty(snapshot.RawCfgContent)) { File.WriteAllText(configFilePath, snapshot.RawCfgContent, Encoding.UTF8); } SyncLiveMemory(snapshot.ExpRate, snapshot.MaxLevel, snapshot.FreePointsPerLevel, snapshot.LowDamageLevel, snapshot.PhysicDamage, snapshot.PhysicArmor, snapshot.AddHp); if (Log != null) { Log.LogInfo((object)"[EpicMMOAdapter] Rollback atómico ejecutado exitosamente."); } return true; } catch (Exception ex) { if (Log != null) { Log.LogError((object)("[EpicMMOAdapter] Error en rollback: " + ex.Message)); } return false; } } } public static int QueryLocalPlayerLevel() { try { Type type = Type.GetType("API.EpicMMOSystem_API, EpicMMOSystem", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("GetLevel", BindingFlags.Static | BindingFlags.Public); if (method != null) { return (int)method.Invoke(null, null); } } } catch { } return -1; } public static bool TryQueryLocalPlayerAttribute(string attributeName, out int value) { value = 0; try { Type type = Type.GetType("API.EpicMMOSystem_API, EpicMMOSystem", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("GetAttributeRusty", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null); if (method != null) { object obj = method.Invoke(null, new object[1] { attributeName }); if (obj is int) { value = (int)obj; return true; } } } } catch { } return false; } public static int QueryLocalPlayerAttribute(string attributeName) { try { Type type = Type.GetType("API.EpicMMOSystem_API, EpicMMOSystem", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("GetAttributeRusty", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null); if (method != null) { return (int)method.Invoke(null, new object[1] { attributeName }); } } } catch { } return 0; } } public static class EvolutionAscensionEngine { public sealed class AscensionPendingData { public Player Player; public Character Target; public AscensionRecipe0736 Recipe; public ItemData Item; public int OldTier; public int NewTier; public float OldMaxHp; public float NewMaxHpEstimated; public float HealthRatio; public float OldDmgMult; public float NewDmgMult; public float OldDmgRed; public float NewDmgRed; public float OldSpeedMult; public float NewSpeedMult; public int SpentPoints; public int AvailablePoints; public int BonusPoints; public string TargetName; public string TargetSpecies; public int Level; public int Stars; } private static AscensionPendingData s_pendingModal; private static Texture2D s_boxBg; private static Texture2D s_btnBg; private static GUIStyle s_boxStyle; private static GUIStyle s_titleStyle; private static GUIStyle s_subStyle; private static GUIStyle s_statLabelStyle; private static GUIStyle s_statValueStyle; private static GUIStyle s_confirmBtnStyle; private static GUIStyle s_cancelBtnStyle; private static Func s_getTier; private static Func s_getTierBadge; private static Func s_getTierHpMult; private static Func s_getTierDmgMult; private static Func s_getTierDmgRed; private static Func s_getTierSpeedMult; private static Action s_ensureTierHealthAndScale; private static Func s_getOwner; private static Func s_getPoints; private static Func s_getStat; private static Action s_setTierOverride; private static Action s_emitAudio; private static Action s_refreshVisualAura; public static bool Active { get; private set; } public static bool IsModalOpen => s_pendingModal != null; public static void Init(Harmony harmony, Type coreType) { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown if (Active) { return; } GameObject val = null; try { if (coreType == null) { throw new ArgumentNullException("coreType"); } BindCoreDelegates(coreType.Assembly); MethodInfo methodInfo = AccessTools.Method(typeof(AscensionRuntime0736), "TryItem", new Type[4] { typeof(Player), typeof(Character), typeof(ItemData), typeof(bool).MakeByRefType() }, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(typeof(AscensionRuntime0736).FullName, "TryItem"); } HarmonyMethod val2 = new HarmonyMethod(AccessTools.Method(typeof(EvolutionAscensionEngine), "TryItem_Prefix", (Type[])null, (Type[])null)); harmony.Patch((MethodBase)methodInfo, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); AscensionModalInput.Install(harmony); val = new GameObject("TameMate_EvolutionPreviewModal"); val.AddComponent(); Object.DontDestroyOnLoad((Object)(object)val); Active = true; } catch { Active = false; CloseModal(); ClearCoreBindings(); if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } if (harmony != null) { harmony.UnpatchSelf(); } throw; } } private static Type RequireCoreType(Assembly asm, string name) { Type type = asm.GetType(name); if (type == null) { throw new TypeLoadException("Ascension core type missing: " + name); } return type; } private static MethodInfo RequireCoreMethod(Type type, string name, Type result, params Type[] parameters) { MethodInfo method = type.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null); if (method == null || method.ReturnType != result) { throw new MissingMethodException(type.FullName, name + " (expected static " + result.Name + ")"); } return method; } private static bool CoreBindingsReady() { if (s_getTier != null && s_getTierBadge != null && s_getTierHpMult != null && s_getTierDmgMult != null && s_getTierDmgRed != null && s_getTierSpeedMult != null && s_ensureTierHealthAndScale != null && s_getOwner != null && s_getPoints != null && s_getStat != null) { return s_setTierOverride != null; } return false; } private static void ClearCoreBindings() { s_getTier = null; s_getTierBadge = null; s_getTierHpMult = null; s_getTierDmgMult = null; s_getTierDmgRed = null; s_getTierSpeedMult = null; s_ensureTierHealthAndScale = null; s_getOwner = null; s_getPoints = null; s_getStat = null; s_setTierOverride = null; s_emitAudio = null; s_refreshVisualAura = null; } private static void BindCoreDelegates(Assembly asm) { ClearCoreBindings(); Type type = RequireCoreType(asm, "TameMate.SupremeTierEngine"); Type type2 = RequireCoreType(asm, "TameMate.CompanionState"); Type type3 = RequireCoreType(asm, "TameMate.CreatureTier"); Type type4 = RequireCoreType(asm, "TameMate.CompanionStat"); if (!type3.IsEnum || !type4.IsEnum) { throw new NotSupportedException("Ascension core enum contract changed"); } ParameterExpression parameterExpression = Expression.Parameter(typeof(Character), "c"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(int), "i"); Func func = Expression.Lambda>(Expression.Convert(Expression.Call(RequireCoreMethod(type, "GetTier", type3, typeof(Character)), parameterExpression), typeof(int)), new ParameterExpression[1] { parameterExpression }).Compile(); Func func2 = (Func)Delegate.CreateDelegate(typeof(Func), RequireCoreMethod(type, "GetTierBadge", typeof(string), typeof(Character))); Func func3 = Expression.Lambda>(Expression.Call(RequireCoreMethod(type, "GetTierHealthMultiplier", typeof(float), type3), Expression.Convert(parameterExpression2, type3)), new ParameterExpression[1] { parameterExpression2 }).Compile(); Func func4 = Expression.Lambda>(Expression.Call(RequireCoreMethod(type, "GetTierDamageMultiplier", typeof(float), type3), Expression.Convert(parameterExpression2, type3)), new ParameterExpression[1] { parameterExpression2 }).Compile(); Func func5 = Expression.Lambda>(Expression.Call(RequireCoreMethod(type, "GetTierDamageReduction", typeof(float), type3), Expression.Convert(parameterExpression2, type3)), new ParameterExpression[1] { parameterExpression2 }).Compile(); Func func6 = Expression.Lambda>(Expression.Call(RequireCoreMethod(type, "GetTierSpeedMultiplier", typeof(float), type3), Expression.Convert(parameterExpression2, type3)), new ParameterExpression[1] { parameterExpression2 }).Compile(); Action action = (Action)Delegate.CreateDelegate(typeof(Action), RequireCoreMethod(type, "EnsureTierHealthAndScale", typeof(void), typeof(Character), typeof(bool))); Func func7 = (Func)Delegate.CreateDelegate(typeof(Func), RequireCoreMethod(type2, "Owner", typeof(long), typeof(Character))); Func func8 = (Func)Delegate.CreateDelegate(typeof(Func), RequireCoreMethod(type2, "Points", typeof(int), typeof(Character))); Action action2 = (Action)Delegate.CreateDelegate(typeof(Action), RequireCoreMethod(type2, "SetTierOverride", typeof(void), typeof(Character), typeof(int))); ParameterExpression parameterExpression3 = Expression.Parameter(typeof(int), "s"); Func func9 = Expression.Lambda>(Expression.Call(RequireCoreMethod(type2, "Stat", typeof(int), typeof(Character), type4), parameterExpression, Expression.Convert(parameterExpression3, type4)), new ParameterExpression[2] { parameterExpression, parameterExpression3 }).Compile(); s_getTier = func; s_getTierBadge = func2; s_getTierHpMult = func3; s_getTierDmgMult = func4; s_getTierDmgRed = func5; s_getTierSpeedMult = func6; s_ensureTierHealthAndScale = action; s_getOwner = func7; s_getPoints = func8; s_setTierOverride = action2; s_getStat = func9; try { Type type5 = asm.GetType("TameMate.WhistleAudio"); Type type6 = asm.GetType("TameMate.WhistleKind"); if (type5 != null && type6 != null && type6.IsEnum && Enum.IsDefined(type6, "Confirm")) { s_emitAudio = Expression.Lambda>(Expression.Call(RequireCoreMethod(type5, "Emit", typeof(void), type6), Expression.Constant(Enum.Parse(type6, "Confirm"), type6)), new ParameterExpression[1] { parameterExpression2 }).Compile(); } Type type7 = asm.GetType("TameMate.TierVisualAura"); if (!(type7 != null)) { return; } MethodInfo ensureAura = RequireCoreMethod(type7, "Ensure", type7, typeof(Character)); MethodInfo refresh = type7.GetMethod("RefreshVisuals", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); if (!(refresh != null) || !(refresh.ReturnType == typeof(void))) { return; } s_refreshVisualAura = delegate(Character c) { try { object obj = ensureAura.Invoke(null, new object[1] { c }); if (obj != null) { refresh.Invoke(obj, null); } } catch { } }; } catch (Exception ex) { Debug.LogWarning((object)("[TameMate] Optional ascension presentation unavailable: " + ex.Message)); } } public static int GetBonusPointsForTier(int toTier) { return toTier switch { 2 => 1, 3 => 2, 4 => 2, 5 => 3, 6 => 3, 7 => 4, 8 => 4, 10 => 5, _ => 1, }; } public static bool TryItem_Prefix(Player player, Character target, ItemData item, ref bool result, ref bool __result) { if (!Active || !CoreBindingsReady()) { return true; } string text = ((item == null || (Object)(object)item.m_dropPrefab == (Object)null) ? null : ((Object)item.m_dropPrefab).name); AscensionRecipe0736 val = AscensionCatalogue0736.Find(text); if (val == null && !AscensionCatalogue0736.Retired(text)) { return true; } result = true; __result = true; if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || (Object)(object)target == (Object)null || !target.IsTamed() || item.m_stack < 1) { return false; } if (val == null) { ((Character)player).Message((MessageType)2, "Este elixir está retirado. Cataclísmico y No-muerto se obtienen por sus apariciones especiales.", 0, (Sprite)null, false); return false; } int num = ((s_getTier == null) ? 1 : s_getTier(target)); if (!AscensionCatalogue0736.Allowed(num, val)) { ((Character)player).Message((MessageType)2, $"Este elixir requiere Tier {val.From} ({val.Tier}). Tu criatura conserva su estado.", 0, (Sprite)null, false); return false; } long num2 = ((s_getOwner != null) ? s_getOwner(target) : 0); if (num2 != 0 && num2 != player.GetPlayerID()) { ((Character)player).Message((MessageType)2, "Solo el amo legítimo de esta criatura puede administrarle la ascensión.", 0, (Sprite)null, false); return false; } ZNetView component = ((Component)target).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return false; } if (num2 == player.GetPlayerID() && !component.IsOwner()) { component.ClaimOwnership(); } OpenPreviewModal(player, target, val, item); return false; } public static void OpenPreviewModal(Player player, Character target, AscensionRecipe0736 recipe, ItemData item) { if (!Active || !CoreBindingsReady()) { return; } int num = ((s_getTier == null) ? 1 : s_getTier(target)); int to = recipe.To; float maxHealth = target.GetMaxHealth(); float health = target.GetHealth(); float healthRatio = Mathf.Clamp01(health / Mathf.Max(1f, maxHealth)); float num2 = ((s_getTierHpMult != null) ? s_getTierHpMult(num) : 1f); float num3 = ((s_getTierHpMult != null) ? s_getTierHpMult(to) : 1.35f); float num4 = ((num2 > 0.01f) ? (maxHealth / num2) : maxHealth); float newMaxHpEstimated = num4 * num3; float oldDmgMult = ((s_getTierDmgMult != null) ? s_getTierDmgMult(num) : 1f); float newDmgMult = ((s_getTierDmgMult != null) ? s_getTierDmgMult(to) : 1.25f); float oldDmgRed = ((s_getTierDmgRed != null) ? s_getTierDmgRed(num) : 0f); float newDmgRed = ((s_getTierDmgRed != null) ? s_getTierDmgRed(to) : 0.05f); float oldSpeedMult = ((s_getTierSpeedMult != null) ? s_getTierSpeedMult(num) : 1f); float newSpeedMult = ((s_getTierSpeedMult != null) ? s_getTierSpeedMult(to) : 1.05f); int num5 = 0; if (s_getStat != null) { try { for (int i = 0; i <= 5; i++) { num5 += s_getStat(target, i); } } catch { } } int availablePoints = ((s_getPoints != null) ? s_getPoints(target) : 0); ZNetView component = ((Component)target).GetComponent(); int bonusPoints = ((!((Object)(object)component != (Object)null) || !component.IsValid() || component.GetZDO().GetInt("TM_AscendedTier_" + to, 0) != 1) ? GetBonusPointsForTier(to) : 0); AscensionPendingData ascensionPendingData = new AscensionPendingData(); ascensionPendingData.Player = player; ascensionPendingData.Target = target; ascensionPendingData.Recipe = recipe; ascensionPendingData.Item = item; ascensionPendingData.OldTier = num; ascensionPendingData.NewTier = to; ascensionPendingData.OldMaxHp = maxHealth; ascensionPendingData.NewMaxHpEstimated = newMaxHpEstimated; ascensionPendingData.HealthRatio = healthRatio; ascensionPendingData.OldDmgMult = oldDmgMult; ascensionPendingData.NewDmgMult = newDmgMult; ascensionPendingData.OldDmgRed = oldDmgRed; ascensionPendingData.NewDmgRed = newDmgRed; ascensionPendingData.OldSpeedMult = oldSpeedMult; ascensionPendingData.NewSpeedMult = newSpeedMult; ascensionPendingData.SpentPoints = num5; ascensionPendingData.AvailablePoints = availablePoints; ascensionPendingData.BonusPoints = bonusPoints; ascensionPendingData.TargetName = target.GetHoverName(); ascensionPendingData.TargetSpecies = target.m_name; ascensionPendingData.Level = target.GetLevel(); ascensionPendingData.Stars = Mathf.Max(0, target.GetLevel() - 1); s_pendingModal = ascensionPendingData; AscensionModalInput.Acquire(player); } public static void CloseModal() { s_pendingModal = null; AscensionModalInput.Release(); } public static void UpdateModalInput() { AscensionPendingData ascensionPendingData = s_pendingModal; if (ascensionPendingData == null) { return; } if (!Active || (Object)(object)ascensionPendingData.Player == (Object)null || (Object)(object)ascensionPendingData.Player != (Object)(object)Player.m_localPlayer || ((Character)ascensionPendingData.Player).IsDead() || ((Character)ascensionPendingData.Player).IsTeleporting() || (Object)(object)ascensionPendingData.Target == (Object)null || ascensionPendingData.Target.IsDead()) { CloseModal(); return; } AscensionModalInput.ShowCursor(); if (Input.GetKeyDown((KeyCode)27)) { CloseModal(); } } public static void ConfirmAscension() { if (s_pendingModal == null) { return; } AscensionPendingData ascensionPendingData = s_pendingModal; CloseModal(); if ((Object)(object)ascensionPendingData.Player == (Object)null || (Object)(object)ascensionPendingData.Target == (Object)null || ascensionPendingData.Target.IsDead()) { return; } if (!Active || !CoreBindingsReady()) { Debug.LogWarning((object)"[TameMate] Ascension not confirmed: core bindings unavailable; elixir retained."); } else { if ((Object)(object)ascensionPendingData.Player != (Object)(object)Player.m_localPlayer || !ascensionPendingData.Target.IsTamed() || ascensionPendingData.Recipe == null || !AscensionCatalogue0736.Allowed(s_getTier(ascensionPendingData.Target), ascensionPendingData.Recipe)) { return; } long num = s_getOwner(ascensionPendingData.Target); if (num != 0 && num != ascensionPendingData.Player.GetPlayerID()) { return; } ZNetView component = ((Component)ascensionPendingData.Target).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } if (!component.IsOwner() && num == ascensionPendingData.Player.GetPlayerID()) { component.ClaimOwnership(); } if (component.IsOwner() && ((Humanoid)ascensionPendingData.Player).GetInventory().GetAllItems().Contains(ascensionPendingData.Item)) { if (!((Humanoid)ascensionPendingData.Player).GetInventory().RemoveItem(ascensionPendingData.Item, 1)) { ((Character)ascensionPendingData.Player).Message((MessageType)2, "No se encontró el elixir requerido en el inventario.", 0, (Sprite)null, false); } else { PerformAtomicAscension(ascensionPendingData.Target, ascensionPendingData.Recipe, ascensionPendingData.Player, ascensionPendingData.HealthRatio, ascensionPendingData.BonusPoints); } } } } public static void PerformAtomicAscension(Character target, AscensionRecipe0736 recipe, Player player, float healthRatio, int bonusPoints) { if (!Active || !CoreBindingsReady()) { return; } ZNetView component = ((Component)target).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } if (!component.IsOwner()) { component.ClaimOwnership(); } if (s_setTierOverride != null) { s_setTierOverride(target, recipe.To); } string text = "TM_AscendedTier_" + recipe.To; bool flag = component.GetZDO().GetInt(text, 0) == 1; int num = 0; if (!flag && bonusPoints > 0) { int num2 = Mathf.Max(0, (s_getPoints != null) ? s_getPoints(target) : component.GetZDO().GetInt("tm_points", 0)); component.GetZDO().Set("tm_points", num2 + bonusPoints); int num3 = Mathf.Max(0, component.GetZDO().GetInt("TM_TotalPointsEarned", 0)); component.GetZDO().Set("TM_TotalPointsEarned", num3 + bonusPoints); component.GetZDO().Set(text, 1); num = bonusPoints; } string text2 = component.GetZDO().GetString("TM_EvolutionHistory", ""); string text3 = $"[{DateTime.UtcNow:yyyy-MM-dd HH:mm}] {recipe.From}->{recipe.To} ({recipe.Tier})"; text2 = ((!string.IsNullOrEmpty(text2)) ? (text2 + " | " + text3) : text3); component.GetZDO().Set("TM_EvolutionHistory", text2); if (s_ensureTierHealthAndScale != null) { s_ensureTierHealthAndScale(target, arg2: true); } float maxHealth = target.GetMaxHealth(); float num4 = Mathf.Clamp(maxHealth * healthRatio, 1f, maxHealth); target.SetHealth(num4); try { if (s_emitAudio != null) { s_emitAudio(0); } } catch { } try { if (s_refreshVisualAura != null) { s_refreshVisualAura(target); } } catch { } string text4 = ((s_getTierBadge != null) ? s_getTierBadge(target) : ("Tier " + recipe.To)); string text5 = string.Format("¡{0} ha ascendido a {1}!\nSalud: {2:F0}/{3:F0} ({4:F0}%)\n{5}", target.GetHoverName(), text4, num4, maxHealth, healthRatio * 100f, (num > 0) ? $"Puntos ganados: +{num} (Pulsa U para asignar)" : "Puntos preservados."); if ((Object)(object)player != (Object)null) { ((Character)player).Message((MessageType)2, text5, 0, (Sprite)null, false); } Debug.Log((object)$"[TameMate] Ascension completed: {target.GetHoverName()} -> Tier {recipe.To} ({recipe.Tier}). Proportional HP: {num4:F0}/{maxHealth:F0}. Bonus Points: +{num}."); } public static void DrawModalGUI() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Invalid comparison between Unknown and I4 //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_0112: 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_054f: Unknown result type (might be due to invalid IL or missing references) //IL_0555: Invalid comparison between Unknown and I4 //IL_055c: Unknown result type (might be due to invalid IL or missing references) //IL_0563: Invalid comparison between Unknown and I4 if (s_pendingModal == null) { return; } AscensionPendingData ascensionPendingData = s_pendingModal; if ((Object)(object)ascensionPendingData.Target == (Object)null || ascensionPendingData.Target.IsDead()) { CloseModal(); return; } if ((int)Event.current.type == 4 && AscensionModalInput.HandleKey(Event.current.keyCode)) { Event.current.Use(); if (!IsModalOpen) { return; } } EnsureStyles(); float num = 540f; float num2 = 480f; float num3 = ((float)Screen.width - num) * 0.5f; float num4 = ((float)Screen.height - num2) * 0.5f; GUI.color = new Color(0f, 0f, 0f, 0.75f); GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)Texture2D.whiteTexture); GUI.color = Color.white; GUI.Box(new Rect(num3, num4, num, num2), GUIContent.none, s_boxStyle); GUILayout.BeginArea(new Rect(num3 + 24f, num4 + 20f, num - 48f, num2 - 40f)); GUILayout.Label("\ud83d\udd2e ASCENSIÓN EVOLUTIVA", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); string arg = ((ascensionPendingData.Stars > 0) ? new string('★', ascensionPendingData.Stars) : ""); GUILayout.Label($"{ascensionPendingData.TargetName} {arg} · Nivel {ascensionPendingData.Level}", s_subStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(12f); string arg2 = ((s_getTierBadge != null) ? s_getTierBadge(ascensionPendingData.Target) : ("Tier " + ascensionPendingData.OldTier)); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"Tier Actual: {arg2}", s_statLabelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("➔", s_statLabelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(25f) }); GUILayout.Label($"Nuevo Tier: Tier {ascensionPendingData.Recipe.To} [{ascensionPendingData.Recipe.Tier}]", s_statValueStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); GUILayout.Space(8f); DrawSeparator(); GUILayout.Space(8f); DrawStatRow("Salud Máxima:", $"{ascensionPendingData.OldMaxHp:F0} HP", $"➔ {ascensionPendingData.NewMaxHpEstimated:F0} HP", "#00FF7F"); DrawStatRow("Salud Proporcional:", $"{ascensionPendingData.HealthRatio * 100f:F0}% ({ascensionPendingData.OldMaxHp * ascensionPendingData.HealthRatio:F0} HP)", $"➔ {ascensionPendingData.HealthRatio * 100f:F0}% ({ascensionPendingData.NewMaxHpEstimated * ascensionPendingData.HealthRatio:F0} HP)", "#00E5FF"); DrawStatRow("Multiplicador Daño:", $"{ascensionPendingData.OldDmgMult * 100f:F0}%", $"➔ {ascensionPendingData.NewDmgMult * 100f:F0}%", "#FFD700"); DrawStatRow("Mitigación Daño:", $"{ascensionPendingData.OldDmgRed * 100f:F0}%", $"➔ {ascensionPendingData.NewDmgRed * 100f:F0}%", "#FF9933"); DrawStatRow("Velocidad:", $"{ascensionPendingData.OldSpeedMult * 100f:F0}%", $"➔ {ascensionPendingData.NewSpeedMult * 100f:F0}%", "#E0B0FF"); GUILayout.Space(8f); DrawSeparator(); GUILayout.Space(8f); GUILayout.Label("ASIGNACIÓN Y PUNTOS DE ATRIBUTO:", s_subStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); DrawPointRow("• Puntos invertidos (Conservados al 100%):", $"{ascensionPendingData.SpentPoints} pts"); DrawPointRow("• Puntos disponibles actuales:", $"{ascensionPendingData.AvailablePoints} pts"); DrawPointRow("• Bonificación Rúnica por Ascensión:", $"+{ascensionPendingData.BonusPoints} pts", "#FFD700"); DrawPointRow("• Total disponible tras ascender:", $"{ascensionPendingData.AvailablePoints + ascensionPendingData.BonusPoints} pts", "#00FF7F"); GUILayout.FlexibleSpace(); GUILayout.Label("Ratón: clic · Tab / ← →: elegir · Intro: aceptar · Esc: cancelar", s_subStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.SetNextControlName("TM_AscensionConfirm"); if (GUILayout.Button("★ CONFIRMAR ASCENSIÓN", s_confirmBtnStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(42f) })) { ConfirmAscension(); } GUILayout.Space(16f); GUI.SetNextControlName("TM_AscensionCancel"); if (GUILayout.Button("✖ CANCELAR", s_cancelBtnStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(42f) })) { CloseModal(); } GUILayout.EndHorizontal(); GUI.FocusControl(AscensionModalInput.ConfirmSelected ? "TM_AscensionConfirm" : "TM_AscensionCancel"); GUILayout.EndArea(); if ((int)Event.current.type == 4 && (int)Event.current.keyCode == 27) { CloseModal(); Event.current.Use(); } } private static void DrawStatRow(string label, string before, string after, string colorHex) { GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(label, s_statLabelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUILayout.Label(before, s_statLabelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); GUILayout.Label($"{after}", s_statValueStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); } private static void DrawPointRow(string label, string value, string colorHex = null) { GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(label, s_statLabelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); if (colorHex != null) { GUILayout.Label($"{value}", s_statValueStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); } else { GUILayout.Label($"{value}", s_statValueStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); } GUILayout.EndHorizontal(); } private static void DrawSeparator() { //IL_0014: 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) GUI.color = new Color(0.8f, 0.7f, 0.4f, 0.35f); GUILayout.Box(GUIContent.none, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Height(1f), GUILayout.ExpandWidth(true) }); GUI.color = Color.white; } private static void EnsureStyles() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_0034: 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_0061: Expected O, but got Unknown //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Expected O, but got Unknown //IL_01a9: 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_01ca: Expected O, but got Unknown //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Expected O, but got Unknown //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Expected O, but got Unknown //IL_02c7: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)s_boxBg == (Object)null) { s_boxBg = new Texture2D(1, 1); s_boxBg.SetPixel(0, 0, new Color(0.08f, 0.09f, 0.12f, 0.96f)); s_boxBg.Apply(); } if ((Object)(object)s_btnBg == (Object)null) { s_btnBg = new Texture2D(1, 1); s_btnBg.SetPixel(0, 0, new Color(0.18f, 0.22f, 0.28f, 0.9f)); s_btnBg.Apply(); } if (s_boxStyle == null) { s_boxStyle = new GUIStyle(GUI.skin.box); s_boxStyle.normal.background = s_boxBg; } if (s_titleStyle == null) { GUIStyle val = new GUIStyle(GUI.skin.label); val.fontSize = 20; val.fontStyle = (FontStyle)1; val.alignment = (TextAnchor)4; s_titleStyle = val; s_titleStyle.normal.textColor = new Color(1f, 0.85f, 0.3f); } if (s_subStyle == null) { GUIStyle val2 = new GUIStyle(GUI.skin.label); val2.fontSize = 13; val2.fontStyle = (FontStyle)0; val2.alignment = (TextAnchor)4; s_subStyle = val2; s_subStyle.normal.textColor = new Color(0.8f, 0.85f, 0.9f); } if (s_statLabelStyle == null) { GUIStyle val3 = new GUIStyle(GUI.skin.label); val3.fontSize = 13; s_statLabelStyle = val3; s_statLabelStyle.normal.textColor = new Color(0.85f, 0.85f, 0.85f); } if (s_statValueStyle == null) { GUIStyle val4 = new GUIStyle(GUI.skin.label); val4.fontSize = 13; val4.alignment = (TextAnchor)5; s_statValueStyle = val4; s_statValueStyle.normal.textColor = Color.white; } if (s_confirmBtnStyle == null) { GUIStyle val5 = new GUIStyle(GUI.skin.button); val5.fontSize = 14; val5.fontStyle = (FontStyle)1; val5.alignment = (TextAnchor)4; s_confirmBtnStyle = val5; s_confirmBtnStyle.normal.background = s_btnBg; s_confirmBtnStyle.normal.textColor = new Color(0.2f, 1f, 0.4f); } if (s_cancelBtnStyle == null) { GUIStyle val6 = new GUIStyle(GUI.skin.button); val6.fontSize = 14; val6.fontStyle = (FontStyle)1; val6.alignment = (TextAnchor)4; s_cancelBtnStyle = val6; s_cancelBtnStyle.normal.background = s_btnBg; s_cancelBtnStyle.normal.textColor = new Color(1f, 0.4f, 0.4f); } } } public sealed class EvolutionPreviewModalComponent : MonoBehaviour { private void Update() { EvolutionAscensionEngine.UpdateModalInput(); } private void OnDisable() { EvolutionAscensionEngine.CloseModal(); } private void OnDestroy() { EvolutionAscensionEngine.CloseModal(); } private void OnGUI() { EvolutionAscensionEngine.DrawModalGUI(); } } [Flags] public enum ExternalProviderCapabilities { None = 0, WorldDifficulty = 1, CreatureScaling = 2, ProgressionAttributes = 4, MagicAffixes = 8, LootScaling = 0x10, CustomPrefabs = 0x20, BossMechanics = 0x40, EnginePerformance = 0x80 } public enum ProviderResponsibility { ConfigurableByTameMate, ReadOnlyDataProvider, PassiveCoexistence, Exclusive, Cumulative, ConflictDetected, Unsupported } public struct CombatCalculationContext { public float BasePlayerDamage; public float BaseCreatureHealth; public float BaseCreatureDamage; public float PlayerDamageRate; public float EnemyDamageRate; public float EnemyHealthRate; public int CreatureStars; public float HealthMultiplierPerStar; public float DamageMultiplierPerStar; public int PlayerStrengthPoints; public float PhysicalDamagePerPoint; public int PlayerEndurancePoints; public float ArmorPerPoint; public int PlayerVigorPoints; public float HealthPerPoint; public bool LowDamageLevelPenaltyActive; public float LevelPenaltyFactor; public float EpicLootDamageBonusPercent; public float EpicLootArmorFlatBonus; public float EpicLootHealthFlatBonus; public float BossHealthMultiplier; public float BossAttackSpeedMultiplier; public bool HasCustomPrefabProvider; public string CustomPrefabProviderName; public static CombatCalculationContext CreateDefault() { return new CombatCalculationContext { BasePlayerDamage = 50f, BaseCreatureHealth = 100f, BaseCreatureDamage = 30f, PlayerDamageRate = 1f, EnemyDamageRate = 1f, EnemyHealthRate = 1f, CreatureStars = 0, HealthMultiplierPerStar = 1f, DamageMultiplierPerStar = 0.5f, PlayerStrengthPoints = 0, PhysicalDamagePerPoint = 0.7f, PlayerEndurancePoints = 0, ArmorPerPoint = 0.25f, PlayerVigorPoints = 0, HealthPerPoint = 1f, LowDamageLevelPenaltyActive = false, LevelPenaltyFactor = 0.1f, EpicLootDamageBonusPercent = 0f, EpicLootArmorFlatBonus = 0f, EpicLootHealthFlatBonus = 0f, BossHealthMultiplier = 1f, BossAttackSpeedMultiplier = 1f, HasCustomPrefabProvider = false, CustomPrefabProviderName = string.Empty }; } public float CalculateEffectivePlayerDamage() { float num = BasePlayerDamage * PlayerDamageRate; float val = 1f + (float)PlayerStrengthPoints * (PhysicalDamagePerPoint / 100f); num *= Math.Max(0.1f, val); float val2 = 1f + EpicLootDamageBonusPercent; num *= Math.Max(0.1f, val2); if (LowDamageLevelPenaltyActive) { num *= Math.Max(0.01f, LevelPenaltyFactor); } return Math.Max(1f, num); } public float CalculateEffectiveCreatureHealth() { float num = BaseCreatureHealth * EnemyHealthRate; float val = 1f + (float)CreatureStars * HealthMultiplierPerStar; num *= Math.Max(0.1f, val); return Math.Max(1f, num); } public float CalculateEffectiveBossHealth(bool isBoss) { float num = CalculateEffectiveCreatureHealth(); if (isBoss && BossHealthMultiplier > 0.01f) { num *= BossHealthMultiplier; } return Math.Max(1f, num); } public float CalculateEffectiveCreatureDamage() { float num = BaseCreatureDamage * EnemyDamageRate; float val = 1f + (float)CreatureStars * DamageMultiplierPerStar; num *= Math.Max(0.1f, val); return Math.Max(1f, num); } public float SimulateTimeToKill(float attacksPerSecond) { return SimulateTimeToKill(attacksPerSecond, isBoss: false); } public float SimulateTimeToKill(float attacksPerSecond, bool isBoss) { if (attacksPerSecond <= 0.001f) { return 9999f; } float num = CalculateEffectivePlayerDamage(); float num2 = (isBoss ? CalculateEffectiveBossHealth(isBoss: true) : CalculateEffectiveCreatureHealth()); float val = num * attacksPerSecond; return num2 / Math.Max(1f, val); } public bool DetectMultiplierConflict(out string conflictDescription) { if (BossHealthMultiplier > 1.05f && EnemyHealthRate > 1.05f && CreatureStars > 0) { conflictDescription = $"SLS + BossAdd + Dificultad Vanilla: Multiplicación compuesta acumulativa detectada (BossAdd={BossHealthMultiplier:F2}x, VanillaHP={EnemyHealthRate:F2}x, Estrellas={CreatureStars}★)."; return true; } if (BossHealthMultiplier > 1.5f && EnemyHealthRate > 1.5f) { conflictDescription = $"BossAdd + Vanilla: Escalado de salud extrema en jefes detectado ({BossHealthMultiplier:F2}x * {EnemyHealthRate:F2}x = {BossHealthMultiplier * EnemyHealthRate:F2}x base)."; return true; } conflictDescription = string.Empty; return false; } } public interface IExternalStatProvider { string ProviderId { get; } string DisplayName { get; } bool IsActive { get; } ExternalProviderCapabilities Capabilities { get; } ProviderResponsibility Responsibility { get; } void CollectModifiers(ref CombatCalculationContext context); } public sealed class VanillaWorldStatProvider : IExternalStatProvider { public string ProviderId => "VanillaWorld"; public string DisplayName => "Valheim Vanilla World Modifiers"; public bool IsActive => VanillaWorldAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.WorldDifficulty; public ProviderResponsibility Responsibility => ProviderResponsibility.ConfigurableByTameMate; public void CollectModifiers(ref CombatCalculationContext context) { VanillaWorldSnapshot vanillaWorldSnapshot = VanillaWorldAdapter.CaptureCurrentState(); context.PlayerDamageRate = vanillaWorldSnapshot.PlayerDamageRate; context.EnemyDamageRate = vanillaWorldSnapshot.EnemyDamageRate; } } public sealed class SlsStatProvider : IExternalStatProvider { public string ProviderId => "MidnightsFX.StarLevelSystem"; public string DisplayName => "StarLevelSystem"; public bool IsActive => StarLevelSystemAdapter.IsConfigFileAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.CreatureScaling; public ProviderResponsibility Responsibility => ProviderResponsibility.ConfigurableByTameMate; public void CollectModifiers(ref CombatCalculationContext context) { SlsConfigSnapshot slsConfigSnapshot = StarLevelSystemAdapter.CaptureCurrentState(); context.HealthMultiplierPerStar = slsConfigSnapshot.StarHealthMultiplier; context.DamageMultiplierPerStar = slsConfigSnapshot.StarDamageMultiplier; } } public sealed class CllcStatProvider : IExternalStatProvider { public const string CllcPluginGuid = "org.bepinex.plugins.creaturelevelcontrol"; public string ProviderId => "SmoothBrain.CreatureLevelControl"; public string DisplayName => "CreatureLevelControl"; public bool IsActive { get { try { if (Chainloader.PluginInfos != null && (Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.creaturelevelcontrol") || Chainloader.PluginInfos.ContainsKey(ProviderId))) { return true; } } catch { } return false; } } public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.CreatureScaling; public ProviderResponsibility Responsibility => ProviderResponsibility.ReadOnlyDataProvider; public void CollectModifiers(ref CombatCalculationContext context) { } } public sealed class EpicMmoStatProvider : IExternalStatProvider { public string ProviderId => "WackyMole.EpicMMOSystem"; public string DisplayName => "EpicMMOSystem"; public bool IsActive => EpicMMOAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.ProgressionAttributes; public ProviderResponsibility Responsibility => ProviderResponsibility.ConfigurableByTameMate; public void CollectModifiers(ref CombatCalculationContext context) { EpicMmoSnapshot epicMmoSnapshot = EpicMMOAdapter.CaptureCurrentState(); context.PhysicalDamagePerPoint = epicMmoSnapshot.PhysicDamage; context.ArmorPerPoint = epicMmoSnapshot.PhysicArmor; context.HealthPerPoint = epicMmoSnapshot.AddHp; context.LowDamageLevelPenaltyActive = epicMmoSnapshot.LowDamageLevel; } } public sealed class EpicLootStatProvider : IExternalStatProvider { public string ProviderId => "randyknapp.mods.epicloot"; public string DisplayName => "EpicLoot"; public bool IsActive => EpicLootAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.MagicAffixes | ExternalProviderCapabilities.LootScaling; public ProviderResponsibility Responsibility => ProviderResponsibility.ConfigurableByTameMate; public void CollectModifiers(ref CombatCalculationContext context) { EpicLootAdapter.CaptureCurrentState(); } } public sealed class MonsterDbStatProvider : IExternalStatProvider { public string ProviderId => "RustyMods.MonsterDB"; public string DisplayName => "MonsterDB (RustyMods)"; public bool IsActive => MonsterDbAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.CreatureScaling | ExternalProviderCapabilities.CustomPrefabs; public ProviderResponsibility Responsibility => ProviderResponsibility.ReadOnlyDataProvider; public void CollectModifiers(ref CombatCalculationContext context) { if (IsActive) { context.HasCustomPrefabProvider = true; context.CustomPrefabProviderName = "MonsterDB"; } } } public sealed class BossAddStatProvider : IExternalStatProvider { public string ProviderId => "bossadd"; public string DisplayName => "BossAdd"; public bool IsActive => BossAddAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.CreatureScaling | ExternalProviderCapabilities.BossMechanics; public ProviderResponsibility Responsibility => ProviderResponsibility.Cumulative; public void CollectModifiers(ref CombatCalculationContext context) { if (IsActive) { BossAddSnapshot bossAddSnapshot = BossAddAdapter.CaptureCurrentState(); context.BossHealthMultiplier = bossAddSnapshot.BonemassHealthMultiplier; context.BossAttackSpeedMultiplier = bossAddSnapshot.BonemassAttackSpeedMultiplier; } } } public sealed class EnhancedEditionStatProvider : IExternalStatProvider { public string ProviderId => "com.chase.valheimenhancededition"; public string DisplayName => "Valheim Enhanced Edition"; public bool IsActive => EnhancedEditionAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.EnginePerformance; public ProviderResponsibility Responsibility => ProviderResponsibility.PassiveCoexistence; public void CollectModifiers(ref CombatCalculationContext context) { } } public static class ExternalStatCatalog { private static readonly List s_providers; private static readonly object s_lock; static ExternalStatCatalog() { s_providers = new List(); s_lock = new object(); RegisterProvider(new VanillaWorldStatProvider()); RegisterProvider(new SlsStatProvider()); RegisterProvider(new CllcStatProvider()); RegisterProvider(new EpicMmoStatProvider()); RegisterProvider(new EpicLootStatProvider()); RegisterProvider(new MonsterDbStatProvider()); RegisterProvider(new BossAddStatProvider()); RegisterProvider(new EnhancedEditionStatProvider()); } public static void RegisterProvider(IExternalStatProvider provider) { if (provider == null) { return; } lock (s_lock) { for (int i = 0; i < s_providers.Count; i++) { if (string.Equals(s_providers[i].ProviderId, provider.ProviderId, StringComparison.OrdinalIgnoreCase)) { s_providers[i] = provider; return; } } s_providers.Add(provider); } } public static bool UnregisterProvider(string providerId) { if (string.IsNullOrEmpty(providerId)) { return false; } lock (s_lock) { for (int i = 0; i < s_providers.Count; i++) { if (string.Equals(s_providers[i].ProviderId, providerId, StringComparison.OrdinalIgnoreCase)) { s_providers.RemoveAt(i); return true; } } } return false; } public static IExternalStatProvider GetProvider(string providerId) { if (string.IsNullOrEmpty(providerId)) { return null; } lock (s_lock) { for (int i = 0; i < s_providers.Count; i++) { if (string.Equals(s_providers[i].ProviderId, providerId, StringComparison.OrdinalIgnoreCase) || string.Equals(s_providers[i].DisplayName, providerId, StringComparison.OrdinalIgnoreCase)) { return s_providers[i]; } } if (providerId.Equals("SLS", StringComparison.OrdinalIgnoreCase) || providerId.Equals("StarLevelSystem", StringComparison.OrdinalIgnoreCase) || providerId.Equals("MidnightsFX.StarLevelSystem", StringComparison.OrdinalIgnoreCase)) { for (int j = 0; j < s_providers.Count; j++) { if (s_providers[j] is SlsStatProvider) { return s_providers[j]; } } } if (providerId.Equals("CLLC", StringComparison.OrdinalIgnoreCase) || providerId.Equals("CreatureLevelControl", StringComparison.OrdinalIgnoreCase) || providerId.Equals("org.bepinex.plugins.creaturelevelcontrol", StringComparison.OrdinalIgnoreCase) || providerId.Equals("SmoothBrain.CreatureLevelControl", StringComparison.OrdinalIgnoreCase)) { for (int k = 0; k < s_providers.Count; k++) { if (s_providers[k] is CllcStatProvider) { return s_providers[k]; } } } } return null; } public static List GetAllProviders() { lock (s_lock) { return new List(s_providers); } } public static List GetActiveProviders() { List list = new List(); lock (s_lock) { for (int i = 0; i < s_providers.Count; i++) { if (s_providers[i].IsActive) { list.Add(s_providers[i]); } } return list; } } public static CombatCalculationContext BuildUnifiedContext() { CombatCalculationContext context = CombatCalculationContext.CreateDefault(); List activeProviders = GetActiveProviders(); for (int i = 0; i < activeProviders.Count; i++) { try { activeProviders[i].CollectModifiers(ref context); } catch { } } return context; } } internal static class FaunaAiHandoff { private static readonly string[] SharedRpcs = new string[3] { "Alert", "OnNearProjectileHit", "SetAggravated" }; private static readonly string[] MonsterRpcs = new string[2] { "RPC_Wakeup", "RPC_Sleep" }; private static readonly FieldInfo Functions = AccessTools.Field(typeof(ZNetView), "m_functions"); private static readonly FieldInfo CharacterAI = AccessTools.Field(typeof(Character), "m_baseAI"); private static readonly HashSet InProgress = new HashSet(); private static readonly HashSet Failed = new HashSet(); private static readonly HashSet Converted = new HashSet(); private static bool BelongsTo(object handler, BaseAI ai) { if (handler == null || object.ReferenceEquals(ai, null)) { return false; } FieldInfo fieldInfo = AccessTools.Field(handler.GetType(), "m_action"); Delegate obj = ((fieldInfo == null) ? null : (fieldInfo.GetValue(handler) as Delegate)); if ((object)obj == null) { return false; } Delegate[] invocationList = obj.GetInvocationList(); foreach (Delegate obj2 in invocationList) { if (!object.ReferenceEquals(obj2.Target, ai)) { return false; } } return true; } private static Delegate WithoutTarget(Delegate source, object target) { if ((object)source == null) { return null; } Delegate obj = source; Delegate[] invocationList = source.GetInvocationList(); foreach (Delegate obj2 in invocationList) { if (object.ReferenceEquals(obj2.Target, target)) { obj = Delegate.Remove(obj, obj2); } } return obj; } internal static bool TryReplace(Character character, AnimalAI animal, ZNetView view, out MonsterAI monster) { monster = null; int instanceID = ((Object)character).GetInstanceID(); if (Failed.Contains(instanceID) || !InProgress.Add(instanceID)) { return false; } IDictionary dictionary = null; Dictionary dictionary2 = new Dictionary(); Action action = null; Action action2 = null; bool flag = false; bool enabled = (Object)(object)animal != (Object)null && ((Behaviour)animal).enabled; try { dictionary = ((Functions == null) ? null : (Functions.GetValue(view) as IDictionary)); if (dictionary == null || CharacterAI == null) { throw new NotSupportedException("AI lifecycle fields unavailable"); } string[] sharedRpcs = SharedRpcs; foreach (string text in sharedRpcs) { int stableHashCode = StringExtensionMethods.GetStableHashCode(text); if (dictionary.Contains(stableHashCode)) { if (!BelongsTo(dictionary[stableHashCode], (BaseAI)(object)animal)) { throw new InvalidOperationException("RPC belongs to another component: " + text); } dictionary2.Add(stableHashCode, dictionary[stableHashCode]); } } string[] monsterRpcs = MonsterRpcs; foreach (string text2 in monsterRpcs) { if (dictionary.Contains(StringExtensionMethods.GetStableHashCode(text2))) { throw new InvalidOperationException("MonsterAI RPC already registered: " + text2); } } if ((Object)(object)animal != (Object)null) { action = character.m_onDamaged; action2 = character.m_onDeath; ((Behaviour)animal).enabled = false; character.m_onDamaged = (Action)WithoutTarget(action, animal); character.m_onDeath = (Action)WithoutTarget(action2, animal); } flag = true; foreach (int key in dictionary2.Keys) { dictionary.Remove(key); } monster = ((Component)character).gameObject.AddComponent(); string[] sharedRpcs2 = SharedRpcs; foreach (string text3 in sharedRpcs2) { if (!BelongsTo(dictionary[StringExtensionMethods.GetStableHashCode(text3)], (BaseAI)(object)monster)) { throw new InvalidOperationException("Incomplete MonsterAI Awake: " + text3); } } string[] monsterRpcs2 = MonsterRpcs; foreach (string text4 in monsterRpcs2) { if (!BelongsTo(dictionary[StringExtensionMethods.GetStableHashCode(text4)], (BaseAI)(object)monster)) { throw new InvalidOperationException("Incomplete MonsterAI Awake: " + text4); } } if ((Object)(object)animal != (Object)null) { ((MonoBehaviour)animal).CancelInvoke(); Object.Destroy((Object)(object)animal); } Converted.Add(character); Debug.Log((object)("[TameMate] Fauna AI handoff complete: " + ((Object)character).name + "; character=" + ((object)character).GetType().Name + "; humanoid=" + (character is Humanoid))); return true; } catch (Exception ex) { if (flag) { if ((Object)(object)monster == (Object)null) { monster = ((Component)character).GetComponent(); } if ((Object)(object)monster != (Object)null) { ((Behaviour)monster).enabled = false; ((MonoBehaviour)monster).CancelInvoke(); character.m_onDamaged = (Action)WithoutTarget(character.m_onDamaged, monster); character.m_onDeath = (Action)WithoutTarget(character.m_onDeath, monster); string[] sharedRpcs3 = SharedRpcs; foreach (string text5 in sharedRpcs3) { if (BelongsTo(dictionary[StringExtensionMethods.GetStableHashCode(text5)], (BaseAI)(object)monster)) { dictionary.Remove(StringExtensionMethods.GetStableHashCode(text5)); } } string[] monsterRpcs3 = MonsterRpcs; foreach (string text6 in monsterRpcs3) { if (BelongsTo(dictionary[StringExtensionMethods.GetStableHashCode(text6)], (BaseAI)(object)monster)) { dictionary.Remove(StringExtensionMethods.GetStableHashCode(text6)); } } Object.Destroy((Object)(object)monster); } foreach (KeyValuePair item in dictionary2) { if (!dictionary.Contains(item.Key)) { dictionary.Add(item.Key, item.Value); } } if ((Object)(object)animal != (Object)null) { if (action != null) { Delegate[] invocationList = action.GetInvocationList(); foreach (Delegate obj in invocationList) { if (object.ReferenceEquals(obj.Target, animal)) { character.m_onDamaged = (Action)Delegate.Combine(character.m_onDamaged, (Action)obj); } } } if (action2 != null) { Delegate[] invocationList2 = action2.GetInvocationList(); foreach (Delegate obj2 in invocationList2) { if (object.ReferenceEquals(obj2.Target, animal)) { character.m_onDeath = (Action)Delegate.Combine(character.m_onDeath, (Action)obj2); } } } CharacterAI.SetValue(character, animal); ((Behaviour)animal).enabled = enabled; } } monster = null; Failed.Add(instanceID); Debug.LogWarning((object)("[TameMate] Fauna AI handoff deferred for " + ((Object)character).name + ": " + ex.Message + ". Creature data retained; reload after resolving the conflict.")); return false; } finally { InProgress.Remove(instanceID); } } internal static bool IsConvertedNonHumanoid(Character character) { if ((Object)(object)character != (Object)null && !(character is Humanoid)) { return Converted.Contains(character); } return false; } internal static void Forget(Character character) { Failed.Remove(((Object)character).GetInstanceID()); Converted.Remove(character); } internal static void Clear() { Failed.Clear(); InProgress.Clear(); Converted.Clear(); } } internal static class FaunaAiRuntimeSafety { internal static void Install(Harmony harmony) { Patch(harmony, "SelectBestAttack", "SelectAttack", typeof(Humanoid), typeof(float)); Patch(harmony, "UpdateTarget", "UpdateTarget", typeof(Humanoid), typeof(float), typeof(bool).MakeByRefType(), typeof(bool).MakeByRefType()); Patch(harmony, "UpdateConsumeItem", "Consume", typeof(Humanoid), typeof(float)); Patch(harmony, "DoAttack", "Attack", typeof(Character), typeof(bool)); } private static void Patch(Harmony harmony, string name, string prefix, params Type[] parameters) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(MonsterAI), name, parameters, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(typeof(MonsterAI).FullName, name); } harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FaunaAiRuntimeSafety), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static bool SelectAttack(Humanoid __0, Character ___m_character, ref ItemData __result) { if ((Object)(object)__0 != (Object)null || !FaunaAiHandoff.IsConvertedNonHumanoid(___m_character)) { return true; } __result = null; return false; } private static bool UpdateTarget(Humanoid __0, Character ___m_character, ref Character ___m_targetCreature, ref StaticTarget ___m_targetStatic, ref bool __2, ref bool __3) { if ((Object)(object)__0 != (Object)null || !FaunaAiHandoff.IsConvertedNonHumanoid(___m_character)) { return true; } ___m_targetCreature = null; ___m_targetStatic = null; __2 = false; __3 = false; return false; } private static bool Consume(Humanoid __0, Character ___m_character, ref bool __result) { if ((Object)(object)__0 != (Object)null || !FaunaAiHandoff.IsConvertedNonHumanoid(___m_character)) { return true; } __result = false; return false; } private static bool Attack(Character ___m_character, ref bool __result) { if (!FaunaAiHandoff.IsConvertedNonHumanoid(___m_character)) { return true; } __result = false; return false; } } public static class FloatingCombatDamage { private struct CombatDamageContext { public Character Attacker; public Character Target; public bool IsCritical; public bool HasContext; } private const int MaxVisualErrorLogs = 3; private static bool s_isInstalled = false; private static ManualLogSource s_logger = null; private static Harmony s_harmonyInstance = null; private static int s_visualErrorLogCount = 0; [ThreadStatic] private static CombatDamageContext s_currentContext; private static readonly FieldInfo s_worldTextsField = AccessTools.Field(typeof(DamageText), "m_worldTexts"); private static FieldInfo s_textFieldField = null; private static float s_cachedScale = 2f; private static Color s_cachedColorPlayer = Color.white; private static Color s_cachedColorCompanion = new Color(0.27f, 0.98f, 0.27f, 1f); private static Color s_cachedColorWild = new Color(1f, 0.2f, 0.2f, 1f); private static Color s_cachedColorCritical = new Color(1f, 0.84f, 0f, 1f); public static ConfigEntry ConfigEnabled; public static ConfigEntry ConfigScale; public static ConfigEntry ConfigOutlineWidth; public static ConfigEntry ConfigColorPlayer; public static ConfigEntry ConfigColorCompanion; public static ConfigEntry ConfigColorWild; public static ConfigEntry ConfigColorCritical; public static bool Enabled { get { if (ConfigEnabled == null) { return true; } return ConfigEnabled.Value; } } public static float DamageScale => s_cachedScale; public static Color ColorPlayer => s_cachedColorPlayer; public static Color ColorCompanion => s_cachedColorCompanion; public static Color ColorWild => s_cachedColorWild; public static Color ColorCritical => s_cachedColorCritical; public static void UpdateCachedSettings() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: 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_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) s_cachedScale = ((ConfigScale != null) ? Mathf.Clamp(ConfigScale.Value, 0.5f, 4f) : 2f); s_cachedColorPlayer = ParseColor((ConfigColorPlayer != null) ? ConfigColorPlayer.Value : "#FFFFFF", Color.white); s_cachedColorCompanion = ParseColor((ConfigColorCompanion != null) ? ConfigColorCompanion.Value : "#44FF44", new Color(0.27f, 0.98f, 0.27f, 1f)); s_cachedColorWild = ParseColor((ConfigColorWild != null) ? ConfigColorWild.Value : "#FF3333", new Color(1f, 0.2f, 0.2f, 1f)); s_cachedColorCritical = ParseColor((ConfigColorCritical != null) ? ConfigColorCritical.Value : "#FFD700", new Color(1f, 0.84f, 0f, 1f)); } private static Color ParseColor(string hex, Color fallback) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(hex)) { return fallback; } Color result = default(Color); if (ColorUtility.TryParseHtmlString(hex, ref result)) { return result; } return fallback; } public static void InitializeConfig(ConfigFile config) { if (config != null) { ConfigEnabled = config.Bind("FloatingDamage", "Enabled", true, "Habilitar indicadores flotantes de daño inspirados en ARK (sistema nativo)."); ConfigScale = config.Bind("FloatingDamage", "Scale", 2f, "Tamaño de los números de daño relativo al original (2.0 = 200%)."); ConfigOutlineWidth = config.Bind("FloatingDamage", "OutlineWidth", 0.25f, "Configuración preservada para compatibilidad de archivo."); ConfigColorPlayer = config.Bind("FloatingDamage", "ColorPlayer", "#FFFFFF", "Color hexadecimal para daño infligido por el jugador (Blanco)."); ConfigColorCompanion = config.Bind("FloatingDamage", "ColorCompanion", "#44FF44", "Color hexadecimal para daño infligido por compañeros domesticados propios (Verde)."); ConfigColorWild = config.Bind("FloatingDamage", "ColorWild", "#FF3333", "Color hexadecimal para daño infligido por criaturas salvajes (Rojo)."); ConfigColorCritical = config.Bind("FloatingDamage", "ColorCritical", "#FFD700", "Color hexadecimal para golpes críticos verificados (Dorado)."); ConfigScale.SettingChanged += delegate { UpdateCachedSettings(); }; ConfigColorPlayer.SettingChanged += delegate { UpdateCachedSettings(); }; ConfigColorCompanion.SettingChanged += delegate { UpdateCachedSettings(); }; ConfigColorWild.SettingChanged += delegate { UpdateCachedSettings(); }; ConfigColorCritical.SettingChanged += delegate { UpdateCachedSettings(); }; UpdateCachedSettings(); } } public static void Install(Harmony harmony, ManualLogSource logger, ConfigFile config = null) { //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown //IL_00f1: Expected O, but got Unknown //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Expected O, but got Unknown if (s_isInstalled) { return; } s_logger = logger; s_harmonyInstance = harmony; s_visualErrorLogCount = 0; if (config != null) { InitializeConfig(config); } else { UpdateCachedSettings(); } try { MethodInfo methodInfo = AccessTools.Method(typeof(Character), "ApplyDamage", new Type[3] { typeof(HitData), typeof(bool), typeof(DamageModifier) }, (Type[])null); if (methodInfo == null) { methodInfo = AccessTools.Method(typeof(Character), "ApplyDamage", (Type[])null, (Type[])null); } if (methodInfo == null) { throw new MissingMethodException("Character", "ApplyDamage"); } MethodInfo methodInfo2 = AccessTools.Method(typeof(FloatingCombatDamage), "ApplyDamagePrefix", (Type[])null, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(typeof(FloatingCombatDamage), "ApplyDamagePostfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (s_logger != null) { s_logger.LogInfo((object)"[FloatingCombatDamage] Character.ApplyDamage context hook installed."); } MethodInfo methodInfo4 = AccessTools.Method(typeof(DamageText), "AddInworldText", new Type[5] { typeof(TextType), typeof(Vector3), typeof(float), typeof(string), typeof(bool) }, (Type[])null); if (methodInfo4 == null) { methodInfo4 = AccessTools.Method(typeof(DamageText), "AddInworldText", (Type[])null, (Type[])null); } if (methodInfo4 == null) { throw new MissingMethodException("DamageText", "AddInworldText"); } MethodInfo methodInfo5 = AccessTools.Method(typeof(FloatingCombatDamage), "AddInworldTextPostfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(methodInfo5), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (s_logger != null) { s_logger.LogInfo((object)"[FloatingCombatDamage] DamageText.AddInworldText styling hook installed."); } s_isInstalled = true; if (s_logger != null) { s_logger.LogInfo((object)"[FloatingCombatDamage] ARK-style floating damage system active (RC6 Visual Safety Certified)."); } } catch (Exception ex) { if (harmony != null) { try { harmony.UnpatchSelf(); } catch { } } s_isInstalled = false; s_currentContext = default(CombatDamageContext); if (s_logger != null) { s_logger.LogError((object)("[FloatingCombatDamage] Installation failed (rolled back atomically): " + ex.Message)); } throw; } } public static void Uninstall() { if (s_harmonyInstance != null) { try { s_harmonyInstance.UnpatchSelf(); } catch { } } s_isInstalled = false; s_currentContext = default(CombatDamageContext); s_visualErrorLogCount = 0; } private static void LogVisualError(string hookName, Exception ex) { if (s_visualErrorLogCount < 3) { s_visualErrorLogCount++; if (s_logger != null) { s_logger.LogWarning((object)$"[FloatingCombatDamage] Visual hook {hookName} non-fatal warning ({s_visualErrorLogCount}/{3}): {ex.Message}"); } } } public static void ApplyDamagePrefix(Character __instance, HitData hit) { if (!Enabled) { return; } try { if (hit != null && !((Object)(object)__instance == (Object)null)) { Character attacker = hit.GetAttacker(); BaseAI component = ((Component)__instance).GetComponent(); bool flag = (Object)(object)component != (Object)null && !component.IsAlerted() && hit.m_backstabBonus > 1f; bool flag2 = __instance.IsStaggering(); bool flag3 = hit.m_weakSpot > 0; bool isCritical = flag || flag2 || flag3; s_currentContext.Attacker = attacker; s_currentContext.Target = __instance; s_currentContext.IsCritical = isCritical; s_currentContext.HasContext = true; } } catch (Exception ex) { LogVisualError("ApplyDamagePrefix", ex); } } public static void ApplyDamagePostfix() { try { s_currentContext.HasContext = false; s_currentContext.Attacker = null; s_currentContext.Target = null; s_currentContext.IsCritical = false; } catch (Exception ex) { LogVisualError("ApplyDamagePostfix", ex); } } public static void AddInworldTextPostfix(DamageText __instance, TextType type, Vector3 pos, float distance, string text, bool mySelf) { //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0164: 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_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) if (!Enabled) { return; } try { if ((Object)(object)__instance == (Object)null || s_worldTextsField == null || !(s_worldTextsField.GetValue(__instance) is IList { Count: not 0 } list)) { return; } object obj = list[list.Count - 1]; if (obj == null) { return; } if (s_textFieldField == null) { s_textFieldField = AccessTools.Field(obj.GetType(), "m_textField"); } if (s_textFieldField == null) { return; } object? value = s_textFieldField.GetValue(obj); TMP_Text val = (TMP_Text)((value is TMP_Text) ? value : null); if (!((Object)(object)val == (Object)null)) { val.fontSize *= s_cachedScale; val.fontStyle = (FontStyles)1; Color color; if (s_currentContext.HasContext && s_currentContext.IsCritical) { color = s_cachedColorCritical; } else if (s_currentContext.HasContext && (Object)(object)s_currentContext.Attacker != (Object)null) { Character attacker = s_currentContext.Attacker; color = ((!attacker.IsPlayer() && !((Object)(object)attacker == (Object)(object)Player.m_localPlayer)) ? ((!attacker.IsTamed() && (int)attacker.m_faction != 0) ? s_cachedColorWild : s_cachedColorCompanion) : s_cachedColorPlayer); } else { color = (mySelf ? s_cachedColorWild : s_cachedColorPlayer); } ((Graphic)val).color = color; } } catch (Exception ex) { LogVisualError("AddInworldTextPostfix", ex); } } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("mitsu.tamemate.lineages", "TameMate Lineages Compatibility", "0.8.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class LineagesPlugin : BaseUnityPlugin { private Harmony harmony; private Harmony taming; private Harmony advice; private Harmony floating; private Harmony mountedAttack; private Harmony passiveGen; private Harmony masteries; private Harmony remoteTaming; private Harmony evolution; private Harmony contextualAdvice; private Harmony saddlebags; private Harmony difficultyCodex; private Harmony rpgCodex; private Harmony bossAddBridge; private Harmony autonomousBalance; private Harmony floatingDamage; private void Awake() { //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Expected O, but got Unknown //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Expected O, but got Unknown //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Expected O, but got Unknown //IL_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Expected O, but got Unknown //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_041e: Expected O, but got Unknown //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_0483: Expected O, but got Unknown //IL_05d6: Unknown result type (might be due to invalid IL or missing references) //IL_05e0: Expected O, but got Unknown //IL_066b: Unknown result type (might be due to invalid IL or missing references) //IL_0675: Expected O, but got Unknown //IL_0790: Unknown result type (might be due to invalid IL or missing references) //IL_079a: Expected O, but got Unknown //IL_0800: Unknown result type (might be due to invalid IL or missing references) //IL_080a: Expected O, but got Unknown //IL_0876: Unknown result type (might be due to invalid IL or missing references) //IL_0880: Expected O, but got Unknown //IL_0720: Unknown result type (might be due to invalid IL or missing references) //IL_072a: Expected O, but got Unknown //IL_096d: Unknown result type (might be due to invalid IL or missing references) //IL_0977: Expected O, but got Unknown if (!Chainloader.PluginInfos.TryGetValue("mitsu.tamemate", out var value)) { return; } ((BaseUnityPlugin)this).Logger.LogInfo((object)"================================================================================"); ((BaseUnityPlugin)this).Logger.LogInfo((object)(" TAMEMATE 0.8.0 — " + "The RPG Experience Update".ToUpperInvariant())); ((BaseUnityPlugin)this).Logger.LogInfo((object)" Assembly: TameMate.Lineages.dll v0.8.0.0 | Plugin GUID: mitsu.tamemate.lineages"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"================================================================================"); if (Chainloader.PluginInfos.TryGetValue("MidnightsFX.StarLevelSystem", out var value2) && (Object)(object)value2.Instance != (Object)null) { SlsLevelSettingsRepair.Run(((object)value2.Instance).GetType().Assembly, Paths.ConfigPath, LogSlsRepairInfo, LogSlsRepairWarning); } SurvivalRuntime0741.Install(); floating = new Harmony("mitsu.tamemate.floating0740"); try { FloatingSafety0740.Install(floating, delegate(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); }); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Floating terrain safety active: world readiness and network-view diagnostics; native authority retained."); } catch (Exception ex) { floating.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("Floating safety inactive: " + ex.GetBaseException().Message)); } try { taming = new Harmony("mitsu.tamemate.taming0740"); TamingRules0740.Install(taming, ((object)value.Instance).GetType().Assembly); SpawnAdvice0740.TamingActive = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.42 taming rules active: species/tier requirements and actual-health combat trials."); } catch (Exception ex2) { if (taming != null) { taming.UnpatchSelf(); } TamingRules0740.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("Taming rules inactive; no partial rule patch retained: " + ex2.GetBaseException().Message)); return; } try { mountedAttack = new Harmony("mitsu.tamemate.mountedattack0742"); MountedSpecialAttack.Install(mountedAttack, ((object)value.Instance).GetType().Assembly, ((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.42 Mounted special attacks active: key C / combo for multi-attack mounts, full 1-3 attack support, riding discount and HUD feedback."); } catch (Exception ex3) { if (mountedAttack != null) { mountedAttack.UnpatchSelf(); } MountedSpecialAttack.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("Mounted special attack inactive: " + ex3.GetBaseException().Message)); } try { passiveGen = new Harmony("mitsu.tamemate.passivegen0743"); PassiveResourceGeneration.Install(passiveGen, ((object)value.Instance).GetType().Assembly, ((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.43 Passive resource generation active: 1 world resource per creature/boss into saddlebags, exploration-preserved balance and storage capacity cap."); } catch (Exception ex4) { if (passiveGen != null) { passiveGen.UnpatchSelf(); } PassiveResourceGeneration.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("Passive resource generation inactive: " + ex4.GetBaseException().Message)); } try { masteries = new Harmony("mitsu.tamemate.masteries0745"); MasteriesSystem.Install(masteries, ((object)value.Instance).GetType().Assembly, ((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.45 Masteries system active: 8 runic paths (4 creatures / 4 player), direct F7 codex menu, draggable HUD medallions and persistent player progression."); } catch (Exception ex5) { if (masteries != null) { masteries.UnpatchSelf(); } MasteriesSystem.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("Masteries system inactive: " + ex5.GetBaseException().Message)); } try { remoteTaming = new Harmony("mitsu.tamemate.remotetaming0745"); RemoteTamingTracker.Init(remoteTaming, ((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.45 Remote taming inspection active: extended chest-feeding range hover and corral status."); } catch (Exception ex6) { if (remoteTaming != null) { remoteTaming.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Remote taming inspection inactive: " + ex6.GetBaseException().Message)); } try { evolution = new Harmony("mitsu.tamemate.evolution0745"); EvolutionAscensionEngine.Init(evolution, ((object)value.Instance).GetType()); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.51 Evolution Ascension Engine active: required core bindings validated; Feral -> Supreme preview and proportional health."); } catch (Exception ex7) { if (evolution != null) { evolution.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Evolution Ascension Engine inactive: " + ex7.GetBaseException().Message)); } try { contextualAdvice = new Harmony("mitsu.tamemate.contextualadvice0746"); ContextualAdviceEngine.Init(contextualAdvice); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.46 Contextual advice active: organic tutorial progression without spawn spam."); } catch (Exception ex8) { if (contextualAdvice != null) { contextualAdvice.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Contextual advice inactive: " + ex8.GetBaseException().Message)); } try { saddlebags = new Harmony("mitsu.tamemate.saddlebags0752"); CompanionSaddlebagsSync.Install(saddlebags, ((object)value.Instance).GetType().Assembly); ReanimationSync.SetLogger(((BaseUnityPlugin)this).Logger); ReanimationSync.Install(saddlebags, ((object)value.Instance).GetType().Assembly); DeepNorthAscension.Install(saddlebags, ((object)value.Instance).GetType().Assembly); UndeadMitigationCap.Install(saddlebags, ((object)value.Instance).GetType().Assembly); CataclysmicCombatPipeline.Install(saddlebags, ((object)value.Instance).GetType().Assembly); CataclysmicHudFormatter.Install(saddlebags, ((object)value.Instance).GetType().Assembly); CommandWheelSaddlebagsIntegration.Install(saddlebags, ((object)value.Instance).GetType().Assembly); PriorityFixesIntegration.Install(saddlebags, ((object)value.Instance).GetType().Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.52 Companion Saddlebags & Reanimation Sync active: modern byte[] storage, safe reanimation transfer, exact 8-scenario single-roll table and 1:1 attribute preservation."); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.54 Cataclysmic Decoupled Architecture active: orthogonal state, mitigation formula verified, and persistent disk backup."); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.54 Ritual 4B-2B.2 prepared: production writes disabled; controlled execution requires verified global identity, which live ZDO inspection does not provide."); } catch (Exception ex9) { if (saddlebags != null) { saddlebags.UnpatchSelf(); } ((BaseUnityPlugin)this).Logger.LogError((object)("Companion Saddlebags & Reanimation Sync inactive: " + ex9.GetBaseException().Message)); } try { difficultyCodex = new Harmony("mitsu.tamemate.difficultycodex0756"); DifficultyCodexPatches.Install(difficultyCodex, ((object)value.Instance).GetType().Assembly); DifficultyCodexGui.Init(((object)value.Instance).GetType().Assembly, ((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.56 Difficulty Codex & Experience Coordinator active: non-destructive F11 staging, multi-category governance, and transactional SLS/Vanilla sync."); } catch (Exception ex10) { if (difficultyCodex != null) { difficultyCodex.UnpatchSelf(); } DifficultyCodexGui.Close(); ((BaseUnityPlugin)this).Logger.LogError((object)("Difficulty Codex inactive: " + ex10.GetBaseException().Message)); } try { rpgCodex = new Harmony("mitsu.tamemate.rpgcodex0756"); RpgCharacterCodexPatches.Install(rpgCodex); RpgCharacterCodexGui.HotkeyConfig = ((BaseUnityPlugin)this).Config.Bind("Controls", "RpgCodexHotkey", (KeyCode)291, "Tecla para abrir o cerrar el Códice del Personaje (Adaptive RPG Archetypes)."); RpgCharacterCodexGui.Init(((object)value.Instance).GetType().Assembly, ((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.7.56 Adaptive RPG Character Codex active: independent F10 modal, 5-category profile introspection, and read-only masteries."); } catch (Exception ex11) { if (rpgCodex != null) { rpgCodex.UnpatchSelf(); } RpgCharacterCodexPatches.Uninstall(); RpgCharacterCodexGui.Close(); ((BaseUnityPlugin)this).Logger.LogError((object)("Adaptive RPG Character Codex inactive: " + ex11.GetBaseException().Message)); } try { if (BossAddAdapter.IsPluginLoaded) { bossAddBridge = new Harmony("mitsu.tamemate.bossaddbridge080"); BossAddAdapter.Install(bossAddBridge, ((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.8.0 BossAdd compatibility active: safe stale-view prevention and orphaned VFX recovery."); } } catch (Exception ex12) { if (bossAddBridge != null) { bossAddBridge.UnpatchSelf(); } BossAddAdapter.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("BossAdd compatibility inactive: " + ex12.GetBaseException().Message)); } try { autonomousBalance = new Harmony("mitsu.tamemate.autonomousbalance080"); AutonomousDifficultyBalance.Install(autonomousBalance, ((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.8.0 Autonomous difficulty balance active: +25% wild creature health in Difícil preset when standalone."); } catch (Exception ex13) { if (autonomousBalance != null) { autonomousBalance.UnpatchSelf(); } AutonomousDifficultyBalance.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("Autonomous difficulty balance inactive: " + ex13.GetBaseException().Message)); } try { floatingDamage = new Harmony("mitsu.tamemate.floatingdamage080"); FloatingCombatDamage.Install(floatingDamage, ((BaseUnityPlugin)this).Logger, ((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Logger.LogInfo((object)"0.8.0 ARK-style Floating Combat Damage active: 200% scalable native indicators with dark outline and verified color coding."); } catch (Exception ex14) { if (floatingDamage != null) { floatingDamage.UnpatchSelf(); } FloatingCombatDamage.Uninstall(); ((BaseUnityPlugin)this).Logger.LogError((object)("Floating Combat Damage inactive: " + ex14.GetBaseException().Message)); } advice = new Harmony("mitsu.tamemate.advice0740"); try { SpawnAdvice0740.Install(advice, delegate(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); }); } catch (Exception ex15) { advice.UnpatchSelf(); ((BaseUnityPlugin)this).Logger.LogError((object)("Spawn advice inactive; taming remains active: " + ex15.GetBaseException().Message)); } if (!Chainloader.PluginInfos.TryGetValue("Azathoth.LinejaeserasRace", out var value3)) { return; } try { if (value3.Metadata.Version == new Version(1, 0, 8)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"LinejaeserasRace 1.0.8 detected: optional integration is currently unsupported in TameMate 0.8.0 (adapter inactive; native race preserved)."); return; } if (value3.Metadata.Version != new Version(1, 0, 7)) { throw new NotSupportedException("Supported LinejaeserasRace version: 1.0.7; found " + value3.Metadata.Version); } Bridge.PassengerKey = ((BaseUnityPlugin)this).Config.Bind("Controls", "Player passenger key", (KeyCode)121, "When LinejaeserasRace uses U, use this key instead during the session. Its saved configuration is preserved. U remains the TameMate wheel."); harmony = new Harmony("mitsu.tamemate.lineages"); Bridge.Install(harmony, ((object)value3.Instance).GetType().Assembly, ((object)value.Instance).GetType().Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"LinejaeserasRace 1.0.7 adapted: racial eligibility, exact tamer, companion boss credit protection and contextual controls. Racial rolls and food speed retained."); } catch (Exception ex16) { if (harmony != null) { harmony.UnpatchSelf(); } Bridge.Ready = false; ((BaseUnityPlugin)this).Logger.LogError((object)("Lineages integration inactive; no partial adapter retained: " + ex16.GetBaseException().Message)); } } private void LogSlsRepairInfo(string message) { ((BaseUnityPlugin)this).Logger.LogInfo((object)message); } private void LogSlsRepairWarning(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); } private void OnDestroy() { if (floatingDamage != null) { floatingDamage.UnpatchSelf(); } FloatingCombatDamage.Uninstall(); if (autonomousBalance != null) { autonomousBalance.UnpatchSelf(); } AutonomousDifficultyBalance.Uninstall(); if (bossAddBridge != null) { bossAddBridge.UnpatchSelf(); } BossAddAdapter.Uninstall(); if (rpgCodex != null) { rpgCodex.UnpatchSelf(); } RpgCharacterCodexPatches.Uninstall(); if (difficultyCodex != null) { difficultyCodex.UnpatchSelf(); } DifficultyCodexGui.Close(); RpgCharacterCodexGui.Close(); if (saddlebags != null) { saddlebags.UnpatchSelf(); } CompanionSaddlebagsSync.Uninstall(); if (contextualAdvice != null) { contextualAdvice.UnpatchSelf(); } if (evolution != null) { evolution.UnpatchSelf(); } if (remoteTaming != null) { remoteTaming.UnpatchSelf(); } if (masteries != null) { masteries.UnpatchSelf(); } MasteriesSystem.Uninstall(); if (passiveGen != null) { passiveGen.UnpatchSelf(); } PassiveResourceGeneration.Uninstall(); if (mountedAttack != null) { mountedAttack.UnpatchSelf(); } MountedSpecialAttack.Uninstall(); SurvivalRuntime0741.Uninstall(); if (harmony != null) { harmony.UnpatchSelf(); } if (taming != null) { taming.UnpatchSelf(); } if (advice != null) { advice.UnpatchSelf(); } if (floating != null) { floating.UnpatchSelf(); } SpawnAdvice0740.TamingActive = false; FloatingSafety0740.Clear(); TamingRules0740.Uninstall(); Bridge.Ready = false; } } public delegate bool RequirementCheck(Player player, Character target, out string reason); public static class Bridge { public sealed class Scope { public Player Actor; public Character Target; public int Tier; public bool Eligible = true; } [ThreadStatic] private static Scope current; public static bool Ready; public static ConfigEntry PassengerKey; internal static RequirementCheck Requirements; internal static Func Peaceful; internal static Func Blocked; internal static Func Trophy; internal static Func Aim; internal static Func Unlock; internal static MethodInfo NativeAim; private static readonly int Owner = StringExtensionMethods.GetStableHashCode("tm_owner"); private static MethodInfo Required(Type type, string name, params Type[] args) { MethodInfo methodInfo = AccessTools.Method(type, name, args, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.FullName, name); } return methodInfo; } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(Bridge), name, (Type[])null); } public static void Install(Harmony h, Assembly race, Assembly core) { //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Expected O, but got Unknown //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Expected O, but got Unknown Type type = race.GetType("LinejaeserasRace.LNE_DarkForestElfSystem", throwOnError: true); Type type2 = core.GetType("TameMate.TamingRequirements", throwOnError: true); Type type3 = core.GetType("TameMate.BiomeLordsPolicy", throwOnError: true); Requirements = (RequirementCheck)Delegate.CreateDelegate(typeof(RequirementCheck), Required(type2, "CanTame", typeof(Player), typeof(Character), typeof(string).MakeByRefType())); Peaceful = (Func)Delegate.CreateDelegate(typeof(Func), Required(type2, "IsPeacefulTameOnly", typeof(Character))); Blocked = (Func)Delegate.CreateDelegate(typeof(Func), Required(type3, "IsBlocked", typeof(Character))); NativeAim = Required(type, "AimCharacter", typeof(Player), typeof(float)); Aim = (Func)Delegate.CreateDelegate(typeof(Func), NativeAim); Unlock = (Func)Delegate.CreateDelegate(typeof(Func), AccessTools.PropertyGetter(type, "TameUnlock")); Trophy = HasTrophy; MethodInfo methodInfo = Required(type, "TryCalm", typeof(Player), typeof(int)); MethodInfo methodInfo2 = Required(type, "Receive", typeof(Player), typeof(string)); MethodInfo methodInfo3 = Required(type, "ApplyAnimal", typeof(Character), typeof(int), typeof(float)); MethodInfo methodInfo4 = Required(race.GetType("LinejaeserasRace.LNE_DarkElfRelay", throwOnError: true), "RPC_Fx", typeof(long), typeof(string)); MethodInfo methodInfo5 = Required(core.GetType("TameMate.CharacterSetTamedPatch", throwOnError: true), "Postfix", typeof(Character), typeof(bool)); MethodInfo methodInfo6 = Required(race.GetType("LinejaeserasRace.Systems.LNE_RaceMountSystem", throwOnError: true), "Tick"); MethodInfo methodInfo7 = Required(typeof(GlobalBalance), "AppendGuide", typeof(string)); List list = CreditLookups(race); if (list.Count < 12) { throw new NotSupportedException("Racial boss credit surface changed: " + list.Count); } h.Patch((MethodBase)Required(typeof(Character), "GetHeight"), new HarmonyMethod(typeof(RaceCapsuleReadiness0740), "Prepare", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Required(typeof(Character), "GetRadius"), new HarmonyMethod(typeof(RaceCapsuleReadiness0740), "Prepare", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo, Hook("BeginCalm"), (HarmonyMethod)null, Hook("CalmCalls"), Hook("EndScope"), (HarmonyMethod)null); h.Patch((MethodBase)methodInfo2, Hook("BeginReceive"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("EndScope"), (HarmonyMethod)null); h.Patch((MethodBase)methodInfo3, Hook("BeginApply"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("EndScope"), (HarmonyMethod)null); h.Patch((MethodBase)methodInfo4, Hook("AuthenticateRelay"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, Hook("OwnerCall"), (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, (HarmonyMethod)null, Hook("KeyCall"), (HarmonyMethod)null, (HarmonyMethod)null); foreach (MethodInfo item in list) { h.Patch((MethodBase)item, Hook((item.GetParameters()[0].ParameterType == typeof(GameObject)) ? "AllowObjectCredit" : "AllowCredit"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } h.Patch((MethodBase)Required(race.GetType("LinejaeserasRace.LNE_OrcovilFelEnergySystem", throwOnError: true), "GrantBossProgressIfEligible", typeof(Player), typeof(Character)), Hook("AllowSecondCredit"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, Hook("Guide"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Ready = true; } private static List CreditLookups(Assembly assembly) { List list = new List(); Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.Namespace == null || !type.Namespace.StartsWith("LinejaeserasRace", StringComparison.Ordinal)) { continue; } MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 1) { bool flag = (methodInfo.Name == "FindBoss" || methodInfo.Name == "FindBossProgress") && (methodInfo.ReturnType.Name == "BossProgressDef" || methodInfo.ReturnType.Name == "BossDefinition"); bool flag2 = methodInfo.Name == "AwardBossProgress" || methodInfo.Name == "TryRecordTaurenBossProgress" || (type.Name == "Character_OnDeath_DwarfOreProgressPatch" && methodInfo.Name == "Postfix"); if ((flag || flag2) && (parameters[0].ParameterType == typeof(Character) || parameters[0].ParameterType == typeof(GameObject))) { list.Add(methodInfo); } } } } return list; } private static bool HasTrophy(Player actor, Character target) { string text = default(string); return RevisionRuntime.HasTrophy(actor, target, ref text); } public static void BeginCalm(Player __0, int __1, out Scope __state) { __state = current; Scope scope = new Scope(); scope.Actor = __0; scope.Tier = __1; current = scope; } public static void BeginReceive(Player __0, out Scope __state) { __state = current; Scope scope = new Scope(); scope.Actor = __0; current = scope; } public static void EndScope(Scope __state) { current = __state; } public static Character AimChecked(Player actor, float range) { Character val = Aim(actor, range); if (current == null) { return val; } current.Target = val; if (!Object.op_Implicit((Object)(object)val) || current.Tier < Unlock()) { return val; } current.Eligible = Eligible(actor, val, out var reason); if (!current.Eligible && (Object)(object)actor == (Object)(object)Player.m_localPlayer) { ((Character)actor).Message((MessageType)2, reason, 0, (Sprite)null, false); } return val; } public static bool Eligible(Player actor, Character target, out string reason) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) reason = (ModLanguage.IsEnglish ? "TameMate: this creature cannot be tamed with the racial ability." : "TameMate: esta criatura no admite la doma racial."); if (!Object.op_Implicit((Object)(object)actor) || ((Character)actor).IsDead() || !Object.op_Implicit((Object)(object)target) || target.IsPlayer() || target.IsDead() || target.IsTamed() || target.IsBoss() || Blocked(target)) { return false; } ZNetView component = ((Component)target).GetComponent(); if (!Object.op_Implicit((Object)(object)component) || !component.IsValid() || Vector3.Distance(((Component)actor).transform.position, ((Component)target).transform.position) > 25f || component.GetZDO().GetLong(Owner, 0L) != 0) { return false; } if ((Object)(object)actor != (Object)(object)Player.m_localPlayer) { return false; } if (!Requirements(actor, target, out reason)) { return false; } if (RevisionRuntime.CoolingDown(target)) { reason = (ModLanguage.IsEnglish ? "Wait for the TameMate taming rejection cooldown." : "Espera a que termine el rechazo de doma de TameMate."); return false; } if (!Peaceful(target) && !Trophy(actor, target)) { reason = (ModLanguage.IsEnglish ? "Carry this creature's trophy to attempt racial taming." : "Lleva el trofeo de esta criatura para intentar la doma racial."); return false; } return true; } public static float RacialRandom() { if (current == null || current.Eligible) { return Random.value; } return 1f; } public static void BeginApply(Character __0, ref int __1, out Scope __state) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) __state = current; if (__1 == 2) { Player val = ((current == null) ? null : current.Actor); ZNetView val2 = (Object.op_Implicit((Object)(object)__0) ? ((Component)__0).GetComponent() : null); if (!Object.op_Implicit((Object)(object)val) || ((Character)val).IsDead() || !Object.op_Implicit((Object)(object)__0) || __0.IsDead() || __0.IsPlayer() || __0.IsBoss() || __0.IsTamed() || Blocked(__0) || !Object.op_Implicit((Object)(object)val2) || !val2.IsValid() || val2.GetZDO().GetLong(Owner, 0L) != 0 || !(Vector3.Distance(((Component)val).transform.position, ((Component)__0).transform.position) <= 25f) || ((Object)(object)val == (Object)(object)Player.m_localPlayer && !current.Eligible)) { __1 = 1; return; } Scope scope = new Scope(); scope.Actor = val; scope.Target = __0; current = scope; } } public static Player ExactTamer(Vector3 point, float range) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) Scope scope = current; if (scope != null && Object.op_Implicit((Object)(object)scope.Actor) && Object.op_Implicit((Object)(object)scope.Target) && Vector3.Distance(point, ((Component)scope.Target).transform.position) < 0.01f) { return scope.Actor; } return Player.GetClosestPlayer(point, range); } public static bool AuthenticateRelay(long __0, Player ____player) { ZNetView val = (Object.op_Implicit((Object)(object)____player) ? ((Component)____player).GetComponent() : null); if (Object.op_Implicit((Object)(object)val) && val.IsValid()) { return val.GetZDO().GetOwner() == __0; } return false; } public static bool AllowCredit(Character __0) { if (Object.op_Implicit((Object)(object)__0)) { return !__0.IsTamed(); } return true; } public static bool AllowSecondCredit(Character __1) { return AllowCredit(__1); } public static bool AllowObjectCredit(GameObject __0) { if (Object.op_Implicit((Object)(object)__0)) { return AllowCredit(__0.GetComponent()); } return true; } public static bool PassengerDown(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_0018: Unknown result type (might be due to invalid IL or missing references) KeyCode val = (((int)key == 117) ? PassengerKey.Value : key); if ((int)val != 117) { return Input.GetKeyDown(val); } return false; } private static IEnumerable Replace(IEnumerable source, MethodInfo from, MethodInfo to, int expected) { List list = new List(source); int num = 0; foreach (CodeInstruction item in list) { if ((item.opcode == OpCodes.Call || item.opcode == OpCodes.Callvirt) && object.Equals(item.operand, from)) { item.opcode = OpCodes.Call; item.operand = to; num++; } } if (num != expected) { throw new NotSupportedException("Adapter call shape changed: " + from.Name + " (" + num + ")"); } return list; } public static IEnumerable CalmCalls(IEnumerable code) { return Replace(Replace(code, NativeAim, Required(typeof(Bridge), "AimChecked", typeof(Player), typeof(float)), 1), AccessTools.PropertyGetter(typeof(Random), "value"), Required(typeof(Bridge), "RacialRandom"), 1); } public static IEnumerable OwnerCall(IEnumerable code) { return Replace(code, Required(typeof(Player), "GetClosestPlayer", typeof(Vector3), typeof(float)), Required(typeof(Bridge), "ExactTamer", typeof(Vector3), typeof(float)), 1); } public static IEnumerable KeyCall(IEnumerable code) { return Replace(code, Required(typeof(Input), "GetKeyDown", typeof(KeyCode)), Required(typeof(Bridge), "PassengerDown", typeof(KeyCode)), 1); } public static void Guide(ref string __result) { __result += (ModLanguage.IsEnglish ? "\n\nLinejaeserasRace integration\nRacial taming retains its chance, cost and food speed bonus. TameMate eligibility and required trophies still apply; the caster owns the companion. A companion boss death grants no racial boss victory. If the player-passenger key is U, the adapter uses its configurable fallback (Y by default). Racial stats remain on the player; riding stamina belongs to the creature. Racial progression remains personal; world difficulty is controlled by the host." : "\n\nIntegración con LinejaeserasRace\nLa doma racial conserva su probabilidad, coste y ventaja de alimentación. Se respetan los requisitos y trofeos de TameMate; el lanzador es el dueño del compañero. La muerte de un jefe compañero no cuenta como victoria racial. Si el transporte entre jugadores usa U, el puente utiliza su tecla alternativa configurable (Y por defecto). Los atributos raciales pertenecen al jugador; el aguante de monta pertenece a la criatura. La progresión racial sigue siendo personal y la dificultad del mundo depende del anfitrión."); } public static void Advice(Player __instance) { if (Ready && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { AdviceFeature.Queue("tamemate_lineages_0740", "TameMate · LinejaeserasRace", ModLanguage.IsEnglish ? "Your racial taming ability now respects TameMate requirements and trophies. Its chance and food speed bonus remain racial benefits. You own creatures you tame. U opens the companion wheel; the conflicting player-passenger shortcut uses Y by default. See F11." : "Tu habilidad racial de doma respeta los requisitos y trofeos de TameMate. Conservas su probabilidad y la ventaja de alimentación. Las criaturas que domesticas te pertenecen. U abre la rueda; el atajo de transporte entre jugadores que coincidía con U usa Y por defecto. Consulta F11.", "tamemate_guide"); } } } public static class RaceCapsuleReadiness0740 { public static bool Prepare(Character __instance, ref CapsuleCollider ___m_collider, ref float __result) { if (!Object.op_Implicit((Object)(object)___m_collider)) { ___m_collider = ((Component)__instance).GetComponent(); } if (Object.op_Implicit((Object)(object)___m_collider)) { return true; } __result = 0f; return false; } } } namespace TameMate { public enum MasteryId { None, BeastKing, FeralBastion, AlphaBloodline, StormBeasts, MasterTamer, GrandCavalier, ApexTracker, BeastShaman } public enum MasteryRank { Locked, Iniciado, Veterano, Experto, Maestro, GranMaestro } public class MasteryRankInfo { public MasteryRank Rank; public string TitleEs; public string TitleEn; public string QuestDescEs; public string QuestDescEn; public int RequiredAmount; public string SpecialFeatEs; public string SpecialFeatEn; public string PerksEs; public string PerksEn; public MasteryRankInfo(MasteryRank rank, string titleEs, string titleEn, string questEs, string questEn, int reqAmt, string specialEs, string specialEn, string perksEs, string perksEn) { Rank = rank; TitleEs = titleEs; TitleEn = titleEn; QuestDescEs = questEs; QuestDescEn = questEn; RequiredAmount = reqAmt; SpecialFeatEs = specialEs; SpecialFeatEn = specialEn; PerksEs = perksEs; PerksEn = perksEn; } public string GetTitle() { if (Localization.instance == null || !(Localization.instance.GetSelectedLanguage() == "Spanish")) { return TitleEn; } return TitleEs; } public string GetQuestDesc() { if (Localization.instance == null || !(Localization.instance.GetSelectedLanguage() == "Spanish")) { return QuestDescEn; } return QuestDescEs; } public string GetPerks() { if (Localization.instance == null || !(Localization.instance.GetSelectedLanguage() == "Spanish")) { return PerksEn; } return PerksEs; } } public class MasteryDefinition { public MasteryId Id; public string NameEs; public string NameEn; public string CategoryEs; public string CategoryEn; public string IconFile; public string SummaryEs; public string SummaryEn; public readonly Dictionary Ranks = new Dictionary(); public Texture2D IconTexture; public Sprite IconSprite; public MasteryDefinition(MasteryId id, string nameEs, string nameEn, string catEs, string catEn, string iconFile, string sumEs, string sumEn) { Id = id; NameEs = nameEs; NameEn = nameEn; CategoryEs = catEs; CategoryEn = catEn; IconFile = iconFile; SummaryEs = sumEs; SummaryEn = sumEn; } public void AddRank(MasteryRank rank, string titleEs, string titleEn, string questEs, string questEn, int reqAmt, string specEs, string specEn, string perksEs, string perksEn) { Ranks[rank] = new MasteryRankInfo(rank, titleEs, titleEn, questEs, questEn, reqAmt, specEs, specEn, perksEs, perksEn); } public string GetName() { if (Localization.instance == null || !(Localization.instance.GetSelectedLanguage() == "Spanish")) { return NameEn; } return NameEs; } public string GetCategory() { if (Localization.instance == null || !(Localization.instance.GetSelectedLanguage() == "Spanish")) { return CategoryEn; } return CategoryEs; } public string GetSummary() { if (Localization.instance == null || !(Localization.instance.GetSelectedLanguage() == "Spanish")) { return SummaryEn; } return SummaryEs; } public MasteryRank GetRank(Player player) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return MasteryRank.Locked; } string key = "TM_Rank_" + Id; if (player.m_customData.TryGetValue(key, out var value) && !string.IsNullOrEmpty(value) && int.TryParse(value, out var result) && Enum.IsDefined(typeof(MasteryRank), result)) { return (MasteryRank)result; } string key2 = "TM_Unlocked_" + Id; if (player.m_customData.TryGetValue(key2, out value) && value == "true") { player.m_customData[key] = "1"; return MasteryRank.Iniciado; } return MasteryRank.Locked; } public bool IsUnlocked(Player player) { return GetRank(player) >= MasteryRank.Iniciado; } public int GetProgress(Player player) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return 0; } string key = "TM_Progress_" + Id; if (player.m_customData.TryGetValue(key, out var value) && !string.IsNullOrEmpty(value) && int.TryParse(value, out var result)) { return result; } return 0; } public bool HasSpecialFeat(Player player, string featId) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return false; } string key = "TM_Feat_" + Id.ToString() + "_" + featId; if (player.m_customData.TryGetValue(key, out var value)) { return value == "true"; } return false; } public void SetSpecialFeat(Player player, string featId) { if (!((Object)(object)player == (Object)null) && player.m_customData != null) { string key = "TM_Feat_" + Id.ToString() + "_" + featId; player.m_customData[key] = "true"; CheckRankUp(player); } } public void AddProgress(Player player, int amount) { if (!((Object)(object)player == (Object)null) && player.m_customData != null) { MasteryRank rank = GetRank(player); if (rank < MasteryRank.GranMaestro) { int num = GetProgress(player) + amount; string key = "TM_Progress_" + Id; player.m_customData[key] = num.ToString(); CheckRankUp(player); } } } public void Reset(Player player) { if (!((Object)(object)player == (Object)null) && player.m_customData != null) { string key = "TM_Rank_" + Id; string key2 = "TM_Unlocked_" + Id; string key3 = "TM_Progress_" + Id; player.m_customData.Remove(key); player.m_customData.Remove(key2); player.m_customData.Remove(key3); if (MasteriesSystem.GetSlotMastery(player, 1) == Id) { player.m_customData["TM_MasterySlot_1"] = ""; } if (MasteriesSystem.GetSlotMastery(player, 2) == Id) { player.m_customData["TM_MasterySlot_2"] = ""; } } } public static int GetCustomInt(Player p, string key) { if ((Object)(object)p == (Object)null || p.m_customData == null) { return 0; } if (p.m_customData.TryGetValue(key, out var value) && int.TryParse(value, out var result)) { return result; } return 0; } public void CheckRankUp(Player player) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return; } MasteryRank rank = GetRank(player); if (rank >= MasteryRank.GranMaestro) { return; } MasteryRank masteryRank = rank + 1; if (!Ranks.TryGetValue(masteryRank, out var value)) { return; } int progress = GetProgress(player); bool flag = progress >= value.RequiredAmount; bool flag2 = true; if (Id == MasteryId.ApexTracker) { switch (masteryRank) { case MasteryRank.Iniciado: { int customInt5 = GetCustomInt(player, "TM_Apex_ProjectileKills"); flag2 = customInt5 >= 15 || HasSpecialFeat(player, "apex_15_projectiles"); break; } case MasteryRank.Veterano: { int customInt2 = GetCustomInt(player, "TM_Apex_StarKills"); flag2 = customInt2 >= 20 || HasSpecialFeat(player, "apex_20_stars"); break; } case MasteryRank.Experto: { int customInt4 = GetCustomInt(player, "TM_Apex_BiomeCount"); flag2 = customInt4 >= 3 || HasSpecialFeat(player, "apex_3_biomes"); break; } case MasteryRank.Maestro: { int customInt3 = GetCustomInt(player, "TM_Apex_BossCount"); flag2 = customInt3 >= 1 || HasSpecialFeat(player, "apex_boss_ranged_1"); break; } case MasteryRank.GranMaestro: { int customInt = GetCustomInt(player, "TM_Apex_BossCount"); bool flag3 = (player.m_customData.ContainsKey("TM_Apex_CoordinatedHunt") && player.m_customData["TM_Apex_CoordinatedHunt"] == "true") || HasSpecialFeat(player, "apex_coordinated_hunt"); flag2 = (customInt >= 2 || HasSpecialFeat(player, "apex_boss_ranged_2")) && flag3; break; } } } else if (Id == MasteryId.BeastShaman) { switch (masteryRank) { case MasteryRank.Iniciado: flag2 = true; break; case MasteryRank.Veterano: flag2 = (player.m_customData.ContainsKey("TM_Shaman_Ritual_Offering") && player.m_customData["TM_Shaman_Ritual_Offering"] == "true") || HasSpecialFeat(player, "shaman_offering_3_species") || HasSpecialFeat(player, "feed_3_species"); break; case MasteryRank.Experto: flag2 = (player.m_customData.ContainsKey("TM_Shaman_Ritual_Consecration") && player.m_customData["TM_Shaman_Ritual_Consecration"] == "true") || HasSpecialFeat(player, "shaman_consecration_adv") || HasSpecialFeat(player, "feed_adv_trophy"); break; case MasteryRank.Maestro: flag2 = (player.m_customData.ContainsKey("TM_Shaman_Ritual_Protection") && player.m_customData["TM_Shaman_Ritual_Protection"] == "true") || HasSpecialFeat(player, "shaman_protection_boss") || HasSpecialFeat(player, "ritual_boss_trophy"); break; case MasteryRank.GranMaestro: { bool flag4 = player.m_customData.ContainsKey("TM_Shaman_PactTriggered") && player.m_customData["TM_Shaman_PactTriggered"] == "true"; bool flag5 = (player.m_customData.ContainsKey("TM_Shaman_Ritual_SupremeCommunion") && player.m_customData["TM_Shaman_Ritual_SupremeCommunion"] == "true") || HasSpecialFeat(player, "shaman_supreme_communion"); flag2 = flag4 && flag5; break; } } } else if (Id == MasteryId.MasterTamer) { switch (masteryRank) { case MasteryRank.Iniciado: case MasteryRank.Veterano: flag2 = true; break; case MasteryRank.Experto: flag2 = HasSpecialFeat(player, "tame_3_species") || GetCustomInt(player, "TM_TamedSpeciesCount") >= 3; break; case MasteryRank.Maestro: flag2 = HasSpecialFeat(player, "tame_advanced_beast") || (player.m_customData.ContainsKey("TM_Tamed_AdvancedBeast") && player.m_customData["TM_Tamed_AdvancedBeast"] == "true"); break; case MasteryRank.GranMaestro: flag2 = HasSpecialFeat(player, "tame_elite_feat") || (player.m_customData.ContainsKey("TM_Tamed_EliteFeat") && player.m_customData["TM_Tamed_EliteFeat"] == "true"); break; } } else if (!string.IsNullOrEmpty(value.SpecialFeatEs)) { flag2 = HasSpecialFeat(player, masteryRank.ToString()) || HasSpecialFeat(player, value.SpecialFeatEs); } if (flag && flag2) { PromoteRank(player, masteryRank); } } public void PromoteRank(Player player, MasteryRank newRank) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return; } string key = "TM_Rank_" + Id; Dictionary customData = player.m_customData; int num = (int)newRank; customData[key] = num.ToString(); player.m_customData["TM_Unlocked_" + Id] = "true"; if ((Object)(object)player == (Object)(object)Player.m_localPlayer) { Ranks.TryGetValue(newRank, out var value); string arg = ((value != null) ? value.GetTitle() : newRank.ToString()); string text = ""; for (int i = 0; i < (int)newRank; i++) { text += "★"; } string text2 = string.Format((Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish") ? "¡ASCENSO DE MAESTRÍA NÓRDICA!\n{0}: {1} {2}\nAbre el Códice [F7] para inspeccionar tus nuevos poderes." : "NORDIC MASTERY PROMOTION!\n{0}: {1} {2}\nOpen Codex [F7] to inspect new powers.", GetName(), arg, text); ((Character)player).Message((MessageType)2, text2, 0, (Sprite)null, false); } } public MasteryRankInfo GetCurrentRankInfo(Player player) { MasteryRank rank = GetRank(player); if (Ranks.TryGetValue(rank, out var value)) { return value; } if (Ranks.TryGetValue(MasteryRank.Iniciado, out value)) { return value; } return null; } public MasteryRankInfo GetNextRankInfo(Player player) { MasteryRank rank = GetRank(player); if (rank >= MasteryRank.GranMaestro) { return null; } MasteryRank key = rank + 1; Ranks.TryGetValue(key, out var value); return value; } } public static class MasteriesSystem { public const string KeySlot1 = "TM_Mastery_Slot1"; public const string KeySlot2 = "TM_Mastery_Slot2"; internal static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate Masteries"); private static Harmony harmony; private static bool isInstalled; public static ConfigEntry MasteriesEnabled; public static ConfigEntry MenuHotkey; public static ConfigEntry HudPositionX; public static ConfigEntry HudPositionY; public static ConfigEntry HudScale; public static ConfigEntry HudVisibleOnlyWithInventory; public static readonly Dictionary Catalog = new Dictionary(); public static Func CustomBossTrophyValidator; private static GameObject uiHostObject; private static MasteriesUI uiComponent; private static readonly MethodInfo LoadImageMethod = typeof(ImageConversion).GetMethod("LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }); public static void Install(Harmony harmonyInstance, Assembly coreAssembly, ConfigFile config) { //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Expected O, but got Unknown //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Expected O, but got Unknown if (isInstalled) { return; } harmony = harmonyInstance; MasteriesEnabled = config.Bind("Masteries", "Enabled", true, "Habilita o deshabilita el sistema de Maestrías de TameMate."); MenuHotkey = config.Bind("Masteries", "MenuHotkey", (KeyCode)288, "Tecla para abrir o cerrar el Códice de Maestrías."); HudPositionX = config.Bind("Masteries", "HudPositionX", 0.78f, "Posición X relativa en pantalla del HUD de maestrías (0.0 izquierda, 1.0 derecha)."); HudPositionY = config.Bind("Masteries", "HudPositionY", 0.08f, "Posición Y relativa en pantalla del HUD de maestrías (0.0 arriba, 1.0 abajo)."); HudScale = config.Bind("Masteries", "HudScale", 1f, "Escala visual de los medallones del HUD (0.5 a 2.0)."); HudVisibleOnlyWithInventory = config.Bind("Masteries", "HudVisibleOnlyWithInventory", false, "Si es verdadero, el HUD de maestrías solo es visible cuando el inventario está abierto."); if (!MasteriesEnabled.Value) { Log.LogInfo((object)"Masteries system is disabled by configuration."); return; } PopulateCatalog(); LoadTextures(); try { harmony.PatchAll(typeof(MasteriesGameplayPatches)); if (coreAssembly != null) { Type type = coreAssembly.GetType("TameMate.TameMateRavenAdvice"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "TriggerAdvice", new Type[4] { typeof(string), typeof(string), typeof(string), typeof(string) }, (Type[])null); if (methodInfo != null) { MethodInfo methodInfo2 = AccessTools.Method(typeof(MasteriesGameplayPatches), "RavenAdviceTriggerAdvicePrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } } catch (Exception ex) { Log.LogError((object)("Failed to apply Masteries gameplay patches: " + ex.Message)); } if ((Object)(object)uiHostObject == (Object)null) { uiHostObject = new GameObject("_TameMate_MasteriesUI"); Object.DontDestroyOnLoad((Object)(object)uiHostObject); uiComponent = uiHostObject.AddComponent(); } isInstalled = true; Log.LogInfo((object)"TameMate Masteries System 0.8.0 installed successfully."); } public static void Uninstall() { if (isInstalled) { if ((Object)(object)uiHostObject != (Object)null) { Object.Destroy((Object)(object)uiHostObject); uiHostObject = null; uiComponent = null; } if (harmony != null) { harmony.UnpatchSelf(); harmony = null; } isInstalled = false; Log.LogInfo((object)"TameMate Masteries System uninstalled."); } } private static void PopulateCatalog() { Catalog.Clear(); MasteryDefinition masteryDefinition = new MasteryDefinition(MasteryId.BeastKing, "Rey de las Bestias", "Beast King", "Criaturas", "Creatures", "icon_beast_king.png", "Liderazgo alfa, sincronización de combate y furia física para tus bestias.", "Alpha leadership, combat synchronization, and physical fury for your beasts."); masteryDefinition.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Derrota a 50 enemigos con participación real de tu bestia.", "Defeat 50 enemies with active companion participation.", 50, null, null, "+2% de daño físico en bestias aliadas.", "+2% physical damage on allied beasts."); masteryDefinition.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 125 bajas acumuladas y derrota al menos 15 enemigos de 1★ o más.", "Reach 125 cumulative kills and defeat at least 15 enemies of 1★ or higher.", 125, "15_star_enemies", "15_star_enemies", "+4% de daño físico.\nSed de Sangre: recupera 1% de vida máxima por baja (CD: 15s).", "+4% physical damage.\nBloodlust: restores 1% max HP per kill (15s CD)."); masteryDefinition.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 250 bajas acumuladas combatiendo en 3 biomas diferentes.", "Reach 250 cumulative kills defeating foes across 3 different biomes.", 250, "3_biomes", "3_biomes", "+7% de daño físico.\nSed de Sangre: recupera 2% de vida máxima por baja (CD: 15s).", "+7% physical damage.\nBloodlust: restores 2% max HP per kill (15s CD)."); masteryDefinition.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 400 bajas y derrota a un Jefe de Bioma con una bestia que sobreviva.", "Reach 400 kills and defeat a Biome Boss with a surviving beast.", 400, "boss_survival_1", "boss_survival_1", "+10% de daño físico.\nSed de Sangre: recupera 3% de vida máxima por baja (CD: 15s).\nRugido Intimidador: al entrar en combate desestabiliza a enemigos menores.", "+10% physical damage.\nBloodlust: restores 3% max HP per kill (15s CD).\nIntimidating Roar: staggers lesser foes when entering combat."); masteryDefinition.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 600 bajas acumuladas y participa en vencer a 3 jefes distintos con compañeros sobrevivientes.", "Reach 600 kills and participate in defeating 3 distinct bosses with surviving companions.", 600, "boss_survival_3", "boss_survival_3", "+15% de daño físico.\nSed de Sangre: recupera 4% de vida máxima por baja (CD: 15s).\nRugido Alfa: control temporal y atemorización de enemigos cercanos.", "+15% physical damage.\nBloodlust: restores 4% max HP per kill (15s CD).\nAlpha Roar: temporary control and fear on nearby foes."); Catalog[MasteryId.BeastKing] = masteryDefinition; MasteryDefinition masteryDefinition2 = new MasteryDefinition(MasteryId.FeralBastion, "Bastión Feral", "Feral Bastion", "Criaturas", "Creatures", "icon_feral_bastion.png", "Armadura de piedra, tenacidad defensiva y protección de manada.", "Stone armor, defensive tenacity, and pack bodyguard protection."); masteryDefinition2.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Haz que tus bestias resistan 1,000 puntos de daño en combate.", "Have your beasts endure 1,000 points of combat damage.", 1000, null, null, "+3% de vida máxima en bestias aliadas.", "+3% max health on allied beasts."); masteryDefinition2.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 3,000 puntos de daño resistido y sobrevive a ataques de 1★.", "Reach 3,000 damage endured and survive 1★ enemy attacks.", 3000, "survive_1star", "survive_1star", "+5% de vida máxima.\n2% de reducción de daño recibido.", "+5% max health.\n2% damage reduction."); masteryDefinition2.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 7,500 puntos de daño resistido en 3 biomas diferentes.", "Reach 7,500 damage endured across 3 different biomes.", 7500, "resist_3_biomes", "resist_3_biomes", "+8% de vida máxima.\n3% de reducción de daño recibido.", "+8% max health.\n3% damage reduction."); masteryDefinition2.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 15,000 de daño resistido y sobrevive a un combate contra un jefe.", "Reach 15,000 damage endured and survive a boss encounter.", 15000, "boss_protect_survive", "boss_protect_survive", "+10% de vida máxima.\n5% de reducción de daño recibido.\nProvocación Feral: atrae el agro de enemigos atacantes hacia la bestia.", "+10% max health.\n5% damage reduction.\nFeral Taunt: draws enemy aggro towards the beast."); masteryDefinition2.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 25,000 de daño resistido y supera una segunda hazaña defensiva ante otro jefe.", "Reach 25,000 damage endured and overcome a 2nd boss defensive trial.", 25000, "boss_protect_survive_2", "boss_protect_survive_2", "+12% de vida máxima.\n7% de reducción de daño recibido.\nEscudo Rúnico Guardián: activa un escudo defensivo temporal al bajar del 30% de vida.", "+12% max health.\n7% damage reduction.\nGuardian Shield: temporary defensive shield when dropping below 30% HP."); Catalog[MasteryId.FeralBastion] = masteryDefinition2; MasteryDefinition masteryDefinition3 = new MasteryDefinition(MasteryId.AlphaBloodline, "Linaje Alfa", "Alpha Bloodline", "Criaturas", "Creatures", "icon_alpha_bloodline.png", "Genética superior de estrellas, crianza saludable y vigor de crías.", "Superior star genetics, healthy breeding, and offspring vigour."); masteryDefinition3.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Cría 5 descendientes válidos en tus corrales.", "Breed 5 valid offspring in your pens.", 5, null, null, "+5% de bienestar y supervivencia inicial de crías.", "+5% offspring wellness and early survival."); masteryDefinition3.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 12 descendientes criados con éxito.", "Reach 12 successfully bred offspring.", 12, null, null, "+10% de bienestar y reducción moderada de vulnerabilidad en crías.", "+10% wellness and moderate vulnerability reduction in offspring."); masteryDefinition3.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 20 descendientes criando al menos 2 especies compatibles.", "Reach 20 offspring breeding at least 2 compatible species.", 20, "breed_2_species", "breed_2_species", "+15% de desarrollo.\n+15% de probabilidad de heredar estrellas.", "+15% development.\n+15% chance to inherit stars."); masteryDefinition3.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 30 descendientes de 3 especies compatibles (o especies disponibles).", "Reach 30 offspring across 3 compatible species (or available species).", 30, "breed_3_species", "breed_3_species", "+20% de desarrollo y protección de manada en base.\n+25% de probabilidad de estrellas.", "+20% development and pack protection at base.\n+25% star inheritance chance."); masteryDefinition3.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 45 descendientes y completa una hazaña especial de linaje avanzado.", "Reach 45 offspring and complete an advanced lineage feat.", 45, "breed_2star_lineage", "breed_2star_lineage", "Habilidad de Linaje Supremo: crías nacen con resistencia mejorada y vigor superior.\nRegeneración pasiva suave en corrales.", "Supreme Lineage: offspring inherit enhanced resistance and superior vigour.\nGentle passive pen regeneration."); Catalog[MasteryId.AlphaBloodline] = masteryDefinition3; MasteryDefinition masteryDefinition4 = new MasteryDefinition(MasteryId.StormBeasts, "Bestias de la Tormenta", "Storm Beasts", "Criaturas", "Creatures", "icon_storm_beasts.png", "Adaptación y combate bajo condiciones climáticas adversas y tempestades.", "Adaptation and combat prowess under adverse weather and tempests."); masteryDefinition4.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Derrota a 15 enemigos durante condiciones climáticas adversas válidas.", "Defeat 15 enemies during valid adverse weather conditions.", 15, null, null, "+3% de resistencia a penalizaciones climáticas y ambientales.", "+3% resistance to weather and environmental penalties."); masteryDefinition4.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 40 bajas acumuladas bajo clima adverso.", "Reach 40 cumulative adverse weather kills.", 40, null, null, "+5% de resistencia ambiental.\nReducción del coste de frío/humedad en bestias.", "+5% environmental resistance.\nReduced cold/wet penalties on beasts."); masteryDefinition4.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 75 bajas combatiendo bajo 2 condiciones climáticas diferentes.", "Reach 75 kills fighting under 2 different weather conditions.", 75, "weather_2_types", "weather_2_types", "+7% de resistencia ambiental.\nMejora moderada de movilidad sobre nieve, lodo o agua.", "+7% environmental resistance.\nModerate mobility improvement across snow, mud, or water."); masteryDefinition4.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 125 bajas climáticas derrotando enemigos avanzados en tormentas.", "Reach 125 weather kills defeating advanced foes during storms.", 125, "storm_danger_kills", "storm_danger_kills", "+10% de resistencia ambiental.\nAura de Tempestad: ataques infligen +8 de daño elemental situacional.", "+10% environmental resistance.\nTempest Aura: attacks deal +8 situational elemental damage."); masteryDefinition4.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 175 bajas climáticas y supera una hazaña climática especial con bestia sobreviviente.", "Reach 175 weather kills and conquer a special weather feat with surviving beast.", 175, "storm_boss_feat", "storm_boss_feat", "+12% de resistencia ambiental.\nTenacidad de Tempestad: resistencia aumentada a aturdimientos y descarga eléctrica de choque.", "+12% environmental resistance.\nTempest Poise: enhanced stagger resistance and shock discharge."); Catalog[MasteryId.StormBeasts] = masteryDefinition4; MasteryDefinition masteryDefinition5 = new MasteryDefinition(MasteryId.MasterTamer, "Maestro Domador", "Master Tamer", "Jugador", "Player", "icon_master_tamer.png", "Eficacia en domesticación, autoridad de mando y armonía con bestias.", "Taming efficiency, command authority, and harmony with beasts."); masteryDefinition5.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Domestica con éxito a 5 criaturas completas.", "Successfully tame 5 complete creatures.", 5, null, null, "+3% de eficiencia en apaciguamiento al alimentar criaturas salvajes.", "+3% soothing efficiency when feeding wild creatures."); masteryDefinition5.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 10 domesticaciones con éxito.", "Reach 10 successful tamings.", 10, null, null, "+5% de eficiencia de apaciguamiento.", "+5% soothing efficiency."); masteryDefinition5.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 18 domesticaciones de al menos 3 especies diferentes.", "Reach 18 tamings across at least 3 different species.", 18, "tame_3_species", "tame_3_species", "+7% de eficiencia de apaciguamiento.\nRango de silbato ampliado a 30 metros.", "+7% soothing efficiency.\nWhistle command range extended to 30 meters."); masteryDefinition5.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 27 domesticaciones y completa una domesticación avanzada.", "Reach 27 tamings and complete an advanced taming.", 27, "tame_advanced_beast", "tame_advanced_beast", "+10% de eficiencia de apaciguamiento.\nVoz de Mando: silbato a 40 metros y alforjas +10% producción.", "+10% soothing efficiency.\nCommand Voice: whistle at 40m and saddlebags +10% yield."); masteryDefinition5.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 40 domesticaciones y completa una hazaña excepcional de domesticación.", "Reach 40 tamings and complete an exceptional taming feat.", 40, "tame_elite_feat", "tame_elite_feat", "+12% de eficiencia de apaciguamiento.\nMando Mejorado: silbato a 50 metros y alforjas +15% producción.", "+12% soothing efficiency.\nImproved Command: whistle at 50m and saddlebags +15% yield."); Catalog[MasteryId.MasterTamer] = masteryDefinition5; MasteryDefinition masteryDefinition6 = new MasteryDefinition(MasteryId.GrandCavalier, "Gran Jinete", "Grand Cavalier", "Jugador", "Player", "icon_grand_cavalier.png", "Dominio de monturas, economía de estamina y combate a lomos de bestias.", "Mount mastery, stamina economy, and horseback/mount warfare."); masteryDefinition6.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Recorre 500 metros montado sobre cualquier criatura.", "Travel 500 meters riding atop any creature.", 500, null, null, "5% de reducción de consumo de estamina en monturas.", "5% mount stamina consumption reduction."); masteryDefinition6.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 1,500 metros acumulados y completa un desafío montado básico.", "Reach 1,500 cumulative meters and complete a basic mounted trial.", 1500, "mounted_10_hits", "mounted_10_hits", "10% de reducción de estamina.\n+2% de velocidad de galope en montura.", "10% stamina reduction.\n+2% mount ride speed."); masteryDefinition6.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 3,000 metros y derrota 10 enemigos en combate montado.", "Reach 3,000 meters and defeat 10 enemies in mounted combat.", 3000, "mounted_10_kills", "mounted_10_kills", "15% de reducción de estamina.\n+3% de velocidad de montura.\nReducción moderada de penalización de sobrepeso al montar.", "15% stamina reduction.\n+3% mount speed.\nModerate encumbrance penalty reduction while riding."); masteryDefinition6.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 5,000 metros y derrota a un enemigo de élite montado.", "Reach 5,000 meters and defeat an elite enemy while mounted.", 5000, "mounted_elite_kill", "mounted_elite_kill", "20% de reducción de estamina.\n+4% de velocidad de montura.\nEmbestida Montada: empuja y daña enemigos al cargar (CD: 30s).", "20% stamina reduction.\n+4% mount speed.\nMounted Charge: knocks back and damages foes on dash (30s CD)."); masteryDefinition6.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 8,000 metros y completa una hazaña extraordinaria montado con bestia sobreviviente.", "Reach 8,000 meters and complete an extraordinary ride feat with surviving mount.", 8000, "mounted_boss_kill", "mounted_boss_kill", "25% de reducción de estamina.\n+5% de velocidad de montura.\nEmbestida Mejorada.\n-10% de daño recibido mientras se monta.", "25% stamina reduction.\n+5% mount speed.\nImproved Charge.\n-10% damage taken while mounted."); Catalog[MasteryId.GrandCavalier] = masteryDefinition6; MasteryDefinition masteryDefinition7 = new MasteryDefinition(MasteryId.ApexTracker, "Rastreador Apex", "Apex Tracker", "Jugador", "Player", "icon_apex_tracker.png", "Cacería táctica, sigilo letal, arcos, ballestas y coordinación a distancia con compañeros.", "Tactical hunting, lethal stealth, bows, crossbows, and ranged coordination with companions."); masteryDefinition7.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Consigue 75 bajas con arco, ballesta o sigilo y 15 remates a distancia.", "Achieve 75 bow, crossbow or sneak kills and 15 ranged projectile finishers.", 75, "apex_15_projectiles", "apex_15_projectiles", "+1% daño a distancia.\n+3% bonificación de sigilo.", "+1% ranged damage.\n+3% stealth bonus."); masteryDefinition7.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 200 bajas acumuladas y derrota 20 enemigos de 1★ o superior.", "Reach 200 kills and defeat 20 enemies of 1★ or higher.", 200, "apex_20_stars", "apex_20_stars", "+2% daño a distancia.\n+5% bonificación de sigilo.", "+2% ranged damage.\n+5% stealth bonus."); masteryDefinition7.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 400 bajas acumuladas cazando en 3 biomas diferentes.", "Reach 400 kills hunting across 3 different biomes.", 400, "apex_3_biomes", "apex_3_biomes", "+3% daño a distancia.\n+8% bonificación de sigilo.\nAlerta temprana de amenazas cercanas.", "+3% ranged damage.\n+8% stealth bonus.\nEarly warning of nearby threats."); masteryDefinition7.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 650 bajas y participa significativamente (≥20%) en derrotar a un Jefe a distancia con compañero vivo.", "Reach 650 kills and participate significantly (≥20%) in defeating a Boss at range with surviving companion.", 650, "apex_boss_ranged_1", "apex_boss_ranged_1", "+5% daño a distancia.\n+10% bonificación de sigilo.\nRadar de Presas: detecta enemigos hostiles en 30m en el mapa.", "+5% ranged damage.\n+10% stealth bonus.\nPrey Radar: tracks hostile foes within 30m on map."); masteryDefinition7.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 1,000 bajas, derrota 2 jefes distintos a distancia y completa una cacería avanzada con bestia.", "Reach 1,000 kills, defeat 2 distinct bosses at range and complete an advanced hunt with beast.", 1000, "apex_boss_ranged_2", "apex_boss_ranged_2", "+7% daño a distancia.\n+15% bonificación de sigilo.\nRadar de Presas Mejorado: alcance 50m y distinción de amenazas de élite.", "+7% ranged damage.\n+15% stealth bonus.\nEnhanced Prey Radar: 50m range and elite threat markers."); Catalog[MasteryId.ApexTracker] = masteryDefinition7; MasteryDefinition masteryDefinition8 = new MasteryDefinition(MasteryId.BeastShaman, "Chamán Espiritual", "Beast Shaman", "Jugador", "Player", "icon_beast_shaman.png", "Comunión espiritual, tributos con trofeos, soporte a criaturas, recuperación y pactos vitales.", "Spiritual communion, trophy tributes, companion support, recovery, and vital pacts."); masteryDefinition8.AddRank(MasteryRank.Iniciado, "Iniciado", "Initiate", "Alimenta compañeros domesticados en 15 ocasiones válidas.", "Feed tamed companions on 15 valid occasions.", 15, null, null, "Recupera 1 de estamina cuando una bestia vinculada daña a un enemigo (CD: 5s).", "Recovers 1 stamina when a linked beast strikes a foe (5s CD)."); masteryDefinition8.AddRank(MasteryRank.Veterano, "Veterano", "Veteran", "Alcanza 35 alimentaciones válidas y completa una Ofrenda Chamánica con 3 trofeos de especies diferentes.", "Reach 35 feedings and complete a Shamanic Offering with 3 trophies of different species.", 35, "shaman_offering_3_species", "shaman_offering_3_species", "Recupera 2 de estamina por impacto de bestia (CD: 5s).\nApoyo Feral: +5% velocidad de movimiento para bestias aliadas cercanas.", "Recovers 2 stamina on beast strikes (5s CD).\nFeral Support: +5% move speed for nearby allied beasts."); masteryDefinition8.AddRank(MasteryRank.Experto, "Experto", "Expert", "Alcanza 65 alimentaciones válidas y completa una Consagración con un trofeo de criatura avanzada.", "Reach 65 feedings and complete a Consecration with an advanced creature trophy.", 65, "shaman_consecration_adv", "shaman_consecration_adv", "Recupera 3 de estamina y 1 de Eitr por impacto de bestia (CD: 5s).", "Recovers 3 stamina and 1 Eitr on beast strikes (5s CD)."); masteryDefinition8.AddRank(MasteryRank.Maestro, "Maestro", "Master", "Alcanza 100 alimentaciones válidas y completa un Ritual de Protección con un trofeo de jefe.", "Reach 100 feedings and complete a Protection Ritual with a boss trophy.", 100, "shaman_protection_boss", "shaman_protection_boss", "Recupera 4 de estamina y 2 de Eitr por impacto de bestia (CD: 5s).\nPacto de Vida: salva a tu compañero de un golpe letal dejándolo al 30% HP (CD: 15 min).", "Recovers 4 stamina and 2 Eitr on beast strikes (5s CD).\nLife Pact: saves companion from fatal blow at 30% HP (15 min CD)."); masteryDefinition8.AddRank(MasteryRank.GranMaestro, "Gran Maestro", "Grand Master", "Alcanza 150 alimentaciones, activa con éxito el Pacto de Vida y completa una Comunión Suprema con un compañero sobreviviente.", "Reach 150 feedings, successfully trigger Life Pact and complete a Supreme Communion with a surviving companion.", 150, "shaman_supreme_communion", "shaman_supreme_communion", "Recupera 5 de estamina y 3 de Eitr por impacto de bestia (CD: 5s).\nPacto de Vida Mejorado (CD: 10 min).\nAura de Sanación: regenera 1 HP cada 2s a compañeros vinculados cercanos.", "Recovers 5 stamina and 3 Eitr on beast strikes (5s CD).\nImproved Life Pact (10 min CD).\nHealing Aura: regenerates 1 HP every 2s for nearby bonded tames."); Catalog[MasteryId.BeastShaman] = masteryDefinition8; Catalog[MasteryId.BeastShaman] = masteryDefinition8; } private static void LoadTextures() { //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) string[] array = new string[6] { Path.Combine(Paths.PluginPath, "MitsurugiCM-TameMate", "assets", "masteries"), Path.Combine(Paths.PluginPath, "EchoesOfBunglas-TameMate", "assets", "masteries"), Path.Combine(Paths.PluginPath, "TameMate", "assets", "masteries"), Path.Combine(Paths.PluginPath, "assets", "masteries"), Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "assets", "masteries"), Path.Combine(Paths.PluginPath, "assets") }; string text = null; for (int i = 0; i < array.Length; i++) { if (Directory.Exists(array[i])) { text = array[i]; break; } } if (string.IsNullOrEmpty(text)) { Log.LogWarning((object)"Masteries icon directory not found in BepInEx plugins; trying workspace asset fallback."); string text2 = "C:\\Users\\Mitsu\\Desktop\\MODS VALHEIM\\TameMate\\assets\\masteries"; if (Directory.Exists(text2)) { text = text2; } } if (string.IsNullOrEmpty(text)) { Log.LogWarning((object)"No masteries asset directory found. Procedural fallback badges will be drawn."); return; } foreach (KeyValuePair item in Catalog) { string path = Path.Combine(text, item.Value.IconFile); if (!File.Exists(path)) { continue; } try { byte[] array2 = File.ReadAllBytes(path); Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false); bool flag = false; if (LoadImageMethod != null) { flag = (bool)LoadImageMethod.Invoke(null, new object[2] { val, array2 }); } if (flag) { ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; item.Value.IconTexture = val; item.Value.IconSprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f)); } } catch (Exception ex) { Log.LogError((object)("Failed to load icon " + item.Value.IconFile + ": " + ex.Message)); } } } public static MasteryId GetSlotMastery(Player player, int slot) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return MasteryId.None; } string key = ((slot == 1) ? "TM_Mastery_Slot1" : "TM_Mastery_Slot2"); if (player.m_customData.TryGetValue(key, out var value) && !string.IsNullOrEmpty(value)) { try { MasteryId masteryId = (MasteryId)Enum.Parse(typeof(MasteryId), value); if (Catalog.TryGetValue(masteryId, out var value2) && value2.IsUnlocked(player)) { return masteryId; } return MasteryId.None; } catch { return MasteryId.None; } } return MasteryId.None; } public static void SetSlotMastery(Player player, int slot, MasteryId id) { if (!((Object)(object)player == (Object)null) && player.m_customData != null) { string key = ((slot == 1) ? "TM_Mastery_Slot1" : "TM_Mastery_Slot2"); if (id == MasteryId.None) { player.m_customData.Remove(key); } else { player.m_customData[key] = id.ToString(); } if ((Object)(object)player == (Object)(object)Player.m_localPlayer && id != MasteryId.None && Catalog.TryGetValue(id, out var value)) { string text = string.Format((Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish") ? "Maestría equipada [Ranura {0}]: {1}" : "Mastery equipped [Slot {0}]: {1}", slot, value.GetName()); ((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false); } } } public static bool HasMastery(Player player, MasteryId id) { if ((Object)(object)player == (Object)null || id == MasteryId.None) { return false; } if (Catalog.TryGetValue(id, out var value) && !value.IsUnlocked(player)) { return false; } if (GetSlotMastery(player, 1) != id) { return GetSlotMastery(player, 2) == id; } return true; } public static void ToggleMastery(Player player, MasteryId id) { if ((Object)(object)player == (Object)null) { return; } if (Catalog.TryGetValue(id, out var value) && !value.IsUnlocked(player)) { string text = ((Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish") ? "¡Maestría Bloqueada! Cumple su hazaña para desbloquearla." : "Mastery Locked! Complete its feat to unlock."); ((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false); return; } MasteryId slotMastery = GetSlotMastery(player, 1); MasteryId slotMastery2 = GetSlotMastery(player, 2); if (slotMastery == id) { SetSlotMastery(player, 1, MasteryId.None); return; } if (slotMastery2 == id) { SetSlotMastery(player, 2, MasteryId.None); return; } if (slotMastery == MasteryId.None) { SetSlotMastery(player, 1, id); return; } if (slotMastery2 == MasteryId.None) { SetSlotMastery(player, 2, id); return; } SetSlotMastery(player, 1, slotMastery2); SetSlotMastery(player, 2, id); } public static void ResetMastery(Player player, MasteryId id) { if (!((Object)(object)player == (Object)null) && Catalog.TryGetValue(id, out var value)) { value.Reset(player); } } public static void ValidatePlayerCoherence(Player player) { if ((Object)(object)player == (Object)null || player.m_customData == null) { return; } if (Catalog.TryGetValue(MasteryId.AlphaBloodline, out var value)) { int progress = value.GetProgress(player); if (progress > 0) { Catalog.TryGetValue(MasteryId.MasterTamer, out var value2); if (value2 == null || value2.GetProgress(player) == 0) { value.Reset(player); } } } foreach (KeyValuePair item in Catalog) { if (item.Value != null) { item.Value.CheckRankUp(player); } } } public static int CountDistinctTrophies(Player player) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Invalid comparison between Unknown and I4 if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { return 0; } List allItems = ((Humanoid)player).GetInventory().GetAllItems(); Dictionary dictionary = new Dictionary(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && val.m_shared != null && (int)val.m_shared.m_itemType == 13) { string key = (((Object)(object)val.m_dropPrefab != (Object)null) ? ((Object)val.m_dropPrefab).name : val.m_shared.m_name); if (!dictionary.ContainsKey(key)) { dictionary[key] = val; } } } return dictionary.Count; } public static bool HasAdvancedTrophy(Player player) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { return false; } List allItems = ((Humanoid)player).GetInventory().GetAllItems(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && val.m_shared != null && (int)val.m_shared.m_itemType == 13) { string text = (((Object)(object)val.m_dropPrefab != (Object)null) ? ((Object)val.m_dropPrefab).name : val.m_shared.m_name); if (text.IndexOf("Lox", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Serpent", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Fenring", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Golem", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Seeker", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Gjall", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Tick", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Elite", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Brute", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Shaman", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Morgen", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Asksvin", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Valkyrie", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Charred", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("_TW", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } } return false; } public static bool HasBossTrophy(Player player) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { return false; } List allItems = ((Humanoid)player).GetInventory().GetAllItems(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && val.m_shared != null && (int)val.m_shared.m_itemType == 13) { string text = (((Object)(object)val.m_dropPrefab != (Object)null) ? ((Object)val.m_dropPrefab).name : val.m_shared.m_name); if (text.IndexOf("Eikthyr", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Elder", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Bonemass", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("DragonQueen", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("GoblinKing", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("SeekerQueen", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Fader", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Jormungandr", StringComparison.OrdinalIgnoreCase) >= 0 || (CustomBossTrophyValidator != null && CustomBossTrophyValidator(text))) { return true; } } } return false; } public static bool IsBenchmarkOrCheatContext(Character c) { if ((Object)(object)c == (Object)null) { return false; } if ((Object)(object)((Component)c).GetComponent("BenchmarkMarker") != (Object)null) { return true; } try { string stackTrace = Environment.StackTrace; if (stackTrace.IndexOf("MountBenchmark", StringComparison.OrdinalIgnoreCase) >= 0 || stackTrace.IndexOf("tm_bench", StringComparison.OrdinalIgnoreCase) >= 0 || (stackTrace.IndexOf("Terminal", StringComparison.OrdinalIgnoreCase) >= 0 && stackTrace.IndexOf("ConsoleCommand", StringComparison.OrdinalIgnoreCase) >= 0)) { return true; } } catch { } return false; } public static void RegisterTamedCreature(Character c, Player responsiblePlayer) { if ((Object)(object)c == (Object)null || c.IsPlayer() || IsBenchmarkOrCheatContext(c)) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } if ((Object)(object)responsiblePlayer == (Object)null || (Object)(object)responsiblePlayer != (Object)(object)localPlayer) { return; } ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null || zDO.GetBool("TM_MasteryTamed", false)) { return; } zDO.Set("TM_MasteryTamed", true); if (!Catalog.TryGetValue(MasteryId.MasterTamer, out var value)) { return; } value.AddProgress(localPlayer, 1); string text = Utils.GetPrefabName(((Component)c).gameObject).Replace("(Clone)", ""); string key = "TM_TamedSpecies_" + text; if (!localPlayer.m_customData.ContainsKey(key)) { localPlayer.m_customData[key] = "true"; int num = MasteryDefinition.GetCustomInt(localPlayer, "TM_TamedSpeciesCount") + 1; localPlayer.m_customData["TM_TamedSpeciesCount"] = num.ToString(); if (num >= 3) { value.SetSpecialFeat(localPlayer, "tame_3_species"); } } if (c.GetLevel() >= 2 || text.IndexOf("Lox", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Wolf", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Fenring", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Serpent", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Asksvin", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("_TW", StringComparison.OrdinalIgnoreCase) >= 0) { localPlayer.m_customData["TM_Tamed_AdvancedBeast"] = "true"; value.SetSpecialFeat(localPlayer, "tame_advanced_beast"); } if (c.GetLevel() >= 3 || c.IsBoss() || (localPlayer.m_customData.ContainsKey("TM_Tamed_AdvancedBeast") && MasteryDefinition.GetCustomInt(localPlayer, "TM_TamedSpeciesCount") >= 5)) { localPlayer.m_customData["TM_Tamed_EliteFeat"] = "true"; value.SetSpecialFeat(localPlayer, "tame_elite_feat"); } value.CheckRankUp(localPlayer); } public static bool TryPerformShamanRitual(Player player, MasteryRank targetRank, out string resultMessage) { //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: 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_04d7: Unknown result type (might be due to invalid IL or missing references) //IL_04de: Invalid comparison between Unknown and I4 //IL_0709: Unknown result type (might be due to invalid IL or missing references) //IL_0714: Unknown result type (might be due to invalid IL or missing references) resultMessage = ""; if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { resultMessage = "Inventario no disponible."; return false; } if (!Catalog.TryGetValue(MasteryId.BeastShaman, out var value)) { resultMessage = "Maestría Chamán no encontrada."; return false; } bool flag = Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish"; switch (targetRank) { case MasteryRank.Veterano: { if (player.m_customData.ContainsKey("TM_Shaman_Ritual_Offering") && player.m_customData["TM_Shaman_Ritual_Offering"] == "true") { resultMessage = (flag ? "La Ofrenda Chamánica ya ha sido completada para este rango." : "Shamanic Offering has already been completed for this rank."); return false; } List allItems3 = ((Humanoid)player).GetInventory().GetAllItems(); Dictionary dictionary = new Dictionary(); for (int k = 0; k < allItems3.Count; k++) { ItemData val5 = allItems3[k]; if (val5 != null && val5.m_shared != null && (int)val5.m_shared.m_itemType == 13) { string key = (((Object)(object)val5.m_dropPrefab != (Object)null) ? ((Object)val5.m_dropPrefab).name : val5.m_shared.m_name); if (!dictionary.ContainsKey(key)) { dictionary[key] = val5; } } } if (dictionary.Count < 3) { resultMessage = (flag ? $"Se requieren trofeos de 3 especies diferentes para la Ofrenda (Llevas {dictionary.Count}/3)." : $"Trophies of 3 different species required for the Offering (Carrying {dictionary.Count}/3)."); return false; } int num = 0; foreach (KeyValuePair item in dictionary) { ((Humanoid)player).GetInventory().RemoveItem(item.Value, 1); num++; if (num >= 3) { break; } } player.m_customData["TM_Shaman_Ritual_Offering"] = "true"; value.SetSpecialFeat(player, "shaman_offering_3_species"); value.SetSpecialFeat(player, MasteryRank.Veterano.ToString()); value.CheckRankUp(player); resultMessage = (flag ? "¡Ofrenda Chamánica completada! Los espíritus de las 3 bestias bendicen tu senda." : "Shamanic Offering complete! The spirits of 3 beasts bless your path."); return true; } case MasteryRank.Experto: { if (player.m_customData.ContainsKey("TM_Shaman_Ritual_Consecration") && player.m_customData["TM_Shaman_Ritual_Consecration"] == "true") { resultMessage = (flag ? "La Consagración Espiritual ya ha sido realizada para este rango." : "Spiritual Consecration has already been completed for this rank."); return false; } List allItems2 = ((Humanoid)player).GetInventory().GetAllItems(); ItemData val3 = null; for (int j = 0; j < allItems2.Count; j++) { ItemData val4 = allItems2[j]; if (val4 != null && val4.m_shared != null && (int)val4.m_shared.m_itemType == 13) { string text2 = (((Object)(object)val4.m_dropPrefab != (Object)null) ? ((Object)val4.m_dropPrefab).name : val4.m_shared.m_name); if (text2.IndexOf("Lox", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Serpent", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Fenring", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Golem", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Seeker", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Gjall", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Tick", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Elite", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Brute", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Shaman", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Morgen", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Asksvin", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Valkyrie", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("Charred", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("_TW", StringComparison.OrdinalIgnoreCase) >= 0) { val3 = val4; break; } } } if (val3 == null) { resultMessage = (flag ? "Requiere portar 1 trofeo de criatura avanzada (Lox, Serpiente, Fenring, Golem, Buscador...)" : "Requires carrying 1 advanced creature trophy (Lox, Serpent, Fenring, Golem, Seeker...)"); return false; } ((Humanoid)player).GetInventory().RemoveItem(val3, 1); player.m_customData["TM_Shaman_Ritual_Consecration"] = "true"; value.SetSpecialFeat(player, "shaman_consecration_adv"); value.SetSpecialFeat(player, MasteryRank.Experto.ToString()); value.CheckRankUp(player); resultMessage = (flag ? "¡Consagración Espiritual realizada con éxito! Comunión con la naturaleza reforzada." : "Spiritual Consecration successful! Communion with nature reinforced."); return true; } case MasteryRank.Maestro: { if (player.m_customData.ContainsKey("TM_Shaman_Ritual_Protection") && player.m_customData["TM_Shaman_Ritual_Protection"] == "true") { resultMessage = (flag ? "El Ritual de Protección ya ha sido sellado para este rango." : "Protection Ritual has already been sealed for this rank."); return false; } List allItems = ((Humanoid)player).GetInventory().GetAllItems(); ItemData val = null; for (int i = 0; i < allItems.Count; i++) { ItemData val2 = allItems[i]; if (val2 != null && val2.m_shared != null && (int)val2.m_shared.m_itemType == 13) { string text = (((Object)(object)val2.m_dropPrefab != (Object)null) ? ((Object)val2.m_dropPrefab).name : val2.m_shared.m_name); if (text.IndexOf("Eikthyr", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Elder", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Bonemass", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("DragonQueen", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("GoblinKing", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("SeekerQueen", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Fader", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Jormungandr", StringComparison.OrdinalIgnoreCase) >= 0 || (CustomBossTrophyValidator != null && CustomBossTrophyValidator(text))) { val = val2; break; } } } if (val == null) { resultMessage = (flag ? "Requiere portar 1 trofeo de Jefe (Eikthyr, El Sabio, Masaósea, Moder, Yagluth...)" : "Requires carrying 1 Boss trophy (Eikthyr, The Elder, Bonemass, Moder, Yagluth...)"); return false; } ((Humanoid)player).GetInventory().RemoveItem(val, 1); player.m_customData["TM_Shaman_Ritual_Protection"] = "true"; value.SetSpecialFeat(player, "shaman_protection_boss"); value.SetSpecialFeat(player, MasteryRank.Maestro.ToString()); value.CheckRankUp(player); resultMessage = (flag ? "¡Ritual de Protección consumado! El Pacto de Vida ha sido sellado con tus bestias." : "Protection Ritual consummated! The Life Pact has been sealed with your beasts."); return true; } case MasteryRank.GranMaestro: { if (player.m_customData.ContainsKey("TM_Shaman_Ritual_SupremeCommunion") && player.m_customData["TM_Shaman_Ritual_SupremeCommunion"] == "true") { resultMessage = (flag ? "La Comunión Suprema ya ha sido consumada." : "Supreme Communion has already been consummated."); return false; } if (!player.m_customData.ContainsKey("TM_Shaman_PactTriggered") || !(player.m_customData["TM_Shaman_PactTriggered"] == "true")) { resultMessage = (flag ? "Debes haber activado con éxito el Pacto de Vida para salvar a un compañero antes de la Comunión Suprema." : "You must have successfully triggered the Life Pact to save a companion before the Supreme Communion."); return false; } bool flag2 = false; List allCharacters = Character.GetAllCharacters(); for (int l = 0; l < allCharacters.Count; l++) { Character val6 = allCharacters[l]; if ((Object)(object)val6 != (Object)null && val6.IsTamed() && !val6.IsPlayer() && !val6.IsDead() && Vector3.Distance(((Component)val6).transform.position, ((Component)player).transform.position) <= 12f && val6.GetHealth() / val6.GetMaxHealth() >= 0.75f) { flag2 = true; break; } } if (!flag2) { resultMessage = (flag ? "Debes estar junto a un compañero domesticado con buena salud (≥75%) para consumar la Comunión." : "You must stand beside a healthy tamed companion (≥75% HP) to consummate the Communion."); return false; } player.m_customData["TM_Shaman_Ritual_SupremeCommunion"] = "true"; value.SetSpecialFeat(player, "shaman_supreme_communion"); value.SetSpecialFeat(player, MasteryRank.GranMaestro.ToString()); value.CheckRankUp(player); resultMessage = (flag ? "¡COMUNIÓN SUPREMA CONSUMADA! Has alcanzado el rango de Gran Maestro Chamán." : "SUPREME COMMUNION CONSUMMATED! You have attained Grand Master Shaman rank."); return true; } default: resultMessage = (flag ? "No hay rituales pendientes para este rango." : "No pending rituals for this rank."); return false; } } } public static class ApexPreyRadar { private static float lastScanTime = 0f; private static readonly List activeRadarPins = new List(); public static void Update(Player local) { //IL_0100: 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_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)local == (Object)null) { ClearRadarPins(); return; } if (!MasteriesSystem.HasMastery(local, MasteryId.ApexTracker)) { if (activeRadarPins.Count > 0) { ClearRadarPins(); } return; } if (!MasteriesSystem.Catalog.TryGetValue(MasteryId.ApexTracker, out var value)) { if (activeRadarPins.Count > 0) { ClearRadarPins(); } return; } MasteryRank rank = value.GetRank(local); if (rank < MasteryRank.Maestro) { if (activeRadarPins.Count > 0) { ClearRadarPins(); } } else { if (Time.time - lastScanTime < 2.5f) { return; } lastScanTime = Time.time; if ((Object)(object)Minimap.instance == (Object)null) { return; } ClearRadarPins(); float num = ((rank >= MasteryRank.GranMaestro) ? 50f : 30f); List allCharacters = Character.GetAllCharacters(); int num2 = 0; for (int i = 0; i < allCharacters.Count; i++) { if (num2 >= 12) { break; } Character val = allCharacters[i]; if ((Object)(object)val == (Object)null || val.IsDead() || val.IsTamed() || val.IsPlayer()) { continue; } float num3 = Vector3.Distance(((Component)val).transform.position, ((Component)local).transform.position); if (num3 <= num) { string text = val.GetHoverName(); if (rank >= MasteryRank.GranMaestro && (val.GetLevel() >= 2 || val.IsBoss())) { text = "★ " + text; } PinData item = Minimap.instance.AddPin(((Component)val).transform.position, (PinType)3, text, false, false, 0L, default(PlatformUserID)); activeRadarPins.Add(item); num2++; } } } } public static void ClearRadarPins() { if ((Object)(object)Minimap.instance != (Object)null && activeRadarPins.Count > 0) { for (int i = 0; i < activeRadarPins.Count; i++) { if (activeRadarPins[i] != null) { Minimap.instance.RemovePin(activeRadarPins[i]); } } } activeRadarPins.Clear(); } } public class MasteriesUI : MonoBehaviour { public static bool IsOpen; private Rect hudRect; private Rect menuRect; private bool isDragging; private Vector2 dragOffset; private GUIStyle windowStyle; private GUIStyle titleStyle; private GUIStyle subtitleStyle; private GUIStyle headerCategoryStyle; private GUIStyle buttonCardStyle; private GUIStyle tooltipBoxStyle; private bool stylesInitialized; private MasteryId hoveredMastery; private MasteryId selectedMastery; private Vector3 lastPlayerPos; private float lastAuraTime; private int activeTab; private Vector2 corralScrollPos = Vector2.zero; private void Start() { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) float num = ((MasteriesSystem.HudScale != null) ? MasteriesSystem.HudScale.Value : 1f); float num2 = ((MasteriesSystem.HudPositionX != null) ? MasteriesSystem.HudPositionX.Value : 0.78f); float num3 = ((MasteriesSystem.HudPositionY != null) ? MasteriesSystem.HudPositionY.Value : 0.08f); hudRect = new Rect((float)Screen.width * num2, (float)Screen.height * num3, 136f * num, 68f * num); menuRect = new Rect(((float)Screen.width - 780f) * 0.5f, ((float)Screen.height - 560f) * 0.5f, 780f, 560f); } public static void Open() { IsOpen = true; Character.SetTakeInputDelay(0.25f); Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; try { ZCursor.LockState = (CursorLockMode)0; ZCursor.Show(); } catch { } try { MasteriesSystem.ValidatePlayerCoherence(Player.m_localPlayer); } catch { } try { ContextualAdviceEngine.OnOpenMasteryCodex(Player.m_localPlayer); } catch { } } public static void Close() { IsOpen = false; Cursor.lockState = (CursorLockMode)1; Cursor.visible = false; try { ZCursor.LockState = (CursorLockMode)1; ZCursor.Hide(); } catch { } } private void Update() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0088: 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_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } KeyCode val = (KeyCode)((MasteriesSystem.MenuHotkey == null) ? 288 : ((int)MasteriesSystem.MenuHotkey.Value)); if (Input.GetKeyDown(val)) { if (IsOpen) { Close(); } else { Open(); } } if (IsOpen) { Character.SetTakeInputDelay(0.25f); Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; try { ZCursor.LockState = (CursorLockMode)0; ZCursor.Show(); } catch { } if (Input.GetKeyDown((KeyCode)27)) { Close(); } } if (((Character)localPlayer).IsAttached()) { if (lastPlayerPos != Vector3.zero) { float num = Vector3.Distance(((Component)localPlayer).transform.position, lastPlayerPos); if (num > 0.1f && num < 50f && MasteriesSystem.Catalog.TryGetValue(MasteryId.GrandCavalier, out var value)) { value.AddProgress(localPlayer, (int)num); } } lastPlayerPos = ((Component)localPlayer).transform.position; } else { lastPlayerPos = Vector3.zero; } ApexPreyRadar.Update(localPlayer); if (!(Time.time - lastAuraTime >= 2f)) { return; } lastAuraTime = Time.time; if (!MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastShaman) || !MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value2) || value2.GetRank(localPlayer) < MasteryRank.GranMaestro) { return; } List allCharacters = Character.GetAllCharacters(); for (int i = 0; i < allCharacters.Count; i++) { Character val2 = allCharacters[i]; if ((Object)(object)val2 != (Object)null && val2.IsTamed() && !val2.IsPlayer() && !val2.IsDead() && Vector3.Distance(((Component)val2).transform.position, ((Component)localPlayer).transform.position) <= 20f && val2.GetHealth() < val2.GetMaxHealth()) { val2.Heal(2f, true); } } } private void OnDestroy() { ApexPreyRadar.ClearRadarPins(); } private void InitStyles() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Expected O, but got Unknown //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Expected O, but got Unknown //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Expected O, but got Unknown //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Expected O, but got Unknown //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Expected O, but got Unknown //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Expected O, but got Unknown if (!stylesInitialized) { Texture2D background = MakeTex(2, 2, new Color(0.08f, 0.08f, 0.1f, 0.96f)); Texture2D background2 = MakeTex(2, 2, new Color(0.14f, 0.14f, 0.16f, 0.85f)); Texture2D background3 = MakeTex(2, 2, new Color(0.24f, 0.22f, 0.18f, 0.95f)); windowStyle = new GUIStyle(GUI.skin.window); windowStyle.normal.background = background; windowStyle.normal.textColor = new Color(0.92f, 0.88f, 0.8f); windowStyle.fontStyle = (FontStyle)1; windowStyle.padding = new RectOffset(16, 16, 14, 16); titleStyle = new GUIStyle(GUI.skin.label); titleStyle.fontSize = 20; titleStyle.fontStyle = (FontStyle)1; titleStyle.alignment = (TextAnchor)4; titleStyle.normal.textColor = new Color(1f, 0.85f, 0.35f); subtitleStyle = new GUIStyle(GUI.skin.label); subtitleStyle.fontSize = 11; subtitleStyle.alignment = (TextAnchor)4; subtitleStyle.normal.textColor = new Color(0.75f, 0.75f, 0.75f); headerCategoryStyle = new GUIStyle(GUI.skin.label); headerCategoryStyle.fontSize = 13; headerCategoryStyle.fontStyle = (FontStyle)1; headerCategoryStyle.normal.textColor = new Color(0.9f, 0.75f, 0.45f); buttonCardStyle = new GUIStyle(GUI.skin.button); buttonCardStyle.normal.background = background2; buttonCardStyle.hover.background = background3; buttonCardStyle.normal.textColor = Color.white; buttonCardStyle.alignment = (TextAnchor)7; buttonCardStyle.fontSize = 10; buttonCardStyle.fontStyle = (FontStyle)1; tooltipBoxStyle = new GUIStyle(GUI.skin.box); tooltipBoxStyle.normal.background = MakeTex(2, 2, new Color(0.05f, 0.05f, 0.07f, 0.96f)); tooltipBoxStyle.normal.textColor = new Color(0.88f, 0.88f, 0.88f); tooltipBoxStyle.alignment = (TextAnchor)0; tooltipBoxStyle.padding = new RectOffset(12, 12, 8, 8); tooltipBoxStyle.fontSize = 11; stylesInitialized = true; } } private Texture2D MakeTex(int width, int height, Color col) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown Color[] array = (Color[])(object)new Color[width * height]; for (int i = 0; i < array.Length; i++) { array[i] = col; } Texture2D val = new Texture2D(width, height); val.SetPixels(array); val.Apply(); return val; } private void OnGUI() { //IL_0035: 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_0050: Expected O, but got Unknown //IL_004b: 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) if (!((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)Hud.instance == (Object)null)) { InitStyles(); DrawMasteryHUD(); if (IsOpen) { menuRect = GUI.Window(884400, menuRect, new WindowFunction(DrawMenuWindow), ""); } } } private void DrawMasteryHUD() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Invalid comparison between Unknown and I4 //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Invalid comparison between Unknown and I4 //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) if (MasteriesSystem.HudVisibleOnlyWithInventory != null && MasteriesSystem.HudVisibleOnlyWithInventory.Value && !InventoryGui.IsVisible()) { return; } Event current = Event.current; Vector2 mousePosition = current.mousePosition; if ((int)current.type == 0 && ((Rect)(ref hudRect)).Contains(mousePosition)) { if (current.shift) { isDragging = true; dragOffset = mousePosition - new Vector2(((Rect)(ref hudRect)).x, ((Rect)(ref hudRect)).y); current.Use(); } else { if (IsOpen) { Close(); } else { Open(); } current.Use(); } } if (isDragging) { if ((int)current.type == 3) { ((Rect)(ref hudRect)).x = mousePosition.x - dragOffset.x; ((Rect)(ref hudRect)).y = mousePosition.y - dragOffset.y; current.Use(); } else if ((int)current.type == 1) { isDragging = false; if (MasteriesSystem.HudPositionX != null) { MasteriesSystem.HudPositionX.Value = ((Rect)(ref hudRect)).x / (float)Screen.width; } if (MasteriesSystem.HudPositionY != null) { MasteriesSystem.HudPositionY.Value = ((Rect)(ref hudRect)).y / (float)Screen.height; } current.Use(); } } GUI.Box(hudRect, GUIContent.none); float num = ((Rect)(ref hudRect)).height - 4f; Rect r = default(Rect); ((Rect)(ref r))..ctor(((Rect)(ref hudRect)).x + 2f, ((Rect)(ref hudRect)).y + 2f, num, num); Rect r2 = default(Rect); ((Rect)(ref r2))..ctor(((Rect)(ref hudRect)).x + num + 6f, ((Rect)(ref hudRect)).y + 2f, num, num); MasteryId slotMastery = MasteriesSystem.GetSlotMastery(Player.m_localPlayer, 1); MasteryId slotMastery2 = MasteriesSystem.GetSlotMastery(Player.m_localPlayer, 2); DrawSlotBadge(r, slotMastery, 1); DrawSlotBadge(r2, slotMastery2, 2); if (Cursor.visible) { if (((Rect)(ref r)).Contains(mousePosition) && slotMastery != MasteryId.None) { DrawHUDTooltip(slotMastery, mousePosition); } else if (((Rect)(ref r2)).Contains(mousePosition) && slotMastery2 != MasteryId.None) { DrawHUDTooltip(slotMastery2, mousePosition); } } } private void DrawSlotBadge(Rect r, MasteryId id, int slotNumber) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (id != MasteryId.None && MasteriesSystem.Catalog.TryGetValue(id, out var value) && (Object)(object)value.IconTexture != (Object)null) { GUI.DrawTexture(r, (Texture)(object)value.IconTexture, (ScaleMode)2); } else { GUI.Box(r, (slotNumber == 1) ? "I" : "II"); } } private void DrawHUDTooltip(MasteryId id, Vector2 pos) { //IL_00c9: Unknown result type (might be due to invalid IL or missing references) if (MasteriesSystem.Catalog.TryGetValue(id, out var value)) { Player localPlayer = Player.m_localPlayer; MasteryRankInfo currentRankInfo = value.GetCurrentRankInfo(localPlayer); string text = ((currentRankInfo != null) ? currentRankInfo.GetPerks() : value.GetSummary()); string text2 = ((currentRankInfo != null) ? currentRankInfo.GetTitle() : "Iniciado"); string text3 = $"{value.GetName()} ({text2})\n{value.GetCategory()}\n\n{text}"; float num = 270f; float num2 = 115f; Rect val = default(Rect); ((Rect)(ref val))..ctor(pos.x - num - 10f, pos.y, num, num2); if (((Rect)(ref val)).x < 10f) { ((Rect)(ref val)).x = pos.x + 20f; } GUI.Box(val, text3, tooltipBoxStyle); } } private void DrawMenuWindow(int windowId) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: 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_014c: Unknown result type (might be due to invalid IL or missing references) //IL_016c: 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_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_03cf: Unknown result type (might be due to invalid IL or missing references) //IL_03f2: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Unknown result type (might be due to invalid IL or missing references) //IL_0390: Unknown result type (might be due to invalid IL or missing references) hoveredMastery = MasteryId.None; Player localPlayer = Player.m_localPlayer; MasteryId slotMastery = MasteriesSystem.GetSlotMastery(localPlayer, 1); MasteryId slotMastery2 = MasteriesSystem.GetSlotMastery(localPlayer, 2); if (selectedMastery == MasteryId.None) { if (slotMastery != MasteryId.None) { selectedMastery = slotMastery; } else if (slotMastery2 != MasteryId.None) { selectedMastery = slotMastery2; } else { selectedMastery = MasteryId.BeastShaman; } } bool flag = Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish"; string text = (flag ? "CÓDICE DE MAESTRÍAS Y DOMA v0.8.0" : "MASTERY & TAMING CODEX v0.8.0"); GUI.Label(new Rect(0f, 8f, ((Rect)(ref menuRect)).width, 24f), text, titleStyle); if (GUI.Button(new Rect(((Rect)(ref menuRect)).width - 34f, 8f, 24f, 24f), "X")) { Close(); } float num = 210f; float num2 = 26f; Rect val = default(Rect); ((Rect)(ref val))..ctor(((Rect)(ref menuRect)).width * 0.5f - num - 8f, 36f, num, num2); Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref menuRect)).width * 0.5f + 8f, 36f, num, num2); GUI.color = ((activeTab == 0) ? new Color(1f, 0.85f, 0.3f) : new Color(0.7f, 0.7f, 0.7f)); if (GUI.Button(val, flag ? "\ud83d\udc51 CÓDICE DE MAESTRÍAS" : "\ud83d\udc51 MASTERY CODEX", buttonCardStyle)) { activeTab = 0; } GUI.color = ((activeTab == 1) ? new Color(0.3f, 0.9f, 1f) : new Color(0.7f, 0.7f, 0.7f)); if (GUI.Button(val2, flag ? "\ud83d\udc3e MONITOR DE CORRALES Y DOMA" : "\ud83d\udc3e CORRAL & TAMING MONITOR", buttonCardStyle)) { activeTab = 1; } GUI.color = Color.white; if (activeTab == 0) { float num3 = 70f; float num4 = 166f; float num5 = 148f; float num6 = 16f; string text2 = (flag ? "\ud83d\udc3a MAESTRÍAS DE CRIATURAS" : "\ud83d\udc3a CREATURE MASTERIES"); GUI.Label(new Rect(32f, num3, 400f, 20f), text2, headerCategoryStyle); MasteryId[] array = new MasteryId[4] { MasteryId.BeastKing, MasteryId.FeralBastion, MasteryId.AlphaBloodline, MasteryId.StormBeasts }; Rect r = default(Rect); for (int i = 0; i < array.Length; i++) { ((Rect)(ref r))..ctor(32f + (float)i * (num4 + num6), num3 + 22f, num4, num5); DrawMasteryCard(r, array[i], localPlayer, slotMastery, slotMastery2); } float num7 = num3 + num5 + 30f; string text3 = (flag ? "\ud83d\udee1\ufe0f MAESTRÍAS DEL JUGADOR" : "\ud83d\udee1\ufe0f PLAYER MASTERIES"); GUI.Label(new Rect(32f, num7, 400f, 20f), text3, headerCategoryStyle); MasteryId[] array2 = new MasteryId[4] { MasteryId.MasterTamer, MasteryId.GrandCavalier, MasteryId.ApexTracker, MasteryId.BeastShaman }; Rect r2 = default(Rect); for (int j = 0; j < array2.Length; j++) { ((Rect)(ref r2))..ctor(32f + (float)j * (num4 + num6), num7 + 22f, num4, num5); DrawMasteryCard(r2, array2[j], localPlayer, slotMastery, slotMastery2); } float num8 = num7 + num5 + 28f; Rect r3 = default(Rect); ((Rect)(ref r3))..ctor(32f, num8, ((Rect)(ref menuRect)).width - 64f, 95f); DrawDescriptionPanel(r3, localPlayer, flag); } else { Rect area = default(Rect); ((Rect)(ref area))..ctor(28f, 70f, ((Rect)(ref menuRect)).width - 56f, ((Rect)(ref menuRect)).height - 85f); DrawCorralMonitor(area, localPlayer, flag); } GUI.DragWindow(new Rect(0f, 0f, ((Rect)(ref menuRect)).width, 36f)); } private void DrawCorralMonitor(Rect area, Player player, bool isEs) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) List list = RemoteTamingTracker.ScanLocalTamingCreatures(35f); GUILayout.BeginArea(area); GUILayout.Label(isEs ? "\ud83d\udce1 MONITOR DE CORRALES Y CRIATURAS EN DOMESTICACIÓN (35m)" : "\ud83d\udce1 CORRAL & TAMING MONITOR (35m)", headerCategoryStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); if (list == null || list.Count == 0) { GUILayout.Space(30f); string text = (isEs ? "No se detectaron criaturas en proceso de domesticación en un radio de 35 metros.\nAcércate a un corral con animales alimentándose desde cofres o arroja comida al suelo." : "No taming creatures detected within 35 meters.\nMove closer to a pen with creatures feeding from chests or ground food."); GUILayout.Label(text, subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } else { corralScrollPos = GUILayout.BeginScrollView(corralScrollPos, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true) }); for (int i = 0; i < list.Count; i++) { TamingStatusInfo tamingStatusInfo = list[i]; GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); string arg = ((tamingStatusInfo.Stars > 0) ? $"{new string('★', tamingStatusInfo.Stars)} " : ""); GUILayout.Label($"{tamingStatusInfo.Name} {arg}({tamingStatusInfo.Species})", headerCategoryStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.FlexibleSpace(); GUILayout.Label($"Distancia: {tamingStatusInfo.Distance:F1}m", subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); int num = 20; int num2 = Mathf.RoundToInt(tamingStatusInfo.TamingProgress01 * (float)num); string arg2 = new string('█', num2) + new string('░', Mathf.Max(0, num - num2)); string arg3 = ((tamingStatusInfo.TamingProgress01 >= 0.8f) ? "#00FF7F" : ((tamingStatusInfo.TamingProgress01 >= 0.4f) ? "#00E5FF" : "#FFD700")); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"Doma: [{arg2}] {tamingStatusInfo.TamingProgress01 * 100f:F0}%", headerCategoryStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("• Alimentación: " + tamingStatusInfo.FedStatusText, subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(12f); GUILayout.Label("• Proceso: " + tamingStatusInfo.SimulationStatusText, subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label($"• Cofres de comida: {tamingStatusInfo.ChestFoodName}", subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.Space(4f); } GUILayout.EndScrollView(); } GUILayout.EndArea(); } private void DrawMasteryCard(Rect r, MasteryId id, Player player, MasteryId s1, MasteryId s2) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) if (!MasteriesSystem.Catalog.TryGetValue(id, out var value)) { return; } MasteryRank rank = value.GetRank(player); bool flag = rank >= MasteryRank.Iniciado; bool flag2 = s1 == id; bool flag3 = s2 == id; bool flag4 = flag2 || flag3; if (((Rect)(ref r)).Contains(Event.current.mousePosition)) { hoveredMastery = id; selectedMastery = id; if ((int)Event.current.type == 0 && Event.current.button == 1 && (Event.current.shift || Event.current.control)) { MasteriesSystem.ResetMastery(player, id); Event.current.Use(); } } string text; if (!flag) { text = ((Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish") ? "\ud83d\udd12 BLOQUEADA" : "\ud83d\udd12 LOCKED"); } else { string text2 = ""; for (int i = 0; i < (int)rank; i++) { text2 += "★"; } text = (flag2 ? "[RANURA I]" : (flag3 ? "[RANURA II]" : (text2 + " " + value.GetName()))); } if (GUI.Button(r, GUIContent.none, buttonCardStyle)) { selectedMastery = id; MasteriesSystem.ToggleMastery(player, id); } if (selectedMastery == id) { Color color = GUI.color; GUI.color = new Color(1f, 0.85f, 0.3f, 0.85f); GUI.Box(new Rect(((Rect)(ref r)).x - 2f, ((Rect)(ref r)).y - 2f, ((Rect)(ref r)).width + 4f, ((Rect)(ref r)).height + 4f), GUIContent.none); GUI.color = color; } float num = 96f; Rect val = default(Rect); ((Rect)(ref val))..ctor(((Rect)(ref r)).x + (((Rect)(ref r)).width - num) * 0.5f, ((Rect)(ref r)).y + 8f, num, num); if ((Object)(object)value.IconTexture != (Object)null) { if (!flag) { GUI.color = new Color(0.4f, 0.4f, 0.4f, 0.7f); } GUI.DrawTexture(val, (Texture)(object)value.IconTexture, (ScaleMode)2); GUI.color = Color.white; } if (flag) { string text3 = ((rank == MasteryRank.GranMaestro) ? "★ V" : ("R " + (int)rank)); GUI.color = (Color)((rank == MasteryRank.GranMaestro) ? new Color(1f, 0.85f, 0.2f) : Color.white); GUI.Box(new Rect(((Rect)(ref r)).x + ((Rect)(ref r)).width - 34f, ((Rect)(ref r)).y + 4f, 30f, 18f), text3); GUI.color = Color.white; } Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref r)).x + 4f, ((Rect)(ref r)).y + num + 12f, ((Rect)(ref r)).width - 8f, 26f); if (flag4) { GUI.color = (flag2 ? new Color(1f, 0.82f, 0.2f) : new Color(0.2f, 0.85f, 1f)); } else if (!flag) { GUI.color = new Color(0.85f, 0.45f, 0.45f); } GUI.Label(val2, text, buttonCardStyle); GUI.color = Color.white; } private void DrawDescriptionPanel(Rect r, Player player, bool isEs) { //IL_04ec: Unknown result type (might be due to invalid IL or missing references) //IL_0784: Unknown result type (might be due to invalid IL or missing references) //IL_0789: Unknown result type (might be due to invalid IL or missing references) //IL_07a3: Unknown result type (might be due to invalid IL or missing references) //IL_07e7: Unknown result type (might be due to invalid IL or missing references) //IL_07c7: Unknown result type (might be due to invalid IL or missing references) //IL_07f1: Unknown result type (might be due to invalid IL or missing references) //IL_0852: Unknown result type (might be due to invalid IL or missing references) MasteryId masteryId = ((hoveredMastery != MasteryId.None) ? hoveredMastery : selectedMastery); MasteryDefinition value = null; if (masteryId != MasteryId.None) { MasteriesSystem.Catalog.TryGetValue(masteryId, out value); } string text3; if (value != null) { MasteryRank rank = value.GetRank(player); MasteryRankInfo currentRankInfo = value.GetCurrentRankInfo(player); MasteryRankInfo nextRankInfo = value.GetNextRankInfo(player); int progress = value.GetProgress(player); if (rank == MasteryRank.Locked) { MasteryRankInfo masteryRankInfo = (value.Ranks.ContainsKey(MasteryRank.Iniciado) ? value.Ranks[MasteryRank.Iniciado] : null); int num = masteryRankInfo?.RequiredAmount ?? 25; string text = ((masteryRankInfo != null) ? masteryRankInfo.GetQuestDesc() : ""); string text2 = ((masteryRankInfo != null) ? masteryRankInfo.GetPerks() : ""); text3 = string.Format("\ud83d\udd12 {0}: {1} ({2})\nHazaña para Rango I (Iniciado): {3}\nProgreso Cuantitativo: {4} / {5} | Poder al desbloquear: {6}", isEs ? "MAESTRÍA BLOQUEADA" : "LOCKED MASTERY", value.GetName(), value.GetCategory(), text, progress, num, text2.Replace("\n", " ")); } else if (rank >= MasteryRank.GranMaestro) { text3 = string.Format("\ud83d\udc51 {0}: {1} (GRAN MAESTRO ★★★★★) ({2})\n¡Dominio Supremo Alcanzado! {3}\n{4}", value.GetName(), (currentRankInfo != null) ? currentRankInfo.GetTitle() : "Gran Maestro", value.GetCategory(), value.GetSummary(), (currentRankInfo != null) ? currentRankInfo.GetPerks().Replace("\n", " | ") : ""); } else { int num2 = nextRankInfo?.RequiredAmount ?? progress; string text4 = ((nextRankInfo != null) ? nextRankInfo.GetQuestDesc() : ""); string text5 = ((nextRankInfo != null) ? nextRankInfo.GetPerks().Replace("\n", " ") : ""); text3 = string.Format("✔ {0}: {1} (Rango {2}) ({3})\nPoderes Activos: {4}\nSiguiente Rango ({5}): {6} [Progreso: {7} / {8}]\nPróximo Poder: {9}", value.GetName(), (currentRankInfo != null) ? currentRankInfo.GetTitle() : rank.ToString(), (int)rank, value.GetCategory(), (currentRankInfo != null) ? currentRankInfo.GetPerks().Replace("\n", " | ") : "", (nextRankInfo != null) ? nextRankInfo.GetTitle() : "", text4, progress, num2, text5); } if (value.Id == MasteryId.ApexTracker) { string text6 = string.Format(isEs ? "\n\ud83c\udfaf Remates Proyectil: {0}/15 | Enemigos 1★+: {1}/20 | Biomas: {2}/3 | Jefes Distancia: {3}/2" : "\n\ud83c\udfaf Projectile Finishes: {0}/15 | 1★+ Foes: {1}/20 | Biomes: {2}/3 | Ranged Bosses: {3}/2", MasteryDefinition.GetCustomInt(player, "TM_Apex_ProjectileKills"), MasteryDefinition.GetCustomInt(player, "TM_Apex_StarKills"), MasteryDefinition.GetCustomInt(player, "TM_Apex_BiomeCount"), MasteryDefinition.GetCustomInt(player, "TM_Apex_BossCount")); text3 += text6; } else if (value.Id == MasteryId.BeastShaman) { float num3 = (player.m_customData.ContainsKey("TM_LastPactTime") ? float.Parse(player.m_customData["TM_LastPactTime"]) : (-2000f)); float num4 = ((rank >= MasteryRank.GranMaestro) ? 600f : 900f); float num5 = Mathf.Max(0f, num4 - (Time.time - num3)); string text7 = ((num5 > 0f) ? $"{num5:F0}s CD" : (isEs ? "Listo" : "Ready")); string text8 = string.Format(isEs ? "\n\ud83c\udf3f Ofrenda: {0} | Consagración: {1} | Ritual Protección: {2} | Pacto de Vida: {3}" : "\n\ud83c\udf3f Offering: {0} | Consecration: {1} | Protection Ritual: {2} | Life Pact: {3}", player.m_customData.ContainsKey("TM_Shaman_Ritual_Offering") ? "✔" : "Pendiente", player.m_customData.ContainsKey("TM_Shaman_Ritual_Consecration") ? "✔" : "Pendiente", player.m_customData.ContainsKey("TM_Shaman_Ritual_Protection") ? "✔" : "Pendiente", text7); text3 += text8; } else if (value.Id == MasteryId.MasterTamer) { int customInt = MasteryDefinition.GetCustomInt(player, "TM_TamedSpeciesCount"); bool flag = player.m_customData.ContainsKey("TM_Tamed_AdvancedBeast"); bool flag2 = player.m_customData.ContainsKey("TM_Tamed_EliteFeat"); string text9 = string.Format(isEs ? "\n\ud83d\udc3e Especies Domesticadas: {0}/3 | Bestia Avanzada: {1} | Doma Excepcional: {2}" : "\n\ud83d\udc3e Tamed Species: {0}/3 | Advanced Beast: {1} | Exceptional Taming: {2}", customInt, flag ? "✔" : (isEs ? "Pendiente" : "Pending"), flag2 ? "✔" : (isEs ? "Pendiente" : "Pending")); text3 += text9; } } else { text3 = (isEs ? "Pasa el cursor sobre un medallón rúnico para ver sus 5 rangos, progreso acumulativo y poderes.\nHaz clic en cualquier maestría desbloqueada para equiparla en la Ranura I o II del Códice." : "Hover over any runic medallion to inspect its 5 ranks, cumulative progress, and powers.\nClick any unlocked mastery to equip it to Slot I or II in the Codex."); } GUI.Box(r, text3, tooltipBoxStyle); if (value == null || value.Id != MasteryId.BeastShaman) { return; } MasteryRank rank2 = value.GetRank(player); if (rank2 >= MasteryRank.GranMaestro) { return; } MasteryRank masteryRank = rank2 + 1; if (masteryRank < MasteryRank.Veterano) { return; } Rect val = default(Rect); ((Rect)(ref val))..ctor(((Rect)(ref r)).x + ((Rect)(ref r)).width - 245f, ((Rect)(ref r)).y + 6f, 235f, 28f); bool flag3 = false; bool flag4 = false; string text10 = ""; switch (masteryRank) { case MasteryRank.Veterano: { flag3 = player.m_customData.ContainsKey("TM_Shaman_Ritual_Offering") && player.m_customData["TM_Shaman_Ritual_Offering"] == "true"; int num6 = MasteriesSystem.CountDistinctTrophies(player); flag4 = num6 >= 3; text10 = ((!flag3) ? (isEs ? $"★ Ofrenda ({num6}/3 Trofeos)" : $"★ Offering ({num6}/3 Trophies)") : (isEs ? "✔ Ofrenda Consumada" : "✔ Offering Completed")); break; } case MasteryRank.Experto: flag3 = player.m_customData.ContainsKey("TM_Shaman_Ritual_Consecration") && player.m_customData["TM_Shaman_Ritual_Consecration"] == "true"; flag4 = MasteriesSystem.HasAdvancedTrophy(player); text10 = ((!flag3) ? ((!flag4) ? (isEs ? "★ Consagración (Falta Trofeo)" : "★ Consecration (Need Trophy)") : (isEs ? "★ Consagración Espiritual" : "★ Spiritual Consecration")) : (isEs ? "✔ Consagración Realizada" : "✔ Consecration Done")); break; case MasteryRank.Maestro: flag3 = player.m_customData.ContainsKey("TM_Shaman_Ritual_Protection") && player.m_customData["TM_Shaman_Ritual_Protection"] == "true"; flag4 = MasteriesSystem.HasBossTrophy(player); text10 = ((!flag3) ? ((!flag4) ? (isEs ? "★ Ritual (Falta Trofeo Jefe)" : "★ Ritual (Need Boss Trophy)") : (isEs ? "★ Ritual de Protección" : "★ Protection Ritual")) : (isEs ? "✔ Pacto Sellado" : "✔ Pact Sealed")); break; case MasteryRank.GranMaestro: flag3 = player.m_customData.ContainsKey("TM_Shaman_Ritual_SupremeCommunion") && player.m_customData["TM_Shaman_Ritual_SupremeCommunion"] == "true"; text10 = ((!flag3) ? (isEs ? "★ Consumar Comunión" : "★ Consummate Communion") : (isEs ? "✔ Comunión Suprema" : "✔ Supreme Communion")); flag4 = player.m_customData.ContainsKey("TM_Shaman_PactTriggered") && player.m_customData["TM_Shaman_PactTriggered"] == "true"; break; } Color color = GUI.color; if (flag3) { GUI.color = new Color(0.4f, 0.9f, 0.5f, 0.9f); } else if (!flag4) { GUI.color = new Color(0.9f, 0.75f, 0.4f, 0.95f); } else { GUI.color = new Color(1f, 0.85f, 0.25f, 1f); } if (GUI.Button(val, text10, buttonCardStyle)) { if (flag3) { value.CheckRankUp(player); ((Character)player).Message((MessageType)2, isEs ? "Este ritual ya fue consumado. Rango evaluado." : "This ritual has already been consummated. Rank evaluated.", 0, (Sprite)null, false); } else { string resultMessage; bool flag5 = MasteriesSystem.TryPerformShamanRitual(player, masteryRank, out resultMessage); ((Character)player).Message((MessageType)((!flag5) ? 1 : 2), resultMessage, 0, (Sprite)null, false); if (flag5) { value.CheckRankUp(player); } } } GUI.color = color; } } public static class MasteriesGameplayPatches { private class HitRecord { public Character Attacker; public ZDOID AttackerZDOID; public bool IsRanged; public bool IsSneak; public float Time; } private class BossContribution { public float TotalDamage; public float PlayerRangedDamage; public float LastPlayerHitTime; } private static readonly Dictionary lastEnemyHits = new Dictionary(); private static readonly Dictionary bossTrackers = new Dictionary(); private static readonly HashSet processedApexDeaths = new HashSet(); public static bool HasSurvivingCompanion(Player local, float radius) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)local == (Object)null) { return false; } List allCharacters = Character.GetAllCharacters(); for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if ((Object)(object)val != (Object)null && val.IsTamed() && !val.IsPlayer() && !val.IsDead() && Vector3.Distance(((Component)val).transform.position, ((Component)local).transform.position) <= radius) { return true; } } return false; } [HarmonyPostfix] [HarmonyPatch(typeof(PlayerController), "TakeInput")] public static void PlayerControllerTakeInputPostfix(ref bool __result) { if (MasteriesUI.IsOpen) { __result = false; } } [HarmonyPostfix] [HarmonyPatch(typeof(PlayerController), "InInventoryEtc")] public static void PlayerControllerInInventoryEtcPostfix(ref bool __result) { if (MasteriesUI.IsOpen) { __result = true; } } [HarmonyPrefix] [HarmonyPatch(typeof(Player), "TakeInput")] public static bool PlayerTakeInputPrefix(ref bool __result) { if (MasteriesUI.IsOpen) { __result = false; return false; } return true; } [HarmonyPatch(typeof(Player), "TakeInput")] [HarmonyPostfix] public static void PlayerTakeInputPostfix(ref bool __result) { if (MasteriesUI.IsOpen) { __result = false; } } [HarmonyPostfix] [HarmonyPatch(typeof(GameCamera), "UpdateMouseCapture")] public static void GameCameraUpdateMouseCapturePostfix() { if (MasteriesUI.IsOpen) { Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; try { ZCursor.LockState = (CursorLockMode)0; ZCursor.Show(); } catch { } } } [HarmonyPatch(typeof(GameCamera), "UpdateCamera", new Type[] { typeof(float) })] [HarmonyPrefix] public static bool GameCameraUpdateCameraPrefix() { if (MasteriesUI.IsOpen) { return false; } return true; } [HarmonyPatch(typeof(Character), "ApplyDamage")] [HarmonyPrefix] public static void ApplyDamagePrefix(Character __instance, HitData hit) { //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_03f7: 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_0403: 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_019a: Invalid comparison between Unknown and I4 //IL_041a: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Invalid comparison between Unknown and I4 //IL_04ec: Unknown result type (might be due to invalid IL or missing references) //IL_04f1: Unknown result type (might be due to invalid IL or missing references) //IL_04f8: Unknown result type (might be due to invalid IL or missing references) //IL_0523: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Unknown result type (might be due to invalid IL or missing references) //IL_050f: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Unknown result type (might be due to invalid IL or missing references) //IL_044d: Invalid comparison between Unknown and I4 //IL_0536: Unknown result type (might be due to invalid IL or missing references) //IL_053c: Invalid comparison between Unknown and I4 //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_0457: Invalid comparison between Unknown and I4 //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Invalid comparison between Unknown and I4 //IL_08aa: Unknown result type (might be due to invalid IL or missing references) //IL_08b5: Unknown result type (might be due to invalid IL or missing references) //IL_0636: Unknown result type (might be due to invalid IL or missing references) //IL_053f: Unknown result type (might be due to invalid IL or missing references) //IL_0546: Invalid comparison between Unknown and I4 //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Invalid comparison between Unknown and I4 //IL_063b: Unknown result type (might be due to invalid IL or missing references) //IL_0642: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Invalid comparison between Unknown and I4 //IL_0485: Unknown result type (might be due to invalid IL or missing references) //IL_048a: Unknown result type (might be due to invalid IL or missing references) //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_049c: Unknown result type (might be due to invalid IL or missing references) //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a1: Invalid comparison between Unknown and I4 //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04a7: Invalid comparison between Unknown and I4 //IL_0578: Unknown result type (might be due to invalid IL or missing references) //IL_057d: Unknown result type (might be due to invalid IL or missing references) //IL_058a: Unknown result type (might be due to invalid IL or missing references) //IL_058f: Unknown result type (might be due to invalid IL or missing references) //IL_0591: Unknown result type (might be due to invalid IL or missing references) //IL_0594: Invalid comparison between Unknown and I4 //IL_04a9: Unknown result type (might be due to invalid IL or missing references) //IL_04ac: Invalid comparison between Unknown and I4 //IL_0596: Unknown result type (might be due to invalid IL or missing references) //IL_059a: Invalid comparison between Unknown and I4 //IL_059c: Unknown result type (might be due to invalid IL or missing references) //IL_059f: Invalid comparison between Unknown and I4 if ((Object)(object)__instance == (Object)null || hit == null) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } Character attacker = hit.GetAttacker(); if ((Object)(object)attacker != (Object)null && attacker.IsTamed() && MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastKing)) { MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastKing, out var value); MasteryRank masteryRank = value?.GetRank(localPlayer) ?? MasteryRank.Locked; float num = 1.02f; if (masteryRank == MasteryRank.Veterano) { num = 1.04f; } else if (masteryRank == MasteryRank.Experto) { num = 1.07f; } else if (masteryRank == MasteryRank.Maestro) { num = 1.1f; } else if (masteryRank >= MasteryRank.GranMaestro) { num = 1.15f; } ref DamageTypes damage = ref hit.m_damage; damage.m_blunt *= num; ref DamageTypes damage2 = ref hit.m_damage; damage2.m_slash *= num; ref DamageTypes damage3 = ref hit.m_damage; damage3.m_pierce *= num; } if ((Object)(object)attacker != (Object)null && attacker.IsTamed() && MasteriesSystem.HasMastery(localPlayer, MasteryId.StormBeasts)) { MasteriesSystem.Catalog.TryGetValue(MasteryId.StormBeasts, out var value2); MasteryRank masteryRank2 = value2?.GetRank(localPlayer) ?? MasteryRank.Locked; if (masteryRank2 >= MasteryRank.Maestro) { ref DamageTypes damage4 = ref hit.m_damage; damage4.m_frost += 5f; ref DamageTypes damage5 = ref hit.m_damage; damage5.m_poison += 3f; } } bool flag = (Object)(object)attacker == (Object)(object)localPlayer || (hit.m_attacker != ZDOID.None && hit.m_attacker == ((Character)localPlayer).GetZDOID()); if (flag && MasteriesSystem.HasMastery(localPlayer, MasteryId.ApexTracker)) { bool flag2 = hit.m_ranged || (int)hit.m_skill == 8 || (int)hit.m_skill == 14; if (!flag2 && ((Humanoid)localPlayer).GetCurrentWeapon() != null && ((Humanoid)localPlayer).GetCurrentWeapon().m_shared != null) { SkillType skillType = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_skillType; ItemType itemType = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_itemType; if ((int)skillType == 8 || (int)skillType == 14 || (int)itemType == 4) { flag2 = true; } } bool flag3 = hit.m_backstabBonus > 1f || ((Character)localPlayer).IsSneaking(); if ((flag2 || flag3) && MasteriesSystem.Catalog.TryGetValue(MasteryId.ApexTracker, out var value3)) { MasteryRank rank = value3.GetRank(localPlayer); float num2 = 1.01f; if (rank == MasteryRank.Veterano) { num2 = 1.02f; } else if (rank == MasteryRank.Experto) { num2 = 1.03f; } else if (rank == MasteryRank.Maestro) { num2 = 1.05f; } else if (rank >= MasteryRank.GranMaestro) { num2 = 1.07f; } ref DamageTypes damage6 = ref hit.m_damage; damage6.m_blunt *= num2; ref DamageTypes damage7 = ref hit.m_damage; damage7.m_slash *= num2; ref DamageTypes damage8 = ref hit.m_damage; damage8.m_pierce *= num2; } } if ((Object)(object)attacker != (Object)null && attacker.IsTamed() && !attacker.IsPlayer() && MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastShaman) && !__instance.IsTamed() && !__instance.IsPlayer()) { float num3 = (localPlayer.m_customData.ContainsKey("TM_LastShamanRecovery") ? float.Parse(localPlayer.m_customData["TM_LastShamanRecovery"]) : (-100f)); if (Time.time - num3 >= 5f) { localPlayer.m_customData["TM_LastShamanRecovery"] = Time.time.ToString(); MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value4); MasteryRank masteryRank3 = value4?.GetRank(localPlayer) ?? MasteryRank.Locked; float num4 = 1f; float num5 = 0f; if (masteryRank3 == MasteryRank.Veterano) { num4 = 2f; } else if (masteryRank3 == MasteryRank.Experto) { num4 = 3f; num5 = 1f; } else if (masteryRank3 == MasteryRank.Maestro) { num4 = 4f; num5 = 2f; } else if (masteryRank3 >= MasteryRank.GranMaestro) { num4 = 5f; num5 = 3f; } ((Character)localPlayer).AddStamina(num4); if (num5 > 0f) { ((Character)localPlayer).AddEitr(num5); } } } if (__instance.IsBoss()) { ZDOID zDOID = __instance.GetZDOID(); if (!bossTrackers.TryGetValue(zDOID, out var value5)) { value5 = new BossContribution(); bossTrackers[zDOID] = value5; } value5.TotalDamage += hit.GetTotalDamage(); if (flag) { bool flag4 = hit.m_ranged || (int)hit.m_skill == 8 || (int)hit.m_skill == 14; if (!flag4 && ((Humanoid)localPlayer).GetCurrentWeapon() != null && ((Humanoid)localPlayer).GetCurrentWeapon().m_shared != null) { SkillType skillType2 = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_skillType; ItemType itemType2 = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_itemType; if ((int)skillType2 == 8 || (int)skillType2 == 14 || (int)itemType2 == 4) { flag4 = true; } } if (flag4) { value5.PlayerRangedDamage += hit.GetTotalDamage(); value5.LastPlayerHitTime = Time.time; } } } if (!__instance.IsTamed() && !__instance.IsPlayer()) { ZDOID zDOID2 = __instance.GetZDOID(); if (!lastEnemyHits.TryGetValue(zDOID2, out var value6)) { value6 = new HitRecord(); lastEnemyHits[zDOID2] = value6; } value6.Attacker = attacker; value6.AttackerZDOID = hit.m_attacker; bool flag5 = hit.m_ranged || (int)hit.m_skill == 8 || (int)hit.m_skill == 14; if (!flag5 && flag && ((Humanoid)localPlayer).GetCurrentWeapon() != null && ((Humanoid)localPlayer).GetCurrentWeapon().m_shared != null) { SkillType skillType3 = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_skillType; ItemType itemType3 = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_itemType; if ((int)skillType3 == 8 || (int)skillType3 == 14 || (int)itemType3 == 4) { flag5 = true; } } value6.IsRanged = flag5; value6.IsSneak = hit.m_backstabBonus > 1f || ((Character)localPlayer).IsSneaking(); value6.Time = Time.time; } if (__instance.IsTamed()) { if (MasteriesSystem.Catalog.TryGetValue(MasteryId.FeralBastion, out var value7)) { value7.AddProgress(localPlayer, (int)hit.GetTotalDamage()); if ((Object)(object)attacker != (Object)null && attacker.GetLevel() >= 2) { value7.SetSpecialFeat(localPlayer, "survive_1star"); } Biome val = (Biome)(((Object)(object)EnvMan.instance != (Object)null) ? ((int)EnvMan.instance.GetCurrentBiome()) : 0); string key = "TM_FB_Biome_" + ((object)val).ToString(); if (!localPlayer.m_customData.ContainsKey(key)) { localPlayer.m_customData[key] = "true"; int num6 = (localPlayer.m_customData.ContainsKey("TM_FB_BiomeCount") ? int.Parse(localPlayer.m_customData["TM_FB_BiomeCount"]) : 0); num6++; localPlayer.m_customData["TM_FB_BiomeCount"] = num6.ToString(); if (num6 >= 3) { value7.SetSpecialFeat(localPlayer, "resist_3_biomes"); } } if ((Object)(object)attacker != (Object)null && attacker.IsBoss()) { value7.SetSpecialFeat(localPlayer, "boss_protect_survive"); string key2 = "TM_FB_Boss_" + ((Object)((Component)attacker).gameObject).name; if (!localPlayer.m_customData.ContainsKey(key2)) { localPlayer.m_customData[key2] = "true"; int num7 = (localPlayer.m_customData.ContainsKey("TM_FB_BossCount") ? int.Parse(localPlayer.m_customData["TM_FB_BossCount"]) : 0); num7++; localPlayer.m_customData["TM_FB_BossCount"] = num7.ToString(); if (num7 >= 2) { value7.SetSpecialFeat(localPlayer, "boss_protect_survive_2"); } } } } if (MasteriesSystem.HasMastery(localPlayer, MasteryId.FeralBastion)) { MasteriesSystem.Catalog.TryGetValue(MasteryId.FeralBastion, out var value8); MasteryRank masteryRank4 = value8?.GetRank(localPlayer) ?? MasteryRank.Locked; float num8 = 1f; if (masteryRank4 == MasteryRank.Veterano) { num8 = 0.98f; } else if (masteryRank4 == MasteryRank.Experto) { num8 = 0.97f; } else if (masteryRank4 == MasteryRank.Maestro) { num8 = 0.95f; } else if (masteryRank4 >= MasteryRank.GranMaestro) { num8 = 0.93f; } if (masteryRank4 >= MasteryRank.GranMaestro && __instance.GetHealth() / __instance.GetMaxHealth() < 0.3f) { num8 *= 0.85f; } ref DamageTypes damage9 = ref hit.m_damage; damage9.m_blunt *= num8; ref DamageTypes damage10 = ref hit.m_damage; damage10.m_slash *= num8; ref DamageTypes damage11 = ref hit.m_damage; damage11.m_pierce *= num8; ref DamageTypes damage12 = ref hit.m_damage; damage12.m_fire *= num8; ref DamageTypes damage13 = ref hit.m_damage; damage13.m_frost *= num8; ref DamageTypes damage14 = ref hit.m_damage; damage14.m_poison *= num8; } } bool flag6 = (Object)(object)__instance != (Object)null && __instance.IsTamed() && !__instance.IsPlayer() && Vector3.Distance(((Component)__instance).transform.position, ((Component)localPlayer).transform.position) <= 30f; bool flag7 = (Object)(object)__instance == (Object)(object)localPlayer; if ((!flag6 && !flag7) || !MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastShaman) || !MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value9)) { return; } MasteryRank rank2 = value9.GetRank(localPlayer); if (rank2 < MasteryRank.Maestro) { return; } float num9 = ((rank2 >= MasteryRank.GranMaestro) ? 600f : 900f); float totalDamage = hit.GetTotalDamage(); if (__instance.GetHealth() - totalDamage <= 0f) { float num10 = (localPlayer.m_customData.ContainsKey("TM_LastPactTime") ? float.Parse(localPlayer.m_customData["TM_LastPactTime"]) : (-2000f)); if (Time.time - num10 >= num9) { localPlayer.m_customData["TM_LastPactTime"] = Time.time.ToString(); localPlayer.m_customData["TM_Shaman_PactTriggered"] = "true"; hit.m_damage.m_blunt = 0f; hit.m_damage.m_slash = 0f; hit.m_damage.m_pierce = 0f; hit.m_damage.m_chop = 0f; hit.m_damage.m_pickaxe = 0f; hit.m_damage.m_fire = 0f; hit.m_damage.m_frost = 0f; hit.m_damage.m_lightning = 0f; hit.m_damage.m_poison = 0f; hit.m_damage.m_spirit = 0f; float health = Mathf.Max(10f, __instance.GetMaxHealth() * 0.3f); __instance.SetHealth(health); string arg = ((!flag7) ? __instance.GetHoverName() : ((Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish") ? "tu vida" : "your life")); ((Character)localPlayer).Message((MessageType)2, $"¡El Pacto de Vida del Chamán ha salvado a {arg} de la muerte!", 0, (Sprite)null, false); } } } [HarmonyPrefix] [HarmonyPatch(typeof(Character), "OnDeath")] public static void OnDeathPrefix(Character __instance, HitData ___m_lastHit) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_03c4: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0586: Unknown result type (might be due to invalid IL or missing references) //IL_0588: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_0428: Unknown result type (might be due to invalid IL or missing references) //IL_05b4: Unknown result type (might be due to invalid IL or missing references) //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_04c4: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_04ee: Invalid comparison between Unknown and I4 //IL_06b1: Unknown result type (might be due to invalid IL or missing references) //IL_04f2: Unknown result type (might be due to invalid IL or missing references) //IL_04f9: Invalid comparison between Unknown and I4 //IL_06b6: Unknown result type (might be due to invalid IL or missing references) //IL_06bd: Unknown result type (might be due to invalid IL or missing references) //IL_075c: Unknown result type (might be due to invalid IL or missing references) //IL_0527: Unknown result type (might be due to invalid IL or missing references) //IL_052c: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_053e: Unknown result type (might be due to invalid IL or missing references) //IL_0540: Unknown result type (might be due to invalid IL or missing references) //IL_0543: Invalid comparison between Unknown and I4 //IL_0545: Unknown result type (might be due to invalid IL or missing references) //IL_0549: Invalid comparison between Unknown and I4 //IL_0884: Unknown result type (might be due to invalid IL or missing references) //IL_054b: Unknown result type (might be due to invalid IL or missing references) //IL_054e: Invalid comparison between Unknown and I4 if ((Object)(object)__instance == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } bool flag = false; List allCharacters = Character.GetAllCharacters(); for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if (!((Object)(object)val != (Object)null) || !val.IsTamed() || !(Vector3.Distance(((Component)val).transform.position, ((Component)localPlayer).transform.position) <= 25f)) { continue; } flag = true; if (!MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastKing)) { continue; } float num = (localPlayer.m_customData.ContainsKey("TM_LastBKHealTime") ? float.Parse(localPlayer.m_customData["TM_LastBKHealTime"]) : (-100f)); if (Time.time - num >= 15f) { MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastKing, out var value); MasteryRank masteryRank = value?.GetRank(localPlayer) ?? MasteryRank.Locked; float num2 = 0f; if (masteryRank >= MasteryRank.GranMaestro) { num2 = 0.04f; } else if (masteryRank >= MasteryRank.Maestro) { num2 = 0.03f; } else if (masteryRank >= MasteryRank.Experto) { num2 = 0.02f; } else if (masteryRank >= MasteryRank.Veterano) { num2 = 0.01f; } if (num2 > 0f) { localPlayer.m_customData["TM_LastBKHealTime"] = Time.time.ToString(); float num3 = val.GetMaxHealth() * num2; val.Heal(num3, true); } } } if (flag && !__instance.IsTamed()) { if (MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastKing, out var value2)) { value2.AddProgress(localPlayer, 1); if (__instance.GetLevel() >= 2) { int num4 = (localPlayer.m_customData.ContainsKey("TM_BK_StarKills") ? int.Parse(localPlayer.m_customData["TM_BK_StarKills"]) : 0); num4++; localPlayer.m_customData["TM_BK_StarKills"] = num4.ToString(); if (num4 >= 15) { value2.SetSpecialFeat(localPlayer, "15_star_enemies"); } } Biome val2 = (Biome)(((Object)(object)EnvMan.instance != (Object)null) ? ((int)EnvMan.instance.GetCurrentBiome()) : 0); string key = "TM_BK_Biome_" + ((object)val2).ToString(); if (!localPlayer.m_customData.ContainsKey(key)) { localPlayer.m_customData[key] = "true"; int num5 = (localPlayer.m_customData.ContainsKey("TM_BK_BiomeCount") ? int.Parse(localPlayer.m_customData["TM_BK_BiomeCount"]) : 0); num5++; localPlayer.m_customData["TM_BK_BiomeCount"] = num5.ToString(); if (num5 >= 3) { value2.SetSpecialFeat(localPlayer, "3_biomes"); } } if (__instance.IsBoss()) { value2.SetSpecialFeat(localPlayer, "boss_survival_1"); string key2 = "TM_BK_Boss_" + ((Object)((Component)__instance).gameObject).name; if (!localPlayer.m_customData.ContainsKey(key2)) { localPlayer.m_customData[key2] = "true"; int num6 = (localPlayer.m_customData.ContainsKey("TM_BK_BossCount") ? int.Parse(localPlayer.m_customData["TM_BK_BossCount"]) : 0); num6++; localPlayer.m_customData["TM_BK_BossCount"] = num6.ToString(); if (num6 >= 3) { value2.SetSpecialFeat(localPlayer, "boss_survival_3"); } } } } if ((Object)(object)EnvMan.instance != (Object)null && (EnvMan.IsFreezing() || EnvMan.IsWet()) && MasteriesSystem.Catalog.TryGetValue(MasteryId.StormBeasts, out var value3)) { value3.AddProgress(localPlayer, 1); } } if (__instance.IsTamed() || __instance.IsPlayer()) { return; } ZDOID zDOID = __instance.GetZDOID(); if (zDOID != ZDOID.None && processedApexDeaths.Contains(zDOID)) { return; } HitRecord value4 = null; bool flag2 = false; bool flag3 = false; bool flag4 = false; if (zDOID != ZDOID.None && lastEnemyHits.TryGetValue(zDOID, out value4)) { if (((Object)(object)value4.Attacker == (Object)(object)localPlayer || (value4.AttackerZDOID != ZDOID.None && value4.AttackerZDOID == ((Character)localPlayer).GetZDOID())) && Time.time - value4.Time <= 10f && (value4.IsRanged || value4.IsSneak)) { flag2 = true; flag3 = value4.IsRanged; flag4 = value4.IsSneak; } lastEnemyHits.Remove(zDOID); } if (!flag2 && ___m_lastHit != null) { Character attacker = ___m_lastHit.GetAttacker(); if ((Object)(object)attacker == (Object)(object)localPlayer || (___m_lastHit.m_attacker != ZDOID.None && ___m_lastHit.m_attacker == ((Character)localPlayer).GetZDOID())) { bool flag5 = ___m_lastHit.m_ranged || (int)___m_lastHit.m_skill == 8 || (int)___m_lastHit.m_skill == 14; if (!flag5 && ((Humanoid)localPlayer).GetCurrentWeapon() != null && ((Humanoid)localPlayer).GetCurrentWeapon().m_shared != null) { SkillType skillType = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_skillType; ItemType itemType = ((Humanoid)localPlayer).GetCurrentWeapon().m_shared.m_itemType; if ((int)skillType == 8 || (int)skillType == 14 || (int)itemType == 4) { flag5 = true; } } bool flag6 = ___m_lastHit.m_backstabBonus > 1f || ((Character)localPlayer).IsSneaking(); if (flag5 || flag6) { flag2 = true; flag3 = flag5; flag4 = flag6; } } } if (!flag2) { return; } if (zDOID != ZDOID.None) { if (processedApexDeaths.Count > 300) { processedApexDeaths.Clear(); } processedApexDeaths.Add(zDOID); } if (!MasteriesSystem.Catalog.TryGetValue(MasteryId.ApexTracker, out var value5)) { return; } value5.AddProgress(localPlayer, 1); if (flag3) { int num7 = (localPlayer.m_customData.ContainsKey("TM_Apex_ProjectileKills") ? int.Parse(localPlayer.m_customData["TM_Apex_ProjectileKills"]) : 0); num7++; localPlayer.m_customData["TM_Apex_ProjectileKills"] = num7.ToString(); if (num7 >= 15) { value5.SetSpecialFeat(localPlayer, "apex_15_projectiles"); } } if (__instance.GetLevel() >= 2) { int num8 = (localPlayer.m_customData.ContainsKey("TM_Apex_StarKills") ? int.Parse(localPlayer.m_customData["TM_Apex_StarKills"]) : 0); num8++; localPlayer.m_customData["TM_Apex_StarKills"] = num8.ToString(); if (num8 >= 20) { value5.SetSpecialFeat(localPlayer, "apex_20_stars"); } } Biome val3 = (Biome)(((Object)(object)EnvMan.instance != (Object)null) ? ((int)EnvMan.instance.GetCurrentBiome()) : 0); string key3 = "TM_Apex_Biome_" + ((object)val3).ToString(); if (!localPlayer.m_customData.ContainsKey(key3)) { localPlayer.m_customData[key3] = "true"; int num9 = (localPlayer.m_customData.ContainsKey("TM_Apex_BiomeCount") ? int.Parse(localPlayer.m_customData["TM_Apex_BiomeCount"]) : 0); num9++; localPlayer.m_customData["TM_Apex_BiomeCount"] = num9.ToString(); if (num9 >= 3) { value5.SetSpecialFeat(localPlayer, "apex_3_biomes"); } } if (__instance.IsBoss() && bossTrackers.TryGetValue(zDOID, out var value6)) { float num10 = Mathf.Max(1f, Mathf.Max(__instance.GetMaxHealth(), value6.TotalDamage)); float num11 = value6.PlayerRangedDamage / num10; if (num11 >= 0.2f && Time.time - value6.LastPlayerHitTime <= 60f && HasSurvivingCompanion(localPlayer, 40f)) { string text = ((Object)((Component)__instance).gameObject).name.Replace("(Clone)", ""); string key4 = "TM_Apex_Boss_" + text; if (!localPlayer.m_customData.ContainsKey(key4)) { localPlayer.m_customData[key4] = "true"; int num12 = (localPlayer.m_customData.ContainsKey("TM_Apex_BossCount") ? int.Parse(localPlayer.m_customData["TM_Apex_BossCount"]) : 0); num12++; localPlayer.m_customData["TM_Apex_BossCount"] = num12.ToString(); if (num12 >= 1) { value5.SetSpecialFeat(localPlayer, "apex_boss_ranged_1"); } if (num12 >= 2) { value5.SetSpecialFeat(localPlayer, "apex_boss_ranged_2"); } } } bossTrackers.Remove(zDOID); } if ((__instance.GetLevel() >= 3 || __instance.IsBoss()) && HasSurvivingCompanion(localPlayer, 30f)) { localPlayer.m_customData["TM_Apex_CoordinatedHunt"] = "true"; value5.SetSpecialFeat(localPlayer, "apex_coordinated_hunt"); } value5.CheckRankUp(localPlayer); MasteriesSystem.Log.LogInfo((object)string.Format("[TameMate Apex] Baja registrada: foe={0}, nivel={1}, proyectil={2}, sigilo={3}, progreso={4}/75, remates_proyectil={5}/15", ((Object)(object)((Component)__instance).gameObject != (Object)null) ? ((Object)((Component)__instance).gameObject).name : "unknown", __instance.GetLevel(), flag3, flag4, value5.GetProgress(localPlayer), MasteryDefinition.GetCustomInt(localPlayer, "TM_Apex_ProjectileKills"))); } [HarmonyPatch(typeof(Character), "AddStaggerDamage")] [HarmonyPrefix] public static bool AddStaggerDamagePrefix(Character __instance) { if ((Object)(object)__instance == (Object)null || !__instance.IsTamed()) { return true; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && MasteriesSystem.HasMastery(localPlayer, MasteryId.StormBeasts)) { return false; } return true; } [HarmonyPrefix] [HarmonyPatch(typeof(Player), "UseStamina")] public static void PlayerUseStaminaPrefix(Player __instance, ref float v) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && ((Character)__instance).IsAttached() && MasteriesSystem.HasMastery(__instance, MasteryId.GrandCavalier)) { MasteriesSystem.Catalog.TryGetValue(MasteryId.GrandCavalier, out var value); MasteryRank masteryRank = value?.GetRank(__instance) ?? MasteryRank.Locked; float num = 0.95f; if (masteryRank == MasteryRank.Veterano) { num = 0.9f; } else if (masteryRank == MasteryRank.Experto) { num = 0.85f; } else if (masteryRank == MasteryRank.Maestro) { num = 0.8f; } else if (masteryRank >= MasteryRank.GranMaestro) { num = 0.75f; } v *= num; } } [HarmonyPostfix] [HarmonyPatch(typeof(Player), "IsEncumbered")] public static void IsEncumberedPostfix(Player __instance, ref bool __result) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && ((Character)__instance).IsAttached() && MasteriesSystem.HasMastery(__instance, MasteryId.GrandCavalier)) { MasteriesSystem.Catalog.TryGetValue(MasteryId.GrandCavalier, out var value); MasteryRank masteryRank = value?.GetRank(__instance) ?? MasteryRank.Locked; if (masteryRank >= MasteryRank.Experto) { __result = false; } } } [HarmonyPrefix] [HarmonyPatch(typeof(Tameable), "DecreaseRemainingTime")] public static void DecreaseRemainingTimePrefix(Tameable __instance, ref float time) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && MasteriesSystem.HasMastery(localPlayer, MasteryId.MasterTamer)) { MasteriesSystem.Catalog.TryGetValue(MasteryId.MasterTamer, out var value); MasteryRank masteryRank = value?.GetRank(localPlayer) ?? MasteryRank.Locked; float num = 1.03f; if (masteryRank == MasteryRank.Veterano) { num = 1.05f; } else if (masteryRank == MasteryRank.Experto) { num = 1.07f; } else if (masteryRank == MasteryRank.Maestro) { num = 1.1f; } else if (masteryRank >= MasteryRank.GranMaestro) { num = 1.12f; } time *= num; } } [HarmonyPatch(typeof(Tameable), "Tame")] [HarmonyPostfix] public static void TameableTamePostfix(Tameable __instance) { if (!((Object)(object)__instance == (Object)null)) { Character component = ((Component)__instance).GetComponent(); MasteriesSystem.RegisterTamedCreature(component, Player.m_localPlayer); } } [HarmonyPatch(typeof(Tameable), "OnConsumedItem")] [HarmonyPostfix] public static void TameableOnConsumedItemPostfix(Tameable __instance, ItemDrop item) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } Character component = ((Component)__instance).GetComponent(); if (!((Object)(object)component != (Object)null) || !component.IsTamed() || !(Vector3.Distance(((Component)__instance).transform.position, ((Component)localPlayer).transform.position) <= 25f)) { return; } string key = "TM_LastFed_" + ((object)component.GetZDOID()/*cast due to .constrained prefix*/).ToString(); float num = (localPlayer.m_customData.ContainsKey(key) ? float.Parse(localPlayer.m_customData[key]) : (-100f)); if (Time.time - num >= 8f) { localPlayer.m_customData[key] = Time.time.ToString(); if (MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value)) { value.AddProgress(localPlayer, 1); } } } [HarmonyPostfix] [HarmonyPatch(typeof(Player), "OnSpawned")] public static void PlayerOnSpawnedPostfix(Player __instance) { if ((Object)(object)__instance != (Object)null && (Object)(object)__instance == (Object)(object)Player.m_localPlayer) { MasteriesSystem.ValidatePlayerCoherence(__instance); } } [HarmonyPostfix] [HarmonyPatch(typeof(Procreation), "Procreate")] public static void ProcreatePostfix(Procreation __instance) { //IL_0038: 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) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)__instance == (Object)null) { return; } Character component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsTamed() || Vector3.Distance(((Component)__instance).transform.position, ((Component)localPlayer).transform.position) > 30f) { return; } bool flag = false; ZNetView component2 = ((Component)component).GetComponent(); if ((Object)(object)component2 != (Object)null && component2.IsValid() && component2.IsOwner()) { flag = true; } MasteriesSystem.Catalog.TryGetValue(MasteryId.MasterTamer, out var value); int num = value?.GetProgress(localPlayer) ?? 0; if (!flag && num == 0) { return; } List confirmedNewbornsForCurrentProcreate = PriorityFixesIntegration.GetConfirmedNewbornsForCurrentProcreate(__instance); if (confirmedNewbornsForCurrentProcreate == null || confirmedNewbornsForCurrentProcreate.Count == 0) { return; } if (MasteriesSystem.Catalog.TryGetValue(MasteryId.AlphaBloodline, out var value2)) { value2.AddProgress(localPlayer, 1); } if (!MasteriesSystem.HasMastery(localPlayer, MasteryId.AlphaBloodline)) { return; } for (int i = 0; i < confirmedNewbornsForCurrentProcreate.Count; i++) { Character val = confirmedNewbornsForCurrentProcreate[i]; if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)component && !val.IsDead() && val.GetLevel() < 3 && Random.value < 0.5f) { val.SetLevel(val.GetLevel() + 1); break; } } } [HarmonyPostfix] [HarmonyPatch(typeof(Player), "GetStealthFactor")] public static void PlayerGetStealthFactorPostfix(Player __instance, ref float __result) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && MasteriesSystem.HasMastery(__instance, MasteryId.ApexTracker) && MasteriesSystem.Catalog.TryGetValue(MasteryId.ApexTracker, out var value)) { MasteryRank rank = value.GetRank(__instance); float num = 0f; if (rank >= MasteryRank.GranMaestro) { num = 0.15f; } else if (rank >= MasteryRank.Maestro) { num = 0.1f; } else if (rank >= MasteryRank.Experto) { num = 0.08f; } else if (rank >= MasteryRank.Veterano) { num = 0.05f; } else if (rank >= MasteryRank.Iniciado) { num = 0.03f; } if (num > 0f) { __result = Mathf.Clamp01(__result * (1f - num)); } } } [HarmonyPatch(typeof(Character), "GetNoiseRange")] [HarmonyPostfix] public static void CharacterGetNoiseRangePostfix(Character __instance, ref float __result) { Player val = (Player)(object)((__instance is Player) ? __instance : null); if (!((Object)(object)val == (Object)null) && !((Object)(object)val != (Object)(object)Player.m_localPlayer) && MasteriesSystem.HasMastery(val, MasteryId.ApexTracker) && MasteriesSystem.Catalog.TryGetValue(MasteryId.ApexTracker, out var value)) { MasteryRank rank = value.GetRank(val); float num = 0f; if (rank >= MasteryRank.GranMaestro) { num = 0.15f; } else if (rank >= MasteryRank.Maestro) { num = 0.1f; } else if (rank >= MasteryRank.Experto) { num = 0.08f; } else if (rank >= MasteryRank.Veterano) { num = 0.05f; } else if (rank >= MasteryRank.Iniciado) { num = 0.03f; } if (num > 0f) { __result *= 1f - num; } } } [HarmonyPatch(typeof(Character), "GetRunSpeedFactor")] [HarmonyPostfix] public static void CharacterGetRunSpeedFactorPostfix(Character __instance, ref float __result) { //IL_0038: 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) if (!((Object)(object)__instance == (Object)null) && __instance.IsTamed() && !__instance.IsPlayer()) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastShaman) && Vector3.Distance(((Component)__instance).transform.position, ((Component)localPlayer).transform.position) <= 25f && MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value) && value.GetRank(localPlayer) >= MasteryRank.Veterano) { __result *= 1.05f; } } } [HarmonyPatch(typeof(Character), "GetJogSpeedFactor")] [HarmonyPostfix] public static void CharacterGetJogSpeedFactorPostfix(Character __instance, ref float __result) { //IL_0038: 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) if (!((Object)(object)__instance == (Object)null) && __instance.IsTamed() && !__instance.IsPlayer()) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastShaman) && Vector3.Distance(((Component)__instance).transform.position, ((Component)localPlayer).transform.position) <= 25f && MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value) && value.GetRank(localPlayer) >= MasteryRank.Veterano) { __result *= 1.05f; } } } [HarmonyPatch(typeof(ItemStand), "GetHoverText")] [HarmonyPostfix] public static void ItemStandGetHoverTextPostfix(ItemStand __instance, ref string __result) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || !MasteriesSystem.HasMastery(localPlayer, MasteryId.BeastShaman) || !MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value)) { return; } MasteryRank rank = value.GetRank(localPlayer); if (rank < MasteryRank.GranMaestro) { MasteryRank masteryRank = rank + 1; if (masteryRank >= MasteryRank.Veterano && masteryRank <= MasteryRank.Maestro) { __result += "\n[Shift + E] Realizar Ritual Chamánico"; } } } [HarmonyPrefix] [HarmonyPatch(typeof(ItemStand), "Interact")] public static bool ItemStandInteractPrefix(ItemStand __instance, Humanoid user, bool hold, bool alt) { Player val = (Player)(object)((user is Player) ? user : null); if ((Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)Player.m_localPlayer) { return true; } if ((Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303)) && MasteriesSystem.HasMastery(val, MasteryId.BeastShaman) && MasteriesSystem.Catalog.TryGetValue(MasteryId.BeastShaman, out var value)) { MasteryRank rank = value.GetRank(val); if (rank < MasteryRank.GranMaestro) { MasteryRank targetRank = rank + 1; string resultMessage; bool flag = MasteriesSystem.TryPerformShamanRitual(val, targetRank, out resultMessage); ((Character)val).Message((MessageType)((!flag) ? 1 : 2), resultMessage, 0, (Sprite)null, false); return false; } } return true; } [HarmonyPatch(typeof(MessageHud), "ShowMessage")] [HarmonyPrefix] public static void MessageHudShowMessagePrefix(ref string text) { if (text != null && (text.IndexOf("Bienvenido a TameMate", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Welcome to TameMate", StringComparison.OrdinalIgnoreCase) >= 0)) { text = text.Replace("0.7.45", "0.8.0").Replace("0.7.0", "0.8.0").Replace("0.7.33", "0.8.0") .Replace("0.7.39", "0.8.0") .Replace("0.7.44", "0.8.0") .Replace("0.7.56", "0.8.0"); if (text.IndexOf("F10", StringComparison.OrdinalIgnoreCase) < 0) { text = text.Replace("para seleccionar tu Dificultad Global o consultar la Guía del Códice.", "para Dificultad, [F10] para Arquetipos RPG o [F7] para Maestrías.").Replace("to select your Global Difficulty or consult the Codex Guide.", "for Difficulty, [F10] for RPG Archetypes or [F7] for Masteries."); } } } [HarmonyPostfix] [HarmonyPatch(typeof(Localization), "Localize", new Type[] { typeof(string) })] public static void LocalizationLocalizePostfix(ref string __result) { if (__result != null && (__result.IndexOf("TameMate 0.7.", StringComparison.OrdinalIgnoreCase) >= 0 || __result.IndexOf("TAMEMATE 0.7.", StringComparison.OrdinalIgnoreCase) >= 0)) { __result = __result.Replace("TameMate 0.7.45", "TameMate 0.8.0").Replace("TameMate 0.7.0", "TameMate 0.8.0").Replace("TameMate 0.7.33", "TameMate 0.8.0") .Replace("TameMate 0.7.39", "TameMate 0.8.0") .Replace("TAMEMATE 0.7.0", "TAMEMATE 0.8.0") .Replace("TAMEMATE 0.7.39", "TAMEMATE 0.8.0") .Replace("TAMEMATE 0.7.45", "TAMEMATE 0.8.0"); } } [HarmonyPatch(typeof(ModLanguage), "Text")] [HarmonyPostfix] public static void ModLanguageTextPostfix(ref string __result) { if (__result != null) { if (__result.IndexOf("0.7.45", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("0.7.45", "0.8.0"); } if (__result.IndexOf("0.7.39", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("0.7.39", "0.8.0"); } if (__result.IndexOf("0.7.0", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("0.7.0", "0.8.0"); } if (__result.IndexOf("0.7.33", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("0.7.33", "0.8.0"); } if (__result.IndexOf("v0.7.45", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("v0.7.45", "v0.8.0"); } if (__result.IndexOf("v0.6.8", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("v0.6.8", "v0.8.0"); } if (__result.IndexOf("v0.5.9", StringComparison.OrdinalIgnoreCase) >= 0) { __result = __result.Replace("v0.5.9", "v0.8.0"); } } } [HarmonyTranspiler] [HarmonyPatch(typeof(TameMateGuidebook), "OnGUI")] public static IEnumerable GuidebookOnGUITranspiler(IEnumerable instructions) { foreach (CodeInstruction instruction in instructions) { string str = instruction.operand as string; if (instruction.opcode == OpCodes.Ldstr) { switch (str) { case "\ud83d\udcdc TAMEMATE CODEX v0.7.45 · GUIDE & SETTINGS": instruction.operand = "\ud83d\udcdc TAMEMATE CODEX v0.8.0 · GUIDE & SETTINGS"; break; case "\ud83d\udcdc CÓDICE DE TAMEMATE v0.7.45 · GUÍA Y CONFIGURACIÓN": instruction.operand = "\ud83d\udcdc CÓDICE DE TAMEMATE v0.8.0 · GUÍA Y CONFIGURACIÓN"; break; } } yield return instruction; } } [HarmonyPostfix] [HarmonyPatch(typeof(TameMateGuidebook), "get_FullGuideSpanishText")] public static void GuidebookFullSpanishTextPostfix(ref string __result) { if (__result != null) { __result = __result.Replace("0.7.45", "0.8.0").Replace("v0.7.45", "v0.8.0"); } } [HarmonyPatch(typeof(TameMateGuidebook), "get_FullGuideEnglishText")] [HarmonyPostfix] public static void GuidebookFullEnglishTextPostfix(ref string __result) { if (__result != null) { __result = __result.Replace("0.7.45", "0.8.0").Replace("v0.7.45", "v0.8.0"); } } public static void RavenAdviceTriggerAdvicePrefix(ref string key, ref string topic, ref string text, ref string label) { if (key == "tamemate_welcome" || (topic != null && topic.IndexOf("0.7.45", StringComparison.OrdinalIgnoreCase) >= 0)) { bool flag = Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Spanish"; topic = (flag ? "⚔ TameMate 0.8.0 · The RPG Experience Update" : "⚔ TameMate 0.8.0 · The RPG Experience Update"); text = (flag ? "¡Saludos, noble guerrero! Has despertado bajo el manto de Odín con el don de vincularte con las bestias del décimo mundo.\n\n• Pulsa [F11] en cualquier momento para ajustar la Dificultad Personalizada (Fácil, Normal, Difícil, Supreme), consultar la Guía del Códice y calibrar estrellas SLS.\n• Pulsa [F10] para abrir el Códice del Personaje (Adaptive RPG Archetypes) e inspeccionar tu afinidad, especializaciones híbridas y desglose de combate.\n• Pulsa [F7] para acceder al Códice de Maestrías Nórdicas, equipar sendas rúnicas y realizar rituales chamánicos.\n• Rueda [U]: tus compañeros en postura Defensiva escoltan en cuña sin estorbar y solo atacan si tú o ellos son agredidos, o si tú golpeas a un enemigo.\n• [F9]: rescata compañeros caídos en tu tumba con protección divina.\n\n• Consagra pasivas con trofeos: consulta Jefes en F11. El trofeo oceánico se usa desde inventario." : "Greetings, noble warrior! You have awoken under Odin's mantle with the gift of bonding with the beasts of the tenth realm.\n\n• Press [F11] at any time to adjust Custom Difficulty (Easy, Normal, Hard, Supreme), browse the Codex Guide, and calibrate SLS stars.\n• Press [F10] to open the Character Codex (Adaptive RPG Archetypes) and inspect your affinity, hybrid specializations, and combat breakdown.\n• Press [F7] for the Norse Masteries Codex, equipping runic paths and conducting shamanic rituals.\n• Wheel [U]: your companions in Defensive posture escort in wedge formation without crowding and only attack if you or they are hit, or if you strike first.\n• [F9]: rescue fallen companions at your tombstone with divine shielding.\n\n• Consecrate boss passives with trophies: check Bosses in F11. The ocean horn is used from inventory."); } } [HarmonyPatch(typeof(TameMateGuidebook), "GetChapterSpanish")] [HarmonyPostfix] public static void GuidebookSpanishPostfix(int chapter, ref string title, ref string content) { if (content == null) { return; } switch (chapter) { case 1: if (content.IndexOf("F11", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83c\udfae Control y Códices de TameMate 0.8.0:\n• [ F11 ] : Códice de Dificultad y Experiencia: Abre el panel de gobernanza multicanal para ajustar dificultad (Fácil, Normal, Difícil, Supreme), topes de estrellas por bioma (SLS) y multiplicadores de combate/recursos.\n• [ F10 ] : Códice del Personaje (Adaptive RPG): Inspecciona tu afinidad de combate, desglose de atributos multidimensionales y especializaciones híbridas.\n• [ F7 ] : Códice de Maestrías Nórdicas: Abre el menú de 8 sendas rúnicas (5 rangos progresivos) y equipa hasta 2 medallones en tu HUD.\n• [ F8 ] : Preparación para Jefes: Analiza las debilidades del jefe de bioma y el nivel recomendado de tus bestias.\n• [ F9 ] : Rescate de Compañeros en Tumba: Rescata a tus compañeros seguidores tras reaparecer en tu lecho, con salvaguarda estricta de corrales (las bestias en Stay nunca son teletransportadas).\n• [ U ] : Rueda de Órdenes y Silbidos: Emite comandos rápidos con números del 1 al 8 sin gastar pociones ni cambiar armas de la barra rápida.\n• [ Shift + E ] : Abre las alforjas del compañero apuntado, o accede al Menú de Rituales Chamánicos frente a un soporte de trofeos (ItemStand).\n• [ Alt + E ] : Desequipar todo el equipo del compañero humanoide apuntado devolviéndolo a tu inventario.\n• [ F ] : Montar o desmontar monturas terrestres o aladas."; } break; case 2: if (content.IndexOf("Fauna Silvestre", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n3. Fauna Silvestre Pequeña (0.8.0):\nLos ciervos y liebres se domestican desarmado a puño limpio (noqueo no letal de sumisión) o alimentándolos con frutas y vegetales. Obedecen órdenes de Seguir y Quedarse y llevan alforjas, pero son demasiado delicados para montarse."; } if (content.IndexOf("Persistencia Genética", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83e\uddec Persistencia Genética y Mutaciones de Crías (0.8.0):\n• Identidad Evolutiva Fija: Toda criatura capturada o domesticada mantiene permanentemente su Tier alcanzado (Alpha, Apex, Frostborn, etc.) y su salud máxima proporcional. Ninguna criatura muta o asciende de forma retroactiva ni involuntaria en tus corrales.\n• Genética Exclusiva en Descendientes (C-02): Las mutaciones espontáneas de tier y estrellas ocurren exclusivamente en las crías recién nacidas de tu corral o potenciadas durante la Luna de Sangre."; } break; case 5: if (content.IndexOf("Generación Pasiva", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83d\udce6 Generación Pasiva de Recursos en Alforjas (0.8.0):\nCada compañero y jefe domesticado genera de forma autónoma 1 recurso específico del mundo en sus alforjas cada 5 minutos (hasta un tope de 20 unidades). La producción escala con las estrellas (+50% a 1 estrella, 2 unidades a 2 estrellas y en jefes). No se generan menas metálicas para preservar la exploración minera con EpicMMO."; } break; case 6: if (content.IndexOf("Distribución Progresiva de Estrellas", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n⭐ Distribución Progresiva de Estrellas SLS (0.8.0):\nLa tasa de aparición de estrellas sigue una progresión exponencial decreciente rigurosa y normalizada (MinLevel: 1, Exponential). Cada bioma respeta su tope natural de estrellas según el preset seleccionado en F11, eliminando aglomeraciones artificiales de élites en zonas iniciales."; } break; case 7: if (content.IndexOf("Códice de Maestrías Nórdicas", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83d\udc51 Códice de Maestrías Nórdicas (v0.8.0):\nPulsa [ F7 ] para acceder al Códice de Maestrías. A diferencia de simples logros, las Maestrías representan la comunión y experiencia viva entre el guerrero y sus bestias a lo largo de 5 Rangos Progresivos:\n• Rango I (Iniciado): Desbloqueo inicial mediante hazañas de iniciación.\n• Rango II (Veterano): Pruebas de destreza con enemigos de 1★+ y volumen de combate o crianza.\n• Rango III (Experto): Dominio en al menos 3 biomas distintos de Valheim.\n• Rango IV (Maestro): Derrota de Jefes con bestias sobrevivientes y desbloqueo de poderes culminantes.\n• Rango V (Gran Maestro): La cúspide vikinga: derrota de múltiples jefes y linajes supremos.\n\nSendas Destacadas Rediseñadas:\n\ud83c\udff9 Rastreador Apex (Jugador): Especializado en arcos, ballestas y sigilo. 75 bajas y 15 remates a distancia (Iniciado: +1% daño a distancia, +3% sigilo) → 200 bajas y 20 de 1★ (Veterano: +2% daño, +5% sigilo) → 400 bajas en 3 biomas (Experto: +3% daño, +8% sigilo, alerta temprana) → 650 bajas y derrota de Jefe a distancia (≥20% daño) con compañero vivo (Maestro: +5% daño, +10% sigilo, Radar de Presas en mapa a 30m) → 1,000 bajas, 2 jefes cazados a distancia y cacería coordinada con bestia (Gran Maestro: +7% daño, +15% sigilo, Radar Mejorado a 50m con marcado de élites ★).\n\ud83d\udd25 Chamán Espiritual (Jugador): Vínculo espiritual y apoyo mutuo. 15 alimentaciones a compañeros (Iniciado: impactos de bestias recuperan 1 estamina, CD: 5s) → 35 alimentaciones y Ofrenda con 3 trofeos distintos (Veterano: 2 estamina, apoyo feral +5% velocidad a bestias) → 65 alimentaciones y Consagración con trofeo avanzado (Experto: 3 estamina, 1 Eitr) → 100 alimentaciones y Ritual de Protección con trofeo de jefe (Maestro: 4 estamina, 2 Eitr, Pacto de Vida que anula golpe letal al compañero o jugador dejándolo a 30% HP con CD de 15m) → 150 alimentaciones, salvar con Pacto de Vida y Comunión Suprema junto a bestia sana (Gran Maestro: 5 estamina, 3 Eitr, Pacto recarga en 10m y Aura de Sanación continua de 1 HP/s para bestias cercanas).\n\nInteracción y HUD:\n• Equipa hasta 2 Maestrías simultáneas en el Códice (F7).\n• Realiza los Rituales Chamánicos directamente desde el panel de F7 o pulsando Shift + E frente a un soporte de trofeos (ItemStand).\n• Mantén Mayús + Clic Izquierdo sobre los medallones en pantalla para moverlos libremente por el HUD.\n\n\ud83d\udee1\ufe0f Adaptive RPG Archetypes (F10): Abre el Códice del Personaje con [F10] para consultar tus arquetipos dinámicos (Guerrero, Cazador, Conjurador, Guardián, Pícaro) y especializaciones híbridas (Paladín, Señor de las Bestias, Asesino Sombrío, etc.), con lectura universal de armas y habilidades de Valheim nativo, EpicMMO y EpicLoot."; } break; } } [HarmonyPatch(typeof(TameMateGuidebook), "GetChapterEnglish")] [HarmonyPostfix] public static void GuidebookEnglishPostfix(int chapter, ref string title, ref string content) { if (content == null) { return; } switch (chapter) { case 1: if (content.IndexOf("F11", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83c\udfae TameMate 0.8.0 Controls & Codices:\n• [ F11 ] : Difficulty & Experience Codex: Open the multichannel governance panel to adjust difficulty (Easy, Normal, Hard, Supreme), per-biome star caps (SLS), and combat/resource multipliers.\n• [ F10 ] : Character Codex (Adaptive RPG): Inspect your combat affinity, multidimensional capability breakdown, and hybrid specializations.\n• [ F7 ] : Norse Masteries Codex: Access 8 runic paths (5 progressive ranks) and equip up to 2 active medallions on your HUD.\n• [ F8 ] : Boss Encounter Preparation: Analyze biome boss weaknesses and recommended companion tier ratings.\n• [ F9 ] : Tombstone Companion Rescue: Rescues your follower companions after respawning at your bed, with strict corral safeguards (companions on Stay are never teleported).\n• [ U ] : Command Wheel & Whistles: Issue swift tactical commands with keys 1 to 8 without consuming potions or switching hotbar weapons.\n• [ Shift + E ] : Opens targeted companion saddlebags, or opens the Shamanic Rituals Menu when facing a trophy stand (ItemStand).\n• [ Alt + E ] : Unequips all gear from the targeted humanoid companion and returns it to your inventory.\n• [ F ] : Mount or dismount land or winged mounts."; } break; case 2: if (content.IndexOf("Small Wildlife", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n3. Small Peaceful Wildlife (0.8.0):\nDeer and hares are subdued unarmed with bare fists (non-lethal knockout) or by feeding fruits and veggies. They follow orders (Follow/Stay) and carry saddlebags, but are too delicate to be ridden."; } if (content.IndexOf("Genetic Persistence", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83e\uddec Genetic Persistence & Offspring Mutations (0.8.0):\n• Fixed Evolutionary Identity: Every captured or tamed creature permanently retains its achieved Tier (Alpha, Apex, Frostborn, etc.) and proportional max health. No creature retroactively or involuntarily mutates or ascends in your corrals.\n• Descendant-Only Genetics (C-02): Spontaneous tier and star mutations occur exclusively in newborn offspring within your pens or empowered during the Blood Moon."; } break; case 5: if (content.IndexOf("Passive Resource Generation", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83d\udce6 Passive Saddlebag Resources (0.8.0):\nEach tamed companion and boss autonomously produces 1 world resource into its saddlebags every 5 minutes (up to 20 units cap). Yield scales with stars (+50% at 1 star, 2 units at 2 stars and on bosses). Metal ores are excluded to preserve EpicMMO mining."; } break; case 6: if (content.IndexOf("Progressive Star Distribution", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n⭐ Progressive Star Distribution SLS (0.8.0):\nCreature star spawn rates follow a strict, normalized exponential drop-off curve (MinLevel: 1, Exponential). Each biome adheres to its natural star cap based on the preset chosen in F11, eliminating artificial elite swarms in starting biomes."; } break; case 7: if (content.IndexOf("Norse Masteries Codex", StringComparison.OrdinalIgnoreCase) < 0) { content += "\n\n\ud83d\udc51 Norse Masteries Codex (v0.8.0):\nPress [ F7 ] to access the Masteries Codex. Far from basic achievements, Masteries represent deep progression and bond between warrior and tames across 5 Progressive Ranks:\n• Rank I (Initiate): Unlocks the runic path upon completing foundational feats.\n• Rank II (Veteran): Proves combat or breeding mastery against 1★+ foes.\n• Rank III (Expert): Lead your companions across at least 3 distinct Valheim biomes.\n• Rank IV (Master): Vanquish biome Bosses with surviving companions and unlock capstone powers.\n• Rank V (Grand Master): The Norse pinnacle: multiple boss conquests and legendary lineages.\n\nFeatured Redesigned Paths:\n\ud83c\udff9 Apex Tracker (Player): Specialized in bows, crossbows, and stealth. 75 kills and 15 ranged finishes (Initiate: +1% ranged dmg, +3% stealth) → 200 kills and 20 1★+ foes (Veteran: +2% dmg, +5% stealth) → 400 kills in 3 biomes (Expert: +3% dmg, +8% stealth, threat warning) → 650 kills and Boss defeat at range (≥20% dmg) with surviving companion (Master: +5% dmg, +10% stealth, Prey Radar on map at 30m) → 1,000 kills, 2 distinct bosses defeated at range and coordinated beast hunt (Grand Master: +7% dmg, +15% stealth, Enhanced Radar at 50m with elite ★ markers).\n\ud83d\udd25 Beast Shaman (Player): Spiritual bond and mutual empowerment. 15 companion feedings (Initiate: beast strikes restore 1 stam, 5s CD) → 35 feedings and Shamanic Offering of 3 distinct trophies (Veteran: 2 stam, feral support +5% speed to tames) → 65 feedings and Consecration with advanced trophy (Expert: 3 stam, 1 Eitr) → 100 feedings and Protection Ritual with boss trophy (Master: 4 stam, 2 Eitr, Life Pact saving companion or player from fatal blow at 30% HP with 15m CD) → 150 feedings, successful Life Pact save and Supreme Communion alongside healthy beast (Grand Master: 5 stam, 3 Eitr, 10m Pact CD and continuous Healing Aura of 1 HP/s for nearby tames).\n\nInteraction & HUD:\n• Equip up to 2 active Masteries simultaneously in the Codex (F7).\n• Perform Shamanic Rituals directly from the F7 panel or by pressing Shift + E while facing a trophy stand (ItemStand).\n• Hold Shift + Left Click on screen medallions to drag and position them anywhere on your HUD.\n\n\ud83d\udee1\ufe0f Adaptive RPG Archetypes (F10): Press [F10] to open the Character Codex and consult your dynamic archetypes (Warrior, Hunter, Conjurer, Guardian, Rogue) and hybrid specializations (Paladin, Beastmaster, Shadow Assassin, etc.), with transparent capability integration for native Valheim, EpicMMO, and EpicLoot."; } break; } } } } namespace TameMate.Lineages { public struct MonsterDbSnapshot { public bool IsAvailable; public bool LockConfiguration; public string LogLevels; public bool DetailedDebugLogs; public int CustomMonsterDefinitionCount; public string ConfigPath; public static MonsterDbSnapshot CreateDefault() { return new MonsterDbSnapshot { IsAvailable = false, LockConfiguration = true, LogLevels = "All", DetailedDebugLogs = false, CustomMonsterDefinitionCount = 0, ConfigPath = string.Empty }; } } public static class MonsterDbAdapter { public const string MonsterDbPluginGuid = "RustyMods.MonsterDB"; private const string ConfigFileName = "RustyMods.MonsterDB.cfg"; private const string ConfigDirectoryName = "MonsterDB"; private static bool? s_isPluginLoadedCached = null; private static string s_customConfigPath = null; private static string s_customMonsterDbDir = null; public static bool IsAvailable { get { if (!IsPluginLoaded) { return IsConfigFileAvailable; } return true; } } public static bool IsPluginLoaded { get { if (s_isPluginLoadedCached.HasValue) { return s_isPluginLoadedCached.Value; } try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("RustyMods.MonsterDB")) { s_isPluginLoadedCached = true; return true; } } catch { } try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { string name = assemblies[i].GetName().Name; if (string.Equals(name, "MonsterDB", StringComparison.OrdinalIgnoreCase)) { s_isPluginLoadedCached = true; return true; } } } catch { } s_isPluginLoadedCached = false; return false; } } public static bool IsConfigFileAvailable { get { string text = ResolveConfigFilePath(); if (!string.IsNullOrEmpty(text)) { return File.Exists(text); } return false; } } public static void SetCustomConfigPathForTesting(string path, string dir = null) { s_customConfigPath = path; s_customMonsterDbDir = dir; } public static string ResolveConfigFilePath() { if (!string.IsNullOrEmpty(s_customConfigPath)) { return s_customConfigPath; } try { string configPath = Paths.ConfigPath; if (!string.IsNullOrEmpty(configPath)) { string text = Path.Combine(configPath, "RustyMods.MonsterDB.cfg"); if (File.Exists(text)) { return text; } } } catch { } string text2 = "C:\\Users\\Mitsu\\AppData\\Roaming\\Thunderstore Mod Manager\\DataFolder\\Valheim\\profiles\\Valheim Supreme\\BepInEx\\config"; if (Directory.Exists(text2)) { string text3 = Path.Combine(text2, "RustyMods.MonsterDB.cfg"); if (File.Exists(text3)) { return text3; } } return string.Empty; } public static string ResolveMonsterDbDirectory() { if (!string.IsNullOrEmpty(s_customMonsterDbDir) && Directory.Exists(s_customMonsterDbDir)) { return s_customMonsterDbDir; } try { string configPath = Paths.ConfigPath; if (!string.IsNullOrEmpty(configPath)) { string text = Path.Combine(configPath, "MonsterDB"); if (Directory.Exists(text)) { return text; } } } catch { } string text2 = "C:\\Users\\Mitsu\\AppData\\Roaming\\Thunderstore Mod Manager\\DataFolder\\Valheim\\profiles\\Valheim Supreme\\BepInEx\\config\\MonsterDB"; if (Directory.Exists(text2)) { return text2; } return string.Empty; } public static MonsterDbSnapshot CaptureCurrentState() { MonsterDbSnapshot result = MonsterDbSnapshot.CreateDefault(); string text = (result.ConfigPath = ResolveConfigFilePath()); if (string.IsNullOrEmpty(text) || !File.Exists(text)) { result.IsAvailable = IsPluginLoaded; return result; } result.IsAvailable = true; try { string[] array = File.ReadAllLines(text); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.StartsWith("#") || string.IsNullOrEmpty(text2)) { continue; } int num = text2.IndexOf('='); if (num > 0) { string a = text2.Substring(0, num).Trim(); string text3 = text2.Substring(num + 1).Trim(); if (string.Equals(a, "Lock Configuration", StringComparison.OrdinalIgnoreCase)) { result.LockConfiguration = string.Equals(text3, "On", StringComparison.OrdinalIgnoreCase) || string.Equals(text3, "true", StringComparison.OrdinalIgnoreCase); } else if (string.Equals(a, "Log Levels", StringComparison.OrdinalIgnoreCase)) { result.LogLevels = text3; } else if (string.Equals(a, "Detailed Debug Logs", StringComparison.OrdinalIgnoreCase)) { result.DetailedDebugLogs = string.Equals(text3, "On", StringComparison.OrdinalIgnoreCase) || string.Equals(text3, "true", StringComparison.OrdinalIgnoreCase); } } } } catch { } try { string text4 = ResolveMonsterDbDirectory(); if (!string.IsNullOrEmpty(text4) && Directory.Exists(text4)) { string path = Path.Combine(text4, "Import"); if (Directory.Exists(path)) { result.CustomMonsterDefinitionCount = Directory.GetFiles(path, "*.json", SearchOption.AllDirectories).Length + Directory.GetFiles(path, "*.yml", SearchOption.AllDirectories).Length; } } } catch { } return result; } public static void ResetCache() { s_isPluginLoadedCached = null; } } public static class MountedSpecialAttack { public static ConfigEntry SpecialAttackKey; public static ConfigEntry TertiaryAttackKey; public static ConfigEntry SpecialAttackStaminaCost; public static ConfigEntry TertiaryAttackStaminaCost; public static ConfigEntry ComboWindowSeconds; private static Func s_getRidingDiscount; private static FieldInfo s_aimModeField; private static readonly Func s_haveStamina; private static readonly Action s_useStamina; private static readonly List s_cachedWeapons; private static float s_lastSpecialAttackTime; private static int s_lastSpecialSlot; private static float s_nextSpecialAttackTime; static MountedSpecialAttack() { s_cachedWeapons = new List(8); s_lastSpecialAttackTime = 0f; s_lastSpecialSlot = 0; s_nextSpecialAttackTime = 0f; MethodInfo methodInfo = AccessTools.Method(typeof(Sadle), "HaveStamina", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo != null) { try { s_haveStamina = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo); } catch { s_haveStamina = null; } } MethodInfo methodInfo2 = AccessTools.Method(typeof(Sadle), "UseStamina", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo2 != null) { try { s_useStamina = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo2); } catch { s_useStamina = null; } } } public static void Install(Harmony harmony, Assembly coreAssembly, ConfigFile config) { //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown if (config != null) { SpecialAttackKey = config.Bind("Controls", "MountedSpecialAttackKey", (KeyCode)99, "Key to execute the mount's secondary special attack (e.g. stomp, ground slam, special claw)."); TertiaryAttackKey = config.Bind("Controls", "MountedTertiaryAttackKey", (KeyCode)0, "Optional dedicated key to trigger mount's 3rd attack (e.g. boss lightning/aoe). If None, tapping C consecutively within the combo window or holding Alt+C triggers attack 3."); SpecialAttackStaminaCost = config.Bind("Controls", "MountedSpecialAttackStaminaCost", 25f, "Base stamina cost for the mount's secondary special attack."); TertiaryAttackStaminaCost = config.Bind("Controls", "MountedTertiaryAttackStaminaCost", 35f, "Base stamina cost for the mount's 3rd special attack."); ComboWindowSeconds = config.Bind("Controls", "MountedAttackComboWindow", 2.5f, "Window in seconds to chain attack 2 into attack 3 via consecutive C taps on 3-attack mounts."); } Type type = coreAssembly.GetType("TameMate.SkillsEngine"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "GetRidingStaminaDiscount", new Type[1] { typeof(Player) }, (Type[])null); if (methodInfo != null) { try { s_getRidingDiscount = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo); } catch { s_getRidingDiscount = null; } } } Type type2 = coreAssembly.GetType("TameMate.MountedCombat"); if (type2 != null) { s_aimModeField = AccessTools.Field(type2, "k__BackingField"); MethodInfo methodInfo2 = AccessTools.Method(type2, "Update", (Type[])null, (Type[])null); if (methodInfo2 != null) { MethodInfo methodInfo3 = AccessTools.Method(typeof(MountedSpecialAttack), "MountedCombat_Update_Prefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } public static void Uninstall() { s_cachedWeapons.Clear(); s_lastSpecialAttackTime = 0f; s_lastSpecialSlot = 0; s_nextSpecialAttackTime = 0f; } public static bool MountedCombat_Update_Prefix(MonoBehaviour __instance) { //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return true; } if (InventoryGui.IsVisible() || Hud.InRadial() || ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || TextInput.IsVisible() || Menu.IsVisible()) { return true; } IDoodadController doodadController = localPlayer.GetDoodadController(); Sadle val = (Sadle)(object)((doodadController is Sadle) ? doodadController : null); Character val2 = (((Object)(object)val != (Object)null) ? val.GetCharacter() : null); if ((Object)(object)val2 == (Object)null && (Object)(object)__instance != (Object)null) { val2 = Traverse.Create((object)__instance).Field("cachedLocalMount").GetValue(); if ((Object)(object)val2 != (Object)null && (val2.IsDead() || !val2.HaveRider())) { val2 = null; } } if ((Object)(object)val2 == (Object)null || val2.IsDead()) { return true; } try { ContextualAdviceEngine.OnMount(localPlayer, val2); } catch { } Humanoid val3 = (Humanoid)(object)((val2 is Humanoid) ? val2 : null); if (Input.GetMouseButtonDown(0)) { if ((Object)(object)val3 != (Object)null && !val2.InAttack()) { PopulateMonsterWeapons(val3, s_cachedWeapons); if (s_cachedWeapons.Count > 0) { ItemData val4 = s_cachedWeapons[0]; if (val3.GetCurrentWeapon() != val4) { val3.EquipItem(val4, true); } } } return true; } KeyCode val5 = (KeyCode)((SpecialAttackKey == null) ? 99 : ((int)SpecialAttackKey.Value)); if (Input.GetKeyDown(val5)) { ExecuteSpecialAttack(val2, val, forceTertiary: false); return true; } if (TertiaryAttackKey != null && (int)TertiaryAttackKey.Value != 0 && Input.GetKeyDown(TertiaryAttackKey.Value)) { ExecuteSpecialAttack(val2, val, forceTertiary: true); return true; } if (Input.GetMouseButtonDown(2)) { ExecuteSpecialAttack(val2, val, forceTertiary: false); return false; } return true; } public static void ExecuteSpecialAttack(Character mount, Sadle saddle, bool forceTertiary) { if ((Object)(object)mount == (Object)null || mount.IsDead() || mount.InAttack()) { return; } Humanoid val = (Humanoid)(object)((mount is Humanoid) ? mount : null); if ((Object)(object)val == (Object)null || Time.time < s_nextSpecialAttackTime) { return; } PopulateMonsterWeapons(val, s_cachedWeapons); if (s_cachedWeapons.Count == 0) { return; } int num = 0; bool flag = false; float num2 = ((ComboWindowSeconds != null) ? ComboWindowSeconds.Value : 2.5f); if (s_cachedWeapons.Count >= 3) { num = ((!forceTertiary && !Input.GetKey((KeyCode)308) && !Input.GetKey((KeyCode)307)) ? ((!(Time.time - s_lastSpecialAttackTime <= num2) || s_lastSpecialSlot != 1) ? 1 : 2) : 2); } else if (s_cachedWeapons.Count == 2) { num = 1; } else if (s_cachedWeapons[0].HaveSecondaryAttack()) { num = 0; flag = true; } else { num = 0; flag = false; } float num3 = ((num == 2) ? ((TertiaryAttackStaminaCost != null) ? TertiaryAttackStaminaCost.Value : 35f) : ((num != 1 && !flag) ? 15f : ((SpecialAttackStaminaCost != null) ? SpecialAttackStaminaCost.Value : 25f))); Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { float ridingDiscount = GetRidingDiscount(localPlayer); num3 *= Mathf.Clamp01(1f - ridingDiscount); } if ((Object)(object)saddle != (Object)null && !SaddleHasStamina(saddle, num3)) { if ((Object)(object)localPlayer != (Object)null) { ((Character)localPlayer).Message((MessageType)2, "$msg_nostamina", 0, (Sprite)null, false); } return; } OrientMountDirection(mount); ItemData val2 = s_cachedWeapons[num]; if (val.GetCurrentWeapon() != val2) { val.EquipItem(val2, true); } if (((Character)val).StartAttack((Character)null, flag)) { if ((Object)(object)saddle != (Object)null) { SaddleUseStamina(saddle, num3); } s_lastSpecialSlot = num; s_lastSpecialAttackTime = Time.time; s_nextSpecialAttackTime = Time.time + 0.6f; ShowAttackFeedback(localPlayer, mount, val2, num, flag); } } public static bool SaddleHasStamina(Sadle saddle, float cost) { if ((Object)(object)saddle == (Object)null) { return true; } if (s_haveStamina != null) { try { return s_haveStamina(saddle, cost); } catch { } } return saddle.GetStamina() >= cost; } public static void SaddleUseStamina(Sadle saddle, float cost) { if ((Object)(object)saddle == (Object)null || cost <= 0f || s_useStamina == null) { return; } try { s_useStamina(saddle, cost); } catch { } } private static void PopulateMonsterWeapons(Humanoid humanoid, List output) { output.Clear(); if ((Object)(object)humanoid == (Object)null) { return; } Inventory inventory = humanoid.GetInventory(); if (inventory != null) { List allItems = inventory.GetAllItems(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && val.IsWeapon() && val.HavePrimaryAttack()) { output.Add(val); } } } if (output.Count == 0 && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0) { humanoid.GiveDefaultItems(); if (inventory != null) { List allItems2 = inventory.GetAllItems(); for (int j = 0; j < allItems2.Count; j++) { ItemData val2 = allItems2[j]; if (val2 != null && val2.IsWeapon() && val2.HavePrimaryAttack()) { output.Add(val2); } } } } if (output.Count == 0 && (Object)(object)humanoid.m_unarmedWeapon != (Object)null && humanoid.m_unarmedWeapon.m_itemData != null) { output.Add(humanoid.m_unarmedWeapon.m_itemData); } if (output.Count == 0 && humanoid.GetCurrentWeapon() != null) { output.Add(humanoid.GetCurrentWeapon()); } } private static float GetRidingDiscount(Player player) { if ((Object)(object)player == (Object)null) { return 0f; } if (s_getRidingDiscount != null) { try { return s_getRidingDiscount(player); } catch { } } float skillFactor = ((Character)player).GetSkillFactor((SkillType)110); return Mathf.Clamp01(0.4f * skillFactor); } private static void OrientMountDirection(Character mount) { //IL_004b: 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_0076: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)mount == (Object)null) { return; } bool flag = false; if (s_aimModeField != null) { try { flag = (bool)s_aimModeField.GetValue(null); } catch { flag = false; } } if (flag && (Object)(object)GameCamera.instance != (Object)null) { Vector3 forward = ((Component)GameCamera.instance).transform.forward; if (!mount.IsFlying()) { forward.y = 0f; } if (((Vector3)(ref forward)).sqrMagnitude > 0.01f) { mount.SetLookDir(((Vector3)(ref forward)).normalized, 1f); } } } private static void ShowAttackFeedback(Player player, Character mount, ItemData weapon, int slot, bool secondaryMode) { if (!((Object)(object)player == (Object)null) && !((Object)(object)mount == (Object)null)) { string text = mount.GetHoverName(); if (string.IsNullOrEmpty(text)) { text = ((Object)mount).name.Replace("(Clone)", "").Trim(); } string text2 = ((weapon != null && weapon.m_shared != null) ? weapon.m_shared.m_name : ""); string text3 = ((!string.IsNullOrEmpty(text2)) ? Localization.instance.Localize(text2) : ""); string text4; if (!string.IsNullOrEmpty(text3) && text3 != text2) { text4 = text + ": " + text3; } else { string text5 = ((slot == 2) ? "Ataque Especial III" : ((slot == 1 || secondaryMode) ? "Ataque Especial II" : "Ataque I")); text4 = text + " [" + text5 + "]"; } ((Character)player).Message((MessageType)1, text4, 0, (Sprite)null, false); } } } } namespace TameMate { public delegate string CustomResourceDelegate(string prefabName, Character character); public static class PassiveResourceGeneration { private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate PassiveGen"); private static Harmony harmony; private static bool isInstalled; public static ConfigEntry Enabled; public static ConfigEntry IntervalSeconds; public static ConfigEntry MaxStorageCap; public static ConfigEntry MaxOfflineCycles; public static CustomResourceDelegate CustomResourceHook; private static Func EnsureContainer; private static Action SaveSaddlebags; private static readonly Dictionary NextCheckTimes = new Dictionary(); private static readonly Dictionary ResourceCatalogue = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Boar", "Mushroom" }, { "Boar_Piggy", "Mushroom" }, { "Neck", "Flint" }, { "Deer", "Dandelion" }, { "Greydwarf", "Resin" }, { "Greydwarf_Shaman", "Thistle" }, { "Greydwarf_Elite", "Wood" }, { "Skeleton", "BoneFragments" }, { "Skeleton_Poison", "BoneFragments" }, { "Troll", "Coins" }, { "Blob", "Guck" }, { "BlobElite", "Guck" }, { "Draugr", "Entrails" }, { "Draugr_Elite", "Entrails" }, { "Draugr_Ranged", "Entrails" }, { "Surtling", "Coal" }, { "Wraith", "Feather" }, { "Leech", "Bloodbag" }, { "Abomination", "Root" }, { "Wolf", "WolfClaw" }, { "WolfCub", "WolfClaw" }, { "StoneGolem", "Crystal" }, { "Bat", "Obsidian" }, { "Fenring", "WolfHair" }, { "Fenring_Cultist", "WolfHair" }, { "Hatchling", "Feather" }, { "Lox", "Cloudberry" }, { "LoxCalf", "Cloudberry" }, { "Goblin", "Coins" }, { "GoblinBrute", "Stone" }, { "GoblinShaman", "Barley" }, { "Deathsquito", "Needle" }, { "Seeker", "Sap" }, { "SeekerSoldier", "BlackMarble" }, { "SeekerBrood", "Softtissue" }, { "Tick", "Bloodbag" }, { "Gjall", "Bilebag" }, { "Dverger", "Softtissue" }, { "DvergerMage", "Softtissue" }, { "Asksvin", "Ashwood" }, { "Asksvin_Calf", "Ashwood" }, { "Charred_Melee", "Coal" }, { "Charred_Archer", "Coal" }, { "Charred_Mage", "BoneFragments" }, { "Charred_Twitcher", "Coal" }, { "Morgen", "Grausten" }, { "FallenValkyrie", "Feather" }, { "BonemawSerpent", "BoneFragments" }, { "Serpent", "SerpentScale" }, { "Eikthyr", "Acorn" }, { "gd_king", "ElderBark" }, { "TheElder", "ElderBark" }, { "Bonemass", "Chain" }, { "Dragon", "FreezeGland" }, { "Moder", "FreezeGland" }, { "GoblinKing", "Tar" }, { "Yagluth", "Tar" }, { "SeekerQueen", "RoyalJelly" }, { "TheQueen", "RoyalJelly" }, { "Fader", "Sulfur" }, { "Asmodeus", "AncientSeed" }, { "Asmodeus_TW", "AncientSeed" }, { "BossAsmodeus_TW", "AncientSeed" }, { "BossSvalt_TW", "FineWood" }, { "Svalt_TW", "FineWood" }, { "Svalt", "FineWood" }, { "BossVrykolathas_TW", "WitheredBone" }, { "Vrykolathas_TW", "WitheredBone" }, { "Vrykolathas", "WitheredBone" }, { "Shark_TW", "Chitin" }, { "Orca_TW", "FishRaw" }, { "GrizzlyBear_TW", "Honey" }, { "BlackBear_TW", "Raspberry" }, { "SilvertipBear_TW", "Blueberries" }, { "Fox_TW", "Dandelion" }, { "Crawler_TW", "Resin" }, { "Prowler_TW", "BoneFragments" }, { "Razorback_TW", "Carrot" }, { "RottingElk_TW", "BoneFragments" }, { "SkeletonMage_TW", "BoneFragments" }, { "GhostWarrior_TW", "BoneFragments" }, { "ObsidianGolem_TW", "Obsidian" }, { "FrostSerpent_TW", "SerpentScale" }, { "LavaGolem_TW", "Grausten" }, { "Surtr_TW", "Coal" }, { "Bjorn", "Honey" }, { "BjornCub", "Honey" }, { "Unbjorn", "BoneFragments" }, { "NeckLord", "Flint" }, { "GreydwarfShamanLord", "Thistle" }, { "DraugrEliteLord", "Entrails" }, { "FenringLord", "WolfHair" }, { "LoxLord", "Cloudberry" }, { "SeekerLord", "BlackMarble" }, { "FallerValkyrieLord", "Feather" }, { "GammeltrollLord", "Coins" } }; public static void Install(Harmony h, Assembly coreAssembly, ConfigFile config) { //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected O, but got Unknown if (!isInstalled) { Enabled = config.Bind("Passive Resource Generation", "PassiveGenerationEnabled", true, "Enables passive resource generation in tamed companion saddlebags over time."); IntervalSeconds = config.Bind("Passive Resource Generation", "PassiveGenerationInterval", 300f, "Time in seconds between resource generation cycles (default 300s = 5 minutes)."); MaxStorageCap = config.Bind("Passive Resource Generation", "PassiveGenerationStorageCap", 20, "Maximum quantity of the creature's generated resource stored in saddlebags before generation pauses."); MaxOfflineCycles = config.Bind("Passive Resource Generation", "PassiveGenerationMaxOfflineCycles", 6, "Maximum offline/catch-up cycles awarded when returning to unloaded companions (default 6 = up to 30 mins)."); Type type = coreAssembly.GetType("TameMate.CompanionSaddlebags", throwOnError: true); MethodInfo methodInfo = AccessTools.Method(type, "Ensure", new Type[1] { typeof(Character) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(type, "SaveNow", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo != null) { EnsureContainer = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo); } if (methodInfo2 != null) { SaveSaddlebags = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo2); } MethodInfo methodInfo3 = AccessTools.Method(typeof(BaseAI), "UpdateAI", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo3 != null) { h.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(PassiveResourceGeneration), "UpdateAIPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } harmony = h; isInstalled = true; Log.LogInfo((object)"TameMate 0.7.43 Passive Resource Generation installed successfully."); } } public static void Uninstall() { if (isInstalled) { NextCheckTimes.Clear(); EnsureContainer = null; SaveSaddlebags = null; isInstalled = false; } } public static string ResolveResource(string prefabName, Character character) { if (CustomResourceHook != null) { string text = CustomResourceHook(prefabName, character); if (!string.IsNullOrEmpty(text)) { return text; } } if (string.IsNullOrEmpty(prefabName)) { return null; } if (ResourceCatalogue.TryGetValue(prefabName, out var value)) { return value; } int num = prefabName.IndexOf("(Clone)", StringComparison.OrdinalIgnoreCase); if (num > 0) { string key = prefabName.Substring(0, num).Trim(); if (ResourceCatalogue.TryGetValue(key, out value)) { return value; } } return null; } public static void UpdateAIPostfix(BaseAI __instance, float dt) { if (!Enabled.Value || !isInstalled || (Object)(object)__instance == (Object)null) { return; } Character component = ((Component)__instance).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsTamed() && !component.IsDead() && component.IsOwner()) { int instanceID = ((Object)component).GetInstanceID(); float time = Time.time; if (!NextCheckTimes.TryGetValue(instanceID, out var value) || !(time < value)) { NextCheckTimes[instanceID] = time + Random.Range(5f, 7.5f); ProcessGeneration(component); } } } public static void ProcessGeneration(Character c) { ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null) { return; } string prefabName = Utils.GetPrefabName(((Component)c).gameObject); string text = ResolveResource(prefabName, c); if (string.IsNullOrEmpty(text) || (Object)(object)ObjectDB.instance == (Object)null) { return; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); if ((Object)(object)itemPrefab == (Object)null) { return; } ItemDrop component2 = itemPrefab.GetComponent(); if ((Object)(object)component2 == (Object)null || component2.m_itemData == null) { return; } long num = (((Object)(object)ZNet.instance != (Object)null) ? ((long)ZNet.instance.GetTimeSeconds()) : ((long)Time.time)); long num2 = zDO.GetLong("TameMate_LastPassiveGen", 0L); if (num2 <= 0) { zDO.Set("TameMate_LastPassiveGen", num); return; } long num3 = (long)Mathf.Max(30f, IntervalSeconds.Value); long num4 = num - num2; if (num4 < num3) { return; } int num5 = (int)(num4 / num3); if (num5 <= 0) { return; } int num6 = Mathf.Max(1, MaxOfflineCycles.Value); if (num5 > num6) { num5 = num6; } if (EnsureContainer == null) { return; } Container val = EnsureContainer(c); if ((Object)(object)val == (Object)null) { return; } Inventory inventory = val.GetInventory(); if (inventory == null) { return; } int num7 = Mathf.Max(1, MaxStorageCap.Value); string name = component2.m_itemData.m_shared.m_name; int num8 = inventory.CountItems(name, -1, true); if (num8 >= num7) { zDO.Set("TameMate_LastPassiveGen", num); return; } int num9 = c.GetLevel() - 1; int num10 = 1; if (c.IsBoss() || num9 >= 2) { num10 = 2; } else if (num9 == 1) { num10 = ((!(Random.value < 0.5f)) ? 1 : 2); } int val2 = num10 * num5; int val3 = num7 - num8; int num11 = Math.Min(val2, val3); if (num11 > 0 && inventory.AddItem(itemPrefab, num11)) { if (SaveSaddlebags != null) { SaveSaddlebags(c); } Log.LogInfo((object)$"[TameMate PassiveGen] {c.GetHoverName()} ({prefabName}) generated {num11}x {name} into saddlebags ({num8 + num11}/{num7})."); } zDO.Set("TameMate_LastPassiveGen", num); } public static void OnCharacterDestroyed(int instanceID) { NextCheckTimes.Remove(instanceID); } } } namespace TameMate.Lineages { public static class PriorityFixesIntegration { private static class RuntimeBindings { public static ManualLogSource Log; public static bool Installed; public static FieldInfo GodShieldDictField; public static MethodInfo RavenAdviceMethod; public static Func GetOwnerFunc; public static Func GetOrderFunc; public static Func GetCommandActiveFunc; public static Type CompanionMotorType; public static MethodInfo ClearAnchorImmediateMethod; public static MethodInfo HasCommittedTargetMethod; public static Func GetTierFunc; public static Func GetHealthMultiplierFunc; public static Action InvalidateTierAction; public static Type CreatureTierType; public static object[] BoxedCreatureTiers; public static Func GetMutationChanceFunc; public static Func GetBreedingMutationBonusFunc; public static Action RaisePackMasteryAction; public static Func IsBloodMoonActiveFunc; public static Func GetActiveCataclysmEventFunc; public static FieldInfo ProcreationOffspringField; } public sealed class PriorityFixesDiagnosticReport { public string OverallState { get; set; } public List InstalledPatches { get; private set; } public Dictionary RejectedPatches { get; private set; } public Dictionary FeatureStates { get; private set; } public Dictionary FeatureRequiredPatches { get; private set; } public PriorityFixesDiagnosticReport() { OverallState = "NotInitialized"; InstalledPatches = new List(); RejectedPatches = new Dictionary(StringComparer.Ordinal); FeatureStates = new Dictionary(StringComparer.Ordinal); FeatureRequiredPatches = new Dictionary(StringComparer.Ordinal) { { "BUG003_EliteConjunctions", new string[1] { "SupremeTierEngine.ComputeTier" } }, { "D0995_EvolutionaryIdentity", new string[5] { "SupremeTierEngine.GetBiomeAt", "SupremeTierEngine.ComputeTier", "Character.SetTamed", "Character.SetLevel", "Procreation.Procreate" } }, { "C02_DescendantOnlyMutations", new string[2] { "Procreation.Procreate", "BreedingMutationPatch.Postfix" } }, { "BUG004_CorpseRescueSafeguard", new string[1] { "AltairBridge.RescueCompanionsAtCorpseRoutine" } } }; } public bool IsPatchInstalled(string patchId) { if (!string.IsNullOrEmpty(patchId)) { return InstalledPatches.Contains(patchId); } return false; } public bool IsFeatureOperational(string featureId) { if (!string.IsNullOrEmpty(featureId) && FeatureStates.TryGetValue(featureId, out var value)) { return value; } return false; } public void EvaluateFeatureStates() { bool flag = true; foreach (KeyValuePair featureRequiredPatch in FeatureRequiredPatches) { string key = featureRequiredPatch.Key; string[] value = featureRequiredPatch.Value; bool flag2 = value != null && value.Length > 0; if (flag2) { for (int i = 0; i < value.Length; i++) { if (!InstalledPatches.Contains(value[i]) || RejectedPatches.ContainsKey(value[i])) { flag2 = false; break; } } } FeatureStates[key] = flag2; if (!flag2) { flag = false; } } if (InstalledPatches.Count == 0) { OverallState = "Failed"; } else if (flag && RejectedPatches.Count == 0) { OverallState = "FullyOperational"; } else { OverallState = "Degraded"; } } } public interface IEvolutionaryStateStore { bool IsValid { get; } bool IsOwner { get; } void ClaimOwnership(); int GetInt(int keyHash, int defaultValue); void SetInt(int keyHash, int value); } public sealed class ValheimEvolutionaryStateStore : IEvolutionaryStateStore { private readonly ZNetView m_znv; private readonly ZDO m_zdo; public bool IsValid { get { if ((Object)(object)m_znv != (Object)null && m_znv.IsValid()) { return m_zdo != null; } return false; } } public bool IsOwner { get { if (IsValid) { return m_znv.IsOwner(); } return false; } } public ValheimEvolutionaryStateStore(ZNetView znv, ZDO zdo) { m_znv = znv; m_zdo = zdo; } public void ClaimOwnership() { if (IsValid && !m_znv.IsOwner()) { m_znv.ClaimOwnership(); } } public int GetInt(int keyHash, int defaultValue) { if (!IsValid) { return defaultValue; } return m_zdo.GetInt(keyHash, defaultValue); } public void SetInt(int keyHash, int value) { if (IsValid && m_znv.IsOwner()) { m_zdo.Set(keyHash, value, false); } } } public sealed class InMemoryEvolutionaryStateStore : IEvolutionaryStateStore { private readonly Dictionary m_values = new Dictionary(); private bool m_isValid; private bool m_isOwner; private int m_claimCount; private int m_blockedWriteCount; private int m_writeCount; public bool IsValid { get { return m_isValid; } set { m_isValid = value; } } public bool IsOwner { get { return m_isOwner; } set { m_isOwner = value; } } public int ClaimCount => m_claimCount; public int BlockedWriteCount => m_blockedWriteCount; public int WriteCount => m_writeCount; public InMemoryEvolutionaryStateStore(bool isValid, bool isOwner) { m_isValid = isValid; m_isOwner = isOwner; } public void ClaimOwnership() { if (m_isValid && !m_isOwner) { m_isOwner = true; m_claimCount++; } } public int GetInt(int keyHash, int defaultValue) { if (!m_isValid) { return defaultValue; } if (!m_values.TryGetValue(keyHash, out var value)) { return defaultValue; } return value; } public void SetInt(int keyHash, int value) { if (m_isValid) { if (!m_isOwner) { m_blockedWriteCount++; return; } m_values[keyHash] = value; m_writeCount++; } } public InMemoryEvolutionaryStateStore CloneForReload(bool newIsOwner) { InMemoryEvolutionaryStateStore inMemoryEvolutionaryStateStore = new InMemoryEvolutionaryStateStore(m_isValid, newIsOwner); foreach (KeyValuePair value in m_values) { inMemoryEvolutionaryStateStore.m_values[value.Key] = value.Value; } return inMemoryEvolutionaryStateStore; } } public const int OrderStay = 0; public const int OrderFollow = 1; public const int OrderMoveTo = 2; public const int OrderGuard = 3; public const int OrderPatrol = 4; public const int OrderHome = 5; public const int OrderAttack = 6; private static PriorityFixesDiagnosticReport s_diagnostics = new PriorityFixesDiagnosticReport(); [ThreadStatic] private static object s_computingCharacter; [ThreadStatic] private static HashSet s_preProcreateInstanceIds; [ThreadStatic] private static List s_currentProcreateNewborns; [ThreadStatic] private static int s_procreateParentNaturalTier; [ThreadStatic] private static int s_procreateParentOriginBiome; public static readonly int OwnerHash = ComputeStableHash("tm_owner"); public static readonly int OrderHash = ComputeStableHash("tm_order"); public static readonly int CommandActiveHash = ComputeStableHash("tm_command_active"); public static readonly int TierHash = ComputeStableHash("tm_tier"); public static readonly int TierOverrideHash = ComputeStableHash("tm_tier_override"); public static readonly int SavedTierHash = ComputeStableHash("TM_070_BaseTier"); public static readonly int IsUndeadHash = ComputeStableHash("TM_IsUndead"); public static readonly int IsCataclysmicHash = ComputeStableHash("TM_IsCataclysmic"); public static readonly int TierHpInitHash = ComputeStableHash("tm_tier_hp_init"); public static readonly int MutatedHash = ComputeStableHash("tm_mutated"); public static readonly int MutationCheckedHash = ComputeStableHash("tm_mutation_checked"); public static readonly int XpHash = ComputeStableHash("tm_xp"); public static readonly int CompanionLevelHash = ComputeStableHash("tm_level"); public static readonly int StatHealthHash = ComputeStableHash("tm_stat_health"); public static readonly int StatDamageHash = ComputeStableHash("tm_stat_damage"); public static readonly int StatSpeedHash = ComputeStableHash("tm_stat_speed"); public static readonly int NaturalTierHash = ComputeStableHash("tm_natural_tier"); public static readonly int OriginBiomeHash = ComputeStableHash("tm_origin_biome"); public static readonly int NaturalTierSealedHash = ComputeStableHash("tm_natural_sealed"); public static readonly int SpawnLevelInitHash = ComputeStableHash("tm_spawn_lvl_init"); public static PriorityFixesDiagnosticReport Diagnostics => s_diagnostics; private static ManualLogSource Log { get { if (RuntimeBindings.Log == null) { RuntimeBindings.Log = Logger.CreateLogSource("TameMate.PriorityFixes"); } return RuntimeBindings.Log; } } public static int ComputeStableHash(string str) { if (str == null) { return 0; } int num = 5381; int num2 = num; for (int i = 0; i < str.Length && str[i] != 0; i += 2) { num = ((num << 5) + num) ^ str[i]; if (i == str.Length - 1 || str[i + 1] == '\0') { break; } num2 = ((num2 << 5) + num2) ^ str[i + 1]; } return num + num2 * 1566083941; } public static object ConvertTierToRuntimeReturnObject(int resolvedTier, object currentResult) { int num = Mathf.Clamp(resolvedTier, 0, 12); if (currentResult != null) { Type type = currentResult.GetType(); if (type.IsEnum) { if (RuntimeBindings.CreatureTierType == type && RuntimeBindings.BoxedCreatureTiers != null && num >= 0 && num < RuntimeBindings.BoxedCreatureTiers.Length && RuntimeBindings.BoxedCreatureTiers[num] != null) { return RuntimeBindings.BoxedCreatureTiers[num]; } return Enum.ToObject(type, num); } } if (RuntimeBindings.CreatureTierType != null) { if (RuntimeBindings.BoxedCreatureTiers != null && num >= 0 && num < RuntimeBindings.BoxedCreatureTiers.Length && RuntimeBindings.BoxedCreatureTiers[num] != null) { return RuntimeBindings.BoxedCreatureTiers[num]; } return Enum.ToObject(RuntimeBindings.CreatureTierType, num); } return num; } private static bool TryInstallPatchIsolated(PriorityFixesDiagnosticReport report, string patchId, MethodBase targetMethod, Action applyPatch) { if (targetMethod == null) { report.RejectedPatches[patchId] = "Target method not found on assembly."; Log.LogWarning((object)$"[PriorityFixes] Patch '{patchId}' skipped: target method not found."); return false; } try { applyPatch(); Patches patchInfo = Harmony.GetPatchInfo(targetMethod); if (patchInfo == null || ((patchInfo.Prefixes == null || patchInfo.Prefixes.Count <= 0) && (patchInfo.Postfixes == null || patchInfo.Postfixes.Count <= 0) && (patchInfo.Transpilers == null || patchInfo.Transpilers.Count <= 0))) { report.RejectedPatches[patchId] = "Harmony.GetPatchInfo returned no active patches after Patch()."; Log.LogError((object)$"[PriorityFixes] Patch '{patchId}' failed post-install verification."); return false; } if (!report.InstalledPatches.Contains(patchId)) { report.InstalledPatches.Add(patchId); } return true; } catch (Exception ex) { string text = ((ex.GetBaseException() != null) ? ex.GetBaseException().Message : ex.Message); report.RejectedPatches[patchId] = text; Log.LogError((object)$"[PriorityFixes] Patch '{patchId}' rejected by Harmony: {text}"); return false; } } public static PriorityFixesDiagnosticReport SimulateIsolatedPatchInstallation(IEnumerable>> patchSteps) { PriorityFixesDiagnosticReport priorityFixesDiagnosticReport = new PriorityFixesDiagnosticReport(); if (patchSteps != null) { foreach (KeyValuePair> patchStep in patchSteps) { string key = patchStep.Key; try { if (patchStep.Value != null && patchStep.Value()) { if (!priorityFixesDiagnosticReport.InstalledPatches.Contains(key)) { priorityFixesDiagnosticReport.InstalledPatches.Add(key); } } else { priorityFixesDiagnosticReport.RejectedPatches[key] = "Simulated patch returned false."; } } catch (Exception ex) { priorityFixesDiagnosticReport.RejectedPatches[key] = ex.Message; } } } priorityFixesDiagnosticReport.EvaluateFeatureStates(); return priorityFixesDiagnosticReport; } public static void ResetForTesting() { RuntimeBindings.Installed = false; s_diagnostics = new PriorityFixesDiagnosticReport(); } public static void Install(Harmony harmony, Assembly coreAssembly) { if (RuntimeBindings.Installed || harmony == null || coreAssembly == null) { return; } PriorityFixesDiagnosticReport priorityFixesDiagnosticReport = (s_diagnostics = new PriorityFixesDiagnosticReport()); try { RuntimeBindings.CreatureTierType = coreAssembly.GetType("TameMate.CreatureTier"); if (RuntimeBindings.CreatureTierType != null && RuntimeBindings.CreatureTierType.IsEnum) { RuntimeBindings.BoxedCreatureTiers = new object[16]; for (int i = 0; i < RuntimeBindings.BoxedCreatureTiers.Length; i++) { RuntimeBindings.BoxedCreatureTiers[i] = Enum.ToObject(RuntimeBindings.CreatureTierType, i); } } RuntimeBindings.ProcreationOffspringField = AccessTools.Field(typeof(Procreation), "m_offspring"); Type type = coreAssembly.GetType("TameMate.SupremeTierEngine"); Type type2 = coreAssembly.GetType("TameMate.AltairBridge"); Type type3 = coreAssembly.GetType("TameMate.CompanionState"); Type type4 = coreAssembly.GetType("TameMate.TameMateConfig"); Type type5 = coreAssembly.GetType("TameMate.SkillsEngine"); Type type6 = coreAssembly.GetType("TameMate.BloodMoonManager"); Type type7 = coreAssembly.GetType("TameMate.CataclysmIntegration"); Type type8 = coreAssembly.GetType("TameMate.BreedingMutationEngine"); RuntimeBindings.CompanionMotorType = coreAssembly.GetType("TameMate.CompanionMotor"); if (type3 != null) { try { MethodInfo methodInfo = AccessTools.Method(type3, "Owner", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo != null) { RuntimeBindings.GetOwnerFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo); } MethodInfo orderMethod = AccessTools.Method(type3, "Order", new Type[1] { typeof(Character) }, (Type[])null); if (orderMethod != null) { RuntimeBindings.GetOrderFunc = delegate(Character c) { object obj = orderMethod.Invoke(null, new object[1] { c }); return (obj != null) ? Convert.ToInt32(obj) : 0; }; } MethodInfo methodInfo2 = AccessTools.Method(type3, "CommandActive", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo2 != null) { RuntimeBindings.GetCommandActiveFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo2); } } catch (Exception ex) { Log.LogWarning((object)("[PriorityFixes] CompanionState binding warning: " + ex.Message)); } } if (RuntimeBindings.CompanionMotorType != null) { RuntimeBindings.ClearAnchorImmediateMethod = AccessTools.Method(RuntimeBindings.CompanionMotorType, "ClearAnchorImmediate", Type.EmptyTypes, (Type[])null); RuntimeBindings.HasCommittedTargetMethod = AccessTools.Method(RuntimeBindings.CompanionMotorType, "HasCommittedTarget", Type.EmptyTypes, (Type[])null); } if (type4 != null) { FieldInfo mutChanceField = AccessTools.Field(type4, "MutationChance"); if (mutChanceField != null) { RuntimeBindings.GetMutationChanceFunc = delegate { try { object value = mutChanceField.GetValue(null); if (value == null) { return 0f; } PropertyInfo property = value.GetType().GetProperty("Value"); if (property != null) { return Convert.ToSingle(property.GetValue(value, null)); } } catch { } return 0.2f; }; } } if (type5 != null) { MethodInfo methodInfo3 = AccessTools.Method(type5, "GetBreedingMutationBonus", new Type[1] { typeof(Player) }, (Type[])null); if (methodInfo3 != null) { RuntimeBindings.GetBreedingMutationBonusFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo3); } MethodInfo methodInfo4 = AccessTools.Method(type5, "RaisePackMastery", new Type[2] { typeof(Player), typeof(float) }, (Type[])null); if (methodInfo4 != null) { RuntimeBindings.RaisePackMasteryAction = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo4); } } if (type6 != null) { PropertyInfo propertyInfo = AccessTools.Property(type6, "IsActive"); if (propertyInfo != null && propertyInfo.GetGetMethod() != null) { RuntimeBindings.IsBloodMoonActiveFunc = (Func)Delegate.CreateDelegate(typeof(Func), propertyInfo.GetGetMethod()); } } if (type7 != null) { PropertyInfo propertyInfo2 = AccessTools.Property(type7, "ActiveEvent"); if (propertyInfo2 != null && propertyInfo2.GetGetMethod() != null) { RuntimeBindings.GetActiveCataclysmEventFunc = (Func)Delegate.CreateDelegate(typeof(Func), propertyInfo2.GetGetMethod()); } } if (type != null) { MethodInfo getTierMethod = AccessTools.Method(type, "GetTier", new Type[1] { typeof(Character) }, (Type[])null); if (getTierMethod != null) { RuntimeBindings.GetTierFunc = delegate(Character c) { object obj = getTierMethod.Invoke(null, new object[1] { c }); return (obj == null) ? 1 : Convert.ToInt32(obj); }; } MethodInfo methodInfo5 = AccessTools.Method(type, "GetHealthMultiplier", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo5 != null) { RuntimeBindings.GetHealthMultiplierFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo5); } MethodInfo methodInfo6 = AccessTools.Method(type, "InvalidateTier", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo6 != null) { RuntimeBindings.InvalidateTierAction = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo6); } MethodInfo getBiomeAtMethod = AccessTools.Method(type, "GetBiomeAt", new Type[1] { typeof(Vector3) }, (Type[])null); TryInstallPatchIsolated(priorityFixesDiagnosticReport, "SupremeTierEngine.GetBiomeAt", getBiomeAtMethod, delegate { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "GetBiomeAt_Postfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)getBiomeAtMethod, (HarmonyMethod)null, new HarmonyMethod(methodInfo7), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); MethodInfo computeTierMethod = AccessTools.Method(type, "ComputeTier", new Type[2] { typeof(Character), typeof(Biome).MakeByRefType() }, (Type[])null); TryInstallPatchIsolated(priorityFixesDiagnosticReport, "SupremeTierEngine.ComputeTier", computeTierMethod, delegate { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_006f: Expected O, but got Unknown //IL_006f: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "ComputeTier_Prefix", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(PriorityFixesIntegration), "ComputeTier_Transpiler", (Type[])null, (Type[])null); MethodInfo methodInfo9 = AccessTools.Method(typeof(PriorityFixesIntegration), "ComputeTier_Postfix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)computeTierMethod, new HarmonyMethod(methodInfo7), new HarmonyMethod(methodInfo9), new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null); }); } MethodInfo setTamedMethod = AccessTools.Method(typeof(Character), "SetTamed", new Type[1] { typeof(bool) }, (Type[])null); TryInstallPatchIsolated(priorityFixesDiagnosticReport, "Character.SetTamed", setTamedMethod, delegate { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "Character_SetTamed_Prefix", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(PriorityFixesIntegration), "Character_SetTamed_Postfix", (Type[])null, (Type[])null); Harmony obj = harmony; MethodInfo methodInfo9 = setTamedMethod; HarmonyMethod val = new HarmonyMethod(methodInfo7); val.priority = 600; HarmonyMethod val2 = new HarmonyMethod(methodInfo8); val2.priority = 200; obj.Patch((MethodBase)methodInfo9, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); MethodInfo setLevelMethod = AccessTools.Method(typeof(Character), "SetLevel", new Type[1] { typeof(int) }, (Type[])null); TryInstallPatchIsolated(priorityFixesDiagnosticReport, "Character.SetLevel", setLevelMethod, delegate { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "Character_SetLevel_Prefix", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(PriorityFixesIntegration), "Character_SetLevel_Postfix", (Type[])null, (Type[])null); Harmony obj = harmony; MethodInfo methodInfo9 = setLevelMethod; HarmonyMethod val = new HarmonyMethod(methodInfo7); val.priority = 600; HarmonyMethod val2 = new HarmonyMethod(methodInfo8); val2.priority = 200; obj.Patch((MethodBase)methodInfo9, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); MethodInfo procreateMethod = AccessTools.Method(typeof(Procreation), "Procreate", Type.EmptyTypes, (Type[])null); TryInstallPatchIsolated(priorityFixesDiagnosticReport, "Procreation.Procreate", procreateMethod, delegate { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "Procreation_Procreate_Prefix", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(PriorityFixesIntegration), "Procreation_Procreate_Postfix_High", (Type[])null, (Type[])null); MethodInfo methodInfo9 = AccessTools.Method(typeof(PriorityFixesIntegration), "Procreation_Procreate_Postfix_Low", (Type[])null, (Type[])null); Harmony obj = harmony; MethodInfo methodInfo10 = procreateMethod; HarmonyMethod val = new HarmonyMethod(methodInfo7); val.priority = 600; HarmonyMethod val2 = new HarmonyMethod(methodInfo8); val2.priority = 600; obj.Patch((MethodBase)methodInfo10, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Harmony obj2 = harmony; MethodInfo methodInfo11 = procreateMethod; HarmonyMethod val3 = new HarmonyMethod(methodInfo9); val3.priority = 200; obj2.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); Type type9 = null; if (type8 != null) { type9 = type8.GetNestedType("BreedingMutationPatch", BindingFlags.Public | BindingFlags.NonPublic); } if (type9 == null) { type9 = coreAssembly.GetType("TameMate.BreedingMutationEngine+BreedingMutationPatch"); } MethodInfo breedingMutationPostfixMethod = ((type9 != null) ? AccessTools.Method(type9, "Postfix", new Type[1] { typeof(Procreation) }, (Type[])null) : null); TryInstallPatchIsolated(priorityFixesDiagnosticReport, "BreedingMutationPatch.Postfix", breedingMutationPostfixMethod, delegate { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "BreedingMutationPatch_Prefix", (Type[])null, (Type[])null); Harmony obj = harmony; MethodInfo methodInfo8 = breedingMutationPostfixMethod; HarmonyMethod val = new HarmonyMethod(methodInfo7); val.priority = 800; obj.Patch((MethodBase)methodInfo8, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); MethodInfo rescueRoutineMethod = null; if (type2 != null) { RuntimeBindings.GodShieldDictField = AccessTools.Field(type2, "s_companionGodShieldUntil"); RuntimeBindings.RavenAdviceMethod = AccessTools.Method(type2, "TriggerAltairSynergyAdvice", new Type[3] { typeof(Player), typeof(string), typeof(string) }, (Type[])null); rescueRoutineMethod = AccessTools.Method(type2, "RescueCompanionsAtCorpseRoutine", new Type[1] { typeof(Player) }, (Type[])null); } TryInstallPatchIsolated(priorityFixesDiagnosticReport, "AltairBridge.RescueCompanionsAtCorpseRoutine", rescueRoutineMethod, delegate { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown MethodInfo methodInfo7 = AccessTools.Method(typeof(PriorityFixesIntegration), "RescueCompanionsAtCorpseRoutine_Prefix", (Type[])null, (Type[])null); Harmony obj = harmony; MethodInfo methodInfo8 = rescueRoutineMethod; HarmonyMethod val = new HarmonyMethod(methodInfo7); val.priority = 600; obj.Patch((MethodBase)methodInfo8, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); priorityFixesDiagnosticReport.EvaluateFeatureStates(); RuntimeBindings.Installed = priorityFixesDiagnosticReport.InstalledPatches.Count > 0; string text = ((priorityFixesDiagnosticReport.InstalledPatches.Count > 0) ? string.Join(", ", priorityFixesDiagnosticReport.InstalledPatches.ToArray()) : "none"); string text2 = "none"; if (priorityFixesDiagnosticReport.RejectedPatches.Count > 0) { List list = new List(); foreach (KeyValuePair rejectedPatch in priorityFixesDiagnosticReport.RejectedPatches) { list.Add(rejectedPatch.Key + " (" + rejectedPatch.Value + ")"); } text2 = string.Join("; ", list.ToArray()); } List list2 = new List(); foreach (KeyValuePair featureState in priorityFixesDiagnosticReport.FeatureStates) { list2.Add(featureState.Key + "=" + (featureState.Value ? "ACTIVE" : "INACTIVE")); } if (priorityFixesDiagnosticReport.OverallState == "FullyOperational") { Log.LogInfo((object)string.Format("[PriorityFixes] D-09.9.8 Initialization State: {0} | Installed ({1}): [{2}] | Rejected: [{3}] | Features: [{4}]", priorityFixesDiagnosticReport.OverallState, priorityFixesDiagnosticReport.InstalledPatches.Count, text, text2, string.Join(", ", list2.ToArray()))); } else { Log.LogWarning((object)string.Format("[PriorityFixes] D-09.9.8 Initialization State: {0} | Installed ({1}): [{2}] | Rejected ({3}): [{4}] | Features: [{5}]", priorityFixesDiagnosticReport.OverallState, priorityFixesDiagnosticReport.InstalledPatches.Count, text, priorityFixesDiagnosticReport.RejectedPatches.Count, text2, string.Join(", ", list2.ToArray()))); } } catch (Exception ex2) { priorityFixesDiagnosticReport.EvaluateFeatureStates(); Log.LogError((object)("[PriorityFixes] Unexpected error in Install coordinator: " + ex2)); } } public static IEnumerable ComputeTier_Transpiler(IEnumerable instructions) { List list = new List(instructions); for (int i = 0; i < list.Count; i++) { if (!(list[i].opcode == OpCodes.Or) || i < 1 || !(list[i - 1].opcode == OpCodes.Ldloc_3)) { continue; } bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; bool flag5 = false; int num = Math.Min(list.Count, i + 6); int num2 = 0; for (int j = i + 1; j < num; j++) { OpCode opcode = list[j].opcode; if (opcode == OpCodes.Ldc_I4_2) { flag = true; } else if (opcode == OpCodes.Ldc_I4_3) { flag2 = true; } else if (opcode == OpCodes.Ldc_I4_4) { flag3 = true; } else if (opcode == OpCodes.Ldc_I4_5) { flag4 = true; } else if (opcode == OpCodes.Ldc_I4_6) { flag5 = true; } else if (opcode == OpCodes.Ret) { num2++; if (num2 >= 2) { break; } } } if ((!flag || !flag2 || flag3 || flag4 || flag5) && ((flag2 && flag3) || (flag3 && flag4) || (flag4 && flag5))) { list[i].opcode = OpCodes.And; } } return list; } public static int EvaluateBiomeEliteTier(Biome biome, int stars, int biomeAscensionLevel) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_001e: Expected I4, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Invalid comparison between Unknown and I4 bool flag = biomeAscensionLevel >= 1; switch (biome - 2) { default: if ((int)biome != 8) { if ((int)biome != 16) { break; } if (biomeAscensionLevel >= 3) { return 8; } if (biomeAscensionLevel >= 2) { return 7; } if (stars < 1 || !flag) { return 5; } return 6; } if (biomeAscensionLevel >= 3) { return 5; } if (biomeAscensionLevel >= 2) { return 4; } if (stars < 1 && !flag) { return 2; } return 3; case 0: if (biomeAscensionLevel >= 3) { return 6; } if (biomeAscensionLevel >= 2) { return 5; } if (stars < 1 || !flag) { return 3; } return 4; case 2: if (biomeAscensionLevel >= 3) { return 7; } if (biomeAscensionLevel >= 2) { return 6; } if (stars < 1 || !flag) { return 4; } return 5; case 1: break; } return 1; } public static Biome ResolveAndPersistOriginBiome(IEvolutionaryStateStore store, Biome currentPositionBiome) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected I4, but got Unknown if (store == null || !store.IsValid) { return currentPositionBiome; } int num = store.GetInt(OriginBiomeHash, 0); if (num > 0) { return (Biome)num; } if ((int)currentPositionBiome != 0 && store.IsOwner) { store.SetInt(OriginBiomeHash, (int)currentPositionBiome); } return currentPositionBiome; } public static int ResolveAndPersistEvolutionaryTier(IEvolutionaryStateStore store, bool isTamed, int level, Biome currentPositionBiome, int rawComputedTierInOriginBiome, out Biome effectiveOriginBiome) { //IL_0003: 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_000a: Expected I4, but got Unknown effectiveOriginBiome = (Biome)(int)ResolveAndPersistOriginBiome(store, currentPositionBiome); if (store == null || !store.IsValid) { return rawComputedTierInOriginBiome; } if (rawComputedTierInOriginBiome == 11 || store.GetInt(IsUndeadHash, 0) == 1) { return 11; } int num = store.GetInt(TierOverrideHash, 0); if (num > 0) { return Mathf.Clamp(num, 1, 11); } int num2 = store.GetInt(SavedTierHash, 0); if (isTamed && num2 >= 1 && num2 <= 10) { return num2; } if (!isTamed && rawComputedTierInOriginBiome == 9) { return 9; } int num3 = store.GetInt(NaturalTierHash, 0); bool flag = isTamed || store.GetInt(NaturalTierSealedHash, 0) == 1; if (num3 >= 1 && num3 <= 10 && flag) { return num3; } int num4 = Mathf.Clamp(rawComputedTierInOriginBiome, 1, 10); if (store.IsOwner) { store.SetInt(NaturalTierHash, num4); if (isTamed || level > 1 || store.GetInt(TierHpInitHash, 0) == 1) { store.SetInt(NaturalTierSealedHash, 1); } } return num4; } public static void LockNaturalIdentityOnTame(IEvolutionaryStateStore store, Biome currentPositionBiome, int preTameNaturalTier, bool claimOwnershipIfNeeded) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected I4, but got Unknown if (store == null || !store.IsValid) { return; } if (claimOwnershipIfNeeded && !store.IsOwner) { store.ClaimOwnership(); } if (store.IsOwner) { if (store.GetInt(OriginBiomeHash, 0) <= 0 && (int)currentPositionBiome != 0) { store.SetInt(OriginBiomeHash, (int)currentPositionBiome); } int num = store.GetInt(NaturalTierHash, 0); if (num < 1 || num > 10) { int value = Mathf.Clamp(preTameNaturalTier, 1, 10); store.SetInt(NaturalTierHash, value); } store.SetInt(NaturalTierSealedHash, 1); store.SetInt(SpawnLevelInitHash, 1); } } public static bool PrepareForSetLevel(IEvolutionaryStateStore store, bool isTamed) { if (store == null || !store.IsValid || !store.IsOwner) { return false; } if (isTamed || store.GetInt(SpawnLevelInitHash, 0) == 1 || store.GetInt(TierHpInitHash, 0) == 1) { if (store.GetInt(NaturalTierHash, 0) > 0) { store.SetInt(NaturalTierSealedHash, 1); } return false; } store.SetInt(NaturalTierSealedHash, 0); store.SetInt(SpawnLevelInitHash, 1); return true; } public static void InheritOffspringEvolutionaryIdentity(IEvolutionaryStateStore parentStore, int parentFallbackNaturalTier, Biome parentFallbackBiome, IEvolutionaryStateStore offspringStore) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected I4, but got Unknown if (offspringStore == null || !offspringStore.IsValid || !offspringStore.IsOwner) { return; } int num = (int)parentFallbackBiome; int value = Mathf.Clamp(parentFallbackNaturalTier, 1, 10); if (parentStore != null && parentStore.IsValid) { int num2 = parentStore.GetInt(OriginBiomeHash, 0); if (num2 > 0) { num = num2; } int num3 = parentStore.GetInt(NaturalTierHash, 0); int num4 = parentStore.GetInt(SavedTierHash, 0); if (num3 >= 1 && num3 <= 10) { value = num3; } else if (num4 >= 1 && num4 <= 10) { value = num4; } } if (num > 0) { offspringStore.SetInt(OriginBiomeHash, num); } offspringStore.SetInt(NaturalTierHash, value); offspringStore.SetInt(NaturalTierSealedHash, 1); offspringStore.SetInt(SpawnLevelInitHash, 1); } public static int ComputeStandardNaturalTierInBiome(Biome originBiome, int stars, int biomeAscensionLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Invalid comparison between Unknown and I4 //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Invalid comparison between Unknown and I4 //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Invalid comparison between Unknown and I4 //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 if ((int)originBiome <= 16) { switch (originBiome - 1) { default: if ((int)originBiome != 8) { if ((int)originBiome != 16) { break; } switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 5; } return 6; case 2: if (stars < 2) { return 6; } return 7; case 3: if (stars < 2) { return 7; } return 8; default: return 5; } } switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 2; } return 3; case 2: if (stars < 2) { return 3; } return 4; case 3: if (stars < 2) { return 4; } return 5; default: return 2; } case 0: switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 1; } return 2; case 2: if (stars < 3) { if (stars < 1) { return 2; } return 3; } return 4; case 3: if (stars < 3) { if (stars < 1) { return 3; } return 4; } return 5; default: return 1; } case 1: switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 3; } return 4; case 2: if (stars < 2) { return 4; } return 5; case 3: if (stars < 2) { return 5; } return 6; default: return 3; } case 3: switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 4; } return 5; case 2: if (stars < 2) { return 5; } return 6; case 3: if (stars < 2) { return 6; } return 7; default: return 4; } case 2: break; } } else if ((int)originBiome <= 64) { if ((int)originBiome == 32) { goto IL_01a7; } if ((int)originBiome == 64) { return 4; } } else { if ((int)originBiome == 256) { goto IL_01a7; } if ((int)originBiome == 512) { switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 6; } return 7; case 2: if (stars < 2) { return 7; } return 8; case 3: if (stars < 2) { return 8; } return 10; default: return 6; } } } return 1; IL_01a7: switch (biomeAscensionLevel) { case 1: if (stars < 2) { return 7; } return 8; case 2: if (stars < 2) { return 8; } return 10; case 3: return 10; default: return 7; } } public static void ComputeTier_Prefix(Character c) { s_computingCharacter = c; } public static void GetBiomeAt_Postfix(Vector3 pos, ref Biome __result) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected I4, but got Unknown object obj = s_computingCharacter; Character val = (Character)((obj is Character) ? obj : null); if ((Object)(object)val == (Object)null || val.IsPlayer()) { return; } try { ZNetView component = ((Component)val).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { ZDO zDO = component.GetZDO(); if (zDO != null) { ValheimEvolutionaryStateStore store = new ValheimEvolutionaryStateStore(component, zDO); __result = (Biome)(int)ResolveAndPersistOriginBiome(store, __result); } } } catch { } } public static void ComputeTier_Postfix(Character c, ref Biome biome, ref object __result) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected I4, but got Unknown s_computingCharacter = null; if ((Object)(object)c == (Object)null || c.IsPlayer()) { return; } try { ZNetView component = ((Component)c).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { ZDO zDO = component.GetZDO(); if (zDO != null) { int rawComputedTierInOriginBiome = ((__result == null) ? 1 : Convert.ToInt32(__result)); ValheimEvolutionaryStateStore store = new ValheimEvolutionaryStateStore(component, zDO); Biome effectiveOriginBiome; int resolvedTier = ResolveAndPersistEvolutionaryTier(store, c.IsTamed(), c.GetLevel(), biome, rawComputedTierInOriginBiome, out effectiveOriginBiome); biome = (Biome)(int)effectiveOriginBiome; __result = ConvertTierToRuntimeReturnObject(resolvedTier, __result); } } } catch { } } public static void Character_SetTamed_Prefix(Character __instance, bool tamed) { //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: 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_00c6: Unknown result type (might be due to invalid IL or missing references) if (!tamed || (Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } try { ZNetView component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null) { return; } ValheimEvolutionaryStateStore valheimEvolutionaryStateStore = new ValheimEvolutionaryStateStore(component, zDO); int num = valheimEvolutionaryStateStore.GetInt(NaturalTierHash, 0); if (num <= 0 && RuntimeBindings.GetTierFunc != null) { try { num = RuntimeBindings.GetTierFunc(__instance); } catch { num = 1; } } if (num == 9 || num == 11) { int num2 = valheimEvolutionaryStateStore.GetInt(SavedTierHash, 0); num = ((num2 < 1 || num2 > 10) ? 1 : num2); } Biome currentPositionBiome = (Biome)0; if (HeightmapBuilder.instance != null) { try { currentPositionBiome = (Biome)((WorldGenerator.instance != null) ? ((int)WorldGenerator.instance.GetBiome(((Component)__instance).transform.position)) : 0); } catch { } } LockNaturalIdentityOnTame(valheimEvolutionaryStateStore, currentPositionBiome, (num <= 0) ? 1 : num, claimOwnershipIfNeeded: true); } catch { } } public static void Character_SetTamed_Postfix(Character __instance, bool tamed) { if (!tamed || (Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } try { ZNetView component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO != null) { ValheimEvolutionaryStateStore valheimEvolutionaryStateStore = new ValheimEvolutionaryStateStore(component, zDO); if (valheimEvolutionaryStateStore.IsOwner && valheimEvolutionaryStateStore.GetInt(NaturalTierHash, 0) > 0) { valheimEvolutionaryStateStore.SetInt(NaturalTierSealedHash, 1); valheimEvolutionaryStateStore.SetInt(SpawnLevelInitHash, 1); } } } catch { } } public static void Character_SetLevel_Prefix(Character __instance, int level) { if ((Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } try { ZNetView component = ((Component)__instance).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { ZDO zDO = component.GetZDO(); if (zDO != null) { ValheimEvolutionaryStateStore store = new ValheimEvolutionaryStateStore(component, zDO); PrepareForSetLevel(store, __instance.IsTamed()); } } } catch { } } public static void Character_SetLevel_Postfix(Character __instance, int level) { if ((Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } try { ZNetView component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO == null) { return; } ValheimEvolutionaryStateStore valheimEvolutionaryStateStore = new ValheimEvolutionaryStateStore(component, zDO); if (__instance.IsTamed() || !valheimEvolutionaryStateStore.IsOwner || valheimEvolutionaryStateStore.GetInt(NaturalTierSealedHash, 0) != 0) { return; } if (RuntimeBindings.InvalidateTierAction != null) { try { RuntimeBindings.InvalidateTierAction(__instance); } catch { } } if (RuntimeBindings.GetTierFunc != null) { try { RuntimeBindings.GetTierFunc(__instance); } catch { } } valheimEvolutionaryStateStore.SetInt(NaturalTierSealedHash, 1); } catch { } } public static bool EvaluateNewbornDescendantEligibility(bool existedBeforeProcreateCall, bool isParentItself, bool isPlayerOrBossOrDead, bool hasValidZNetViewAndOwner, float distanceFromParentMeters, bool alreadyMutationChecked, bool alreadyMutated, bool hasAdultCompanionProgression, bool hasActivePlayerOrder, bool hasGrowupComponent, bool matchesOffspringOrParentSpecies) { if (existedBeforeProcreateCall) { return false; } if (isParentItself || isPlayerOrBossOrDead) { return false; } if (!hasValidZNetViewAndOwner) { return false; } if (distanceFromParentMeters > 6f) { return false; } if (alreadyMutationChecked || alreadyMutated) { return false; } if (hasAdultCompanionProgression || hasActivePlayerOrder) { return false; } if (!hasGrowupComponent) { return matchesOffspringOrParentSpecies; } return true; } public static bool TryRollNewbornMutation(IEvolutionaryStateStore candidateStore, bool isEligibleNewborn, float effectiveMutationChance, float randomRoll01, ref int creatureLevel) { if (candidateStore == null || !candidateStore.IsValid || !candidateStore.IsOwner) { return false; } if (!isEligibleNewborn) { return false; } if (candidateStore.GetInt(MutationCheckedHash, 0) != 0) { return false; } candidateStore.SetInt(MutationCheckedHash, 1); if (effectiveMutationChance <= 0f) { return false; } if (randomRoll01 <= effectiveMutationChance) { creatureLevel = Mathf.Max(1, creatureLevel) + 1; candidateStore.SetInt(MutatedHash, 1); return true; } return false; } public static void ComputeIdempotentCompanionHealth(float prefabBaseHealth, int level, float tierHealthMultiplier, bool isMutated, int healthStatPoints, out float targetZdoBaseMaxHealth, out float expectedEffectiveMaxHealth) { float num = Mathf.Max(1f, prefabBaseHealth); int num2 = Mathf.Max(1, level); float num3 = Mathf.Max(1f, tierHealthMultiplier); float num4 = (isMutated ? 1.25f : 1f); int num5 = Mathf.Max(0, healthStatPoints); float num6 = 1f + (float)num5 * 0.05f; targetZdoBaseMaxHealth = Mathf.Max(1f, num * (float)num2 * num3 * num4); expectedEffectiveMaxHealth = targetZdoBaseMaxHealth * num6; } public static float ReconstructHistoricalCompoundedMutationHealth(float preMutationZdoBaseHealth, int healthStatPoints) { float num = 1f + (float)Mathf.Max(0, healthStatPoints) * 0.05f; float num2 = preMutationZdoBaseHealth * num; float num3 = num2 * 1.25f; return num3 * num; } public static void Procreation_Procreate_Prefix(Procreation __instance) { if ((Object)(object)__instance == (Object)null) { return; } try { Character component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null) { return; } s_preProcreateInstanceIds = new HashSet(); s_currentProcreateNewborns = new List(); List allCharacters = Character.GetAllCharacters(); if (allCharacters != null) { for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if ((Object)(object)val != (Object)null) { s_preProcreateInstanceIds.Add(((Object)val).GetInstanceID()); } } } s_procreateParentNaturalTier = GetDisplayedCompanionBaseTier(component, null); s_procreateParentOriginBiome = 0; ZNetView component2 = ((Component)component).GetComponent(); if ((Object)(object)component2 != (Object)null && component2.IsValid() && component2.GetZDO() != null) { s_procreateParentOriginBiome = component2.GetZDO().GetInt(OriginBiomeHash, 0); } } catch { } } public static void Procreation_Procreate_Postfix_High(Procreation __instance) { PropagateProcreationIdentityToNewborns(__instance); } public static void Procreation_Procreate_Postfix_Low(Procreation __instance) { PropagateProcreationIdentityToNewborns(__instance); s_preProcreateInstanceIds = null; s_currentProcreateNewborns = null; } public static List GetConfirmedNewbornsForCurrentProcreate(Procreation procreation) { if (s_currentProcreateNewborns == null && (Object)(object)procreation != (Object)null && s_preProcreateInstanceIds != null) { PropagateProcreationIdentityToNewborns(procreation); } return s_currentProcreateNewborns ?? new List(); } private static bool IsCharacterAdultCompanionWithProgression(ZDO zdo) { if (zdo == null) { return false; } if (zdo.GetInt(XpHash, 0) <= 0 && zdo.GetInt(CompanionLevelHash, 1) <= 1 && zdo.GetInt(StatHealthHash, 0) <= 0 && zdo.GetInt(StatDamageHash, 0) <= 0 && zdo.GetInt(StatSpeedHash, 0) <= 0 && zdo.GetInt(TierOverrideHash, 0) <= 0) { return zdo.GetInt(SavedTierHash, 0) > 0; } return true; } private static void PropagateProcreationIdentityToNewborns(Procreation procreation) { //IL_00c0: 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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)procreation == (Object)null || s_preProcreateInstanceIds == null) { return; } try { Character component = ((Component)procreation).GetComponent(); if ((Object)(object)component == (Object)null) { return; } ZNetView component2 = ((Component)component).GetComponent(); ZDO val = (((Object)(object)component2 != (Object)null && component2.IsValid()) ? component2.GetZDO() : null); ValheimEvolutionaryStateStore parentStore = (((Object)(object)component2 != (Object)null && val != null) ? new ValheimEvolutionaryStateStore(component2, val) : null); string value = null; if (RuntimeBindings.ProcreationOffspringField != null) { try { object? value2 = RuntimeBindings.ProcreationOffspringField.GetValue(procreation); GameObject val2 = (GameObject)((value2 is GameObject) ? value2 : null); if ((Object)(object)val2 != (Object)null) { value = ((Object)val2).name; } } catch { } } List allCharacters = Character.GetAllCharacters(); if (allCharacters == null) { return; } if (s_currentProcreateNewborns == null) { s_currentProcreateNewborns = new List(); } Vector3 position = ((Component)procreation).transform.position; for (int i = 0; i < allCharacters.Count; i++) { Character val3 = allCharacters[i]; if ((Object)(object)val3 == (Object)null || (Object)(object)val3 == (Object)(object)component || val3.IsPlayer() || s_preProcreateInstanceIds.Contains(((Object)val3).GetInstanceID())) { continue; } float num = Vector3.Distance(((Component)val3).transform.position, position); if (num > 6f) { continue; } ZNetView component3 = ((Component)val3).GetComponent(); if ((Object)(object)component3 == (Object)null || !component3.IsValid()) { continue; } ZDO zDO = component3.GetZDO(); if (zDO == null) { continue; } bool hasGrowupComponent = (Object)(object)((Component)val3).GetComponent() != (Object)null; bool matchesOffspringOrParentSpecies = true; if (!string.IsNullOrEmpty(value) && (Object)(object)((Component)val3).gameObject != (Object)null && !string.IsNullOrEmpty(((Object)((Component)val3).gameObject).name)) { matchesOffspringOrParentSpecies = ((Object)((Component)val3).gameObject).name.StartsWith(value, StringComparison.OrdinalIgnoreCase) || string.Equals(val3.m_name, component.m_name, StringComparison.OrdinalIgnoreCase); } if (!EvaluateNewbornDescendantEligibility(existedBeforeProcreateCall: false, isParentItself: false, val3.IsPlayer() || val3.IsBoss() || val3.IsDead(), component3.IsOwner(), num, zDO.GetInt(MutationCheckedHash, 0) != 0, zDO.GetInt(MutatedHash, 0) != 0, IsCharacterAdultCompanionWithProgression(zDO), zDO.GetInt(CommandActiveHash, 0) != 0, hasGrowupComponent, matchesOffspringOrParentSpecies)) { continue; } if (!s_currentProcreateNewborns.Contains(val3)) { s_currentProcreateNewborns.Add(val3); } ValheimEvolutionaryStateStore offspringStore = new ValheimEvolutionaryStateStore(component3, zDO); InheritOffspringEvolutionaryIdentity(parentStore, (s_procreateParentNaturalTier <= 0) ? 1 : s_procreateParentNaturalTier, (Biome)s_procreateParentOriginBiome, offspringStore); if (RuntimeBindings.InvalidateTierAction != null) { try { RuntimeBindings.InvalidateTierAction(val3); } catch { } } } } catch { } } public static bool BreedingMutationPatch_Prefix(Procreation __instance) { //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null) { return false; } try { float num = ((RuntimeBindings.GetMutationChanceFunc != null) ? RuntimeBindings.GetMutationChanceFunc() : 0.2f); if (num <= 0f) { return false; } List confirmedNewbornsForCurrentProcreate = GetConfirmedNewbornsForCurrentProcreate(__instance); if (confirmedNewbornsForCurrentProcreate == null || confirmedNewbornsForCurrentProcreate.Count == 0) { return false; } for (int i = 0; i < confirmedNewbornsForCurrentProcreate.Count; i++) { Character val = confirmedNewbornsForCurrentProcreate[i]; if ((Object)(object)val == (Object)null || val.IsDead() || !val.IsTamed()) { continue; } ZNetView component = ((Component)val).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner()) { continue; } ZDO zDO = component.GetZDO(); if (zDO == null || zDO.GetInt(MutationCheckedHash, 0) != 0) { continue; } Player closestPlayer = Player.GetClosestPlayer(((Component)__instance).transform.position, 30f); float num2 = num; if ((Object)(object)closestPlayer != (Object)null) { if (RuntimeBindings.GetBreedingMutationBonusFunc != null) { try { num2 += RuntimeBindings.GetBreedingMutationBonusFunc(closestPlayer); } catch { } } if (RuntimeBindings.RaisePackMasteryAction != null) { try { RuntimeBindings.RaisePackMasteryAction(closestPlayer, 1.5f); } catch { } } } if (RuntimeBindings.IsBloodMoonActiveFunc != null) { try { if (RuntimeBindings.IsBloodMoonActiveFunc()) { num2 *= 2.2f; } } catch { } } if (RuntimeBindings.GetActiveCataclysmEventFunc != null) { try { string value = RuntimeBindings.GetActiveCataclysmEventFunc(); if (!string.IsNullOrEmpty(value)) { num2 *= 1.5f; } } catch { } } ValheimEvolutionaryStateStore candidateStore = new ValheimEvolutionaryStateStore(component, zDO); int creatureLevel = val.GetLevel(); float value2 = Random.value; if (!TryRollNewbornMutation(candidateStore, isEligibleNewborn: true, num2, value2, ref creatureLevel)) { break; } val.SetLevel(creatureLevel); float tierHealthMultiplier = 1f; if (RuntimeBindings.GetHealthMultiplierFunc != null) { try { tierHealthMultiplier = Mathf.Max(1f, RuntimeBindings.GetHealthMultiplierFunc(val)); } catch { tierHealthMultiplier = 1f; } } int healthStatPoints = Mathf.Max(0, zDO.GetInt(StatHealthHash, 0)); ComputeIdempotentCompanionHealth(val.GetMaxHealthBase(), creatureLevel, tierHealthMultiplier, isMutated: true, healthStatPoints, out var targetZdoBaseMaxHealth, out var _); val.SetMaxHealth(targetZdoBaseMaxHealth); val.SetHealth(val.GetMaxHealth()); if ((Object)(object)closestPlayer != (Object)null) { ((Character)closestPlayer).Message((MessageType)2, $"¡MUTACIÓN GENÉTICA! (+1 Estrella: {val.m_name})", 0, (Sprite)null, false); } if ((Object)(object)ZNetScene.instance != (Object)null) { GameObject prefab = ZNetScene.instance.GetPrefab("vfx_LevelUp"); if ((Object)(object)prefab != (Object)null) { Object.Instantiate(prefab, ((Component)val).transform.position, Quaternion.identity); } } break; } } catch { } return false; } public static int GetDisplayedCompanionBaseTier(Character c, ZDO zdo) { if (zdo == null && (Object)(object)c != (Object)null) { ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { zdo = component.GetZDO(); } } if (zdo != null) { int num = zdo.GetInt(TierOverrideHash, 0); if (num >= 1 && num <= 10) { return num; } int num2 = zdo.GetInt(SavedTierHash, 0); if (num2 >= 1 && num2 <= 10) { return num2; } int num3 = zdo.GetInt(NaturalTierHash, 0); if (num3 >= 1 && num3 <= 10) { return num3; } } if ((Object)(object)c != (Object)null && RuntimeBindings.GetTierFunc != null) { try { int num4 = RuntimeBindings.GetTierFunc(c); if (num4 >= 1 && num4 <= 10 && num4 != 9) { return num4; } } catch { } } return 1; } public static int EvaluateSwampEliteTierWithOverrides(bool isUndead, int tierOverride, int persistedTier, bool defeatedBonemass, bool defeatedVrykolathas, bool defeatedDraugrLord, bool nightOrStorm) { if (isUndead) { return 11; } if (tierOverride >= 0 && tierOverride <= 11) { return tierOverride; } if (persistedTier >= 0 && persistedTier <= 11) { return persistedTier; } if ((!defeatedBonemass && !defeatedVrykolathas && !defeatedDraugrLord) || !nightOrStorm) { return 3; } return 4; } public static int ValidateTierCore(int rawTier, bool isTamed, int persistedTier, Biome biome, bool isSwampAscended, int stars) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Invalid comparison between Unknown and I4 //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Invalid comparison between Unknown and I4 switch (rawTier) { case 11: return 11; default: return rawTier; case 4: if (isTamed && persistedTier > 0) { return rawTier; } if ((int)biome == 4 || (int)biome == 64) { return 4; } if ((int)biome == 2) { if (!isSwampAscended) { return 3; } if (stars < 1) { return 3; } return 4; } if ((int)biome == 1 || (int)biome == 8) { return Math.Min(rawTier, 3); } return rawTier; } } public static int ValidateTierAgainstBiomeProgression(int rawTier, Character c, Biome biome) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) bool isTamed = false; int persistedTier = 0; int stars = 0; if ((Object)(object)c != (Object)null) { stars = Mathf.Max(0, c.GetLevel() - 1); if (c.IsTamed()) { isTamed = true; ZNetView component = ((Component)c).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { ZDO zDO = component.GetZDO(); if (zDO != null) { int num = zDO.GetInt(TierOverrideHash, -1); if (num >= 0) { return num; } persistedTier = zDO.GetInt(TierHash, 0); } } } } bool isSwampAscended = false; if ((Object)(object)ZoneSystem.instance != (Object)null) { isSwampAscended = ZoneSystem.instance.GetGlobalKey("defeated_bonemass") || ZoneSystem.instance.GetGlobalKey("defeated_vrykolathas") || ZoneSystem.instance.GetGlobalKey("defeated_draugr_lord"); } return ValidateTierCore(rawTier, isTamed, persistedTier, biome, isSwampAscended, stars); } public static bool EvaluateCompanionRescueEligibility(bool isDead, bool isTamed, bool isBoss, bool isPlayer, bool hasValidZNetView, bool hasMonsterAi, bool isDirectFollowTargetLocalPlayer, bool isOrderAnchorFollowTarget, bool hasCommittedCombatTarget, long ownerId, int persistedOrder, bool commandActive, long playerId) { if (isDead || !isTamed || isBoss || isPlayer) { return false; } if (!hasValidZNetView || !hasMonsterAi) { return false; } if (playerId != 0 && ownerId != 0 && ownerId != playerId) { return false; } if (commandActive && persistedOrder != 1) { return false; } if (playerId != 0 && ownerId == playerId && persistedOrder == 1) { return true; } if (playerId != 0 && ownerId == playerId && (isOrderAnchorFollowTarget || hasCommittedCombatTarget) && persistedOrder == 1) { return true; } if (isDirectFollowTargetLocalPlayer && (ownerId == 0 || ownerId == playerId) && persistedOrder != 2 && persistedOrder != 3 && persistedOrder != 4 && persistedOrder != 5) { return true; } return false; } public static bool ShouldRescueCompanion(bool isDead, bool isTamed, bool isBoss, bool isPlayer, bool hasValidZNetView, bool hasMonsterAi, bool isFollowingThisPlayer, long ownerId, long playerId) { return EvaluateCompanionRescueEligibility(isDead, isTamed, isBoss, isPlayer, hasValidZNetView, hasMonsterAi, isFollowingThisPlayer, isOrderAnchorFollowTarget: false, hasCommittedCombatTarget: false, ownerId, isFollowingThisPlayer ? 1 : 0, !isFollowingThisPlayer, playerId); } public static bool ShouldApplyEmergencyHealing(float currentHealth, float maxHealth, out float healAmount) { healAmount = 0f; if (maxHealth <= 0f) { return false; } if (currentHealth < maxHealth * 0.35f) { healAmount = maxHealth * 0.25f; return true; } return false; } public static bool RescueCompanionsAtCorpseRoutine_Prefix(Player jugador, ref IEnumerator __result) { __result = SafeRescueCompanionsRoutine(jugador); return false; } public static IEnumerator SafeRescueCompanionsRoutine(Player jugador) { yield return (object)new WaitForSeconds(0.4f); if ((Object)(object)jugador == (Object)null || ((Character)jugador).IsDead()) { yield break; } Vector3 corpsePos = ((Component)jugador).transform.position; long playerId = jugador.GetPlayerID(); float godShieldDuration = 15f; float godShieldUntil = Time.time + godShieldDuration; int rescuedCount = 0; List allCharacters = Character.GetAllCharacters(); if (allCharacters == null) { yield break; } Dictionary godShieldDict = null; if (RuntimeBindings.GodShieldDictField != null) { try { godShieldDict = RuntimeBindings.GodShieldDictField.GetValue(null) as Dictionary; } catch { } } float num2 = default(float); for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if ((Object)(object)val == (Object)null) { continue; } ZNetView component = ((Component)val).GetComponent(); bool flag = (Object)(object)component != (Object)null && component.IsValid(); ZDO val2 = (flag ? component.GetZDO() : null); MonsterAI component2 = ((Component)val).GetComponent(); bool flag2 = (Object)(object)component2 != (Object)null; GameObject val3 = (flag2 ? component2.GetFollowTarget() : null); bool isDirectFollowTargetLocalPlayer = (Object)(object)val3 != (Object)null && (Object)(object)val3 == (Object)(object)((Component)jugador).gameObject; bool isOrderAnchorFollowTarget = (Object)(object)val3 != (Object)null && ((Object)val3).name == "TameMate_OrderAnchor"; long num = 0L; int persistedOrder = 0; bool commandActive = false; if (val2 != null) { num = val2.GetLong(OwnerHash, 0L); persistedOrder = Mathf.Clamp(val2.GetInt(OrderHash, 0), 0, 6); commandActive = val2.GetInt(CommandActiveHash, 0) != 0; } else { if (RuntimeBindings.GetOwnerFunc != null) { try { num = RuntimeBindings.GetOwnerFunc(val); } catch { } } if (RuntimeBindings.GetOrderFunc != null) { try { persistedOrder = RuntimeBindings.GetOrderFunc(val); } catch { } } if (RuntimeBindings.GetCommandActiveFunc != null) { try { commandActive = RuntimeBindings.GetCommandActiveFunc(val); } catch { } } } Component val4 = ((RuntimeBindings.CompanionMotorType != null) ? ((Component)val).GetComponent(RuntimeBindings.CompanionMotorType) : null); bool hasCommittedCombatTarget = false; if ((Object)(object)val4 != (Object)null && RuntimeBindings.HasCommittedTargetMethod != null) { try { object obj5 = RuntimeBindings.HasCommittedTargetMethod.Invoke(val4, null); hasCommittedCombatTarget = obj5 is bool && (bool)obj5; } catch { } } if (!EvaluateCompanionRescueEligibility(val.IsDead(), val.IsTamed(), val.IsBoss(), val.IsPlayer(), flag, flag2, isDirectFollowTargetLocalPlayer, isOrderAnchorFollowTarget, hasCommittedCombatTarget, num, persistedOrder, commandActive, playerId)) { continue; } if (!component.IsOwner()) { component.ClaimOwnership(); } if (val2 != null && num == 0 && playerId != 0) { val2.Set(OwnerHash, playerId); val2.Set(OrderHash, 1, false); val2.Set(CommandActiveHash, 1, false); } if ((Object)(object)val4 != (Object)null && RuntimeBindings.ClearAnchorImmediateMethod != null) { try { RuntimeBindings.ClearAnchorImmediateMethod.Invoke(val4, null); } catch { } } component2.SetFollowTarget(((Component)jugador).gameObject); if (godShieldDict != null) { godShieldDict[((Object)val).GetInstanceID()] = godShieldUntil; } if (ShouldApplyEmergencyHealing(val.GetHealth(), val.GetMaxHealth(), out var healAmount)) { val.Heal(healAmount, true); } Vector3 val5 = ((Component)val).transform.position - corpsePos; float sqrMagnitude = ((Vector3)(ref val5)).sqrMagnitude; if (sqrMagnitude > 144f) { Vector3 val6 = Random.insideUnitSphere * 3.5f; val6.y = 0.2f; Vector3 val7 = corpsePos + val6; if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGroundHeight(val7, ref num2)) { val7.y = Mathf.Max(val7.y, num2 + 0.2f); } Rigidbody component3 = ((Component)val).GetComponent(); if ((Object)(object)component3 != (Object)null) { component3.velocity = Vector3.zero; component3.angularVelocity = Vector3.zero; } val.TeleportTo(val7, ((Component)jugador).transform.rotation, true); ((Component)val).transform.position = val7; if (val2 != null) { val2.SetPosition(val7); } } rescuedCount++; } if (rescuedCount <= 0) { yield break; } if ((Object)(object)MessageHud.instance != (Object)null) { string text = string.Format(ModLanguage.Text("✦ RESCATE SAGRADO DE ALTAIR ✦\n{0} compañero(s) protegido(s) con Escudo Divino (15s)"), rescuedCount); MessageHud.instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true); } string text2 = string.Format(ModLanguage.Text("Altair ha reagrupado y bendecido a {0} compañero(s) cerca de tu tumba."), rescuedCount); ((Character)jugador).Message((MessageType)1, text2, 0, (Sprite)null, false); if (RuntimeBindings.RavenAdviceMethod != null) { try { string text3 = ModLanguage.Text("Altair — Rescate Sagrado: Tus compañeros han sido reagrupados y bendecidos con un Escudo Divino de 15 segundos."); RuntimeBindings.RavenAdviceMethod.Invoke(null, new object[3] { jugador, "companion_rescue", text3 }); } catch { } } } } public static class ReanimationSync { private static bool s_installed = false; private static bool s_transpilerApplied = false; private static ManualLogSource s_log; private static PropertyInfo s_bloodMoonActiveProp; private static bool s_bloodMoonResolved = false; public static bool IsApplied => s_transpilerApplied; public static void SetLogger(ManualLogSource log) { s_log = log; } private static void LogDiagnostic(string message) { if (s_log != null) { s_log.LogInfo((object)message); } else { Debug.Log((object)message); } } private static void LogDiagnosticWarning(string message) { if (s_log != null) { s_log.LogWarning((object)message); } else { Debug.LogWarning((object)message); } } private static void LogDiagnosticError(string message) { if (s_log != null) { s_log.LogError((object)message); } else { Debug.LogError((object)message); } } private static bool IsBloodMoonActive() { if (!s_bloodMoonResolved) { s_bloodMoonResolved = true; try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { Type type = assembly.GetType("TameMate.BloodMoonManager"); if (type != null) { s_bloodMoonActiveProp = type.GetProperty("IsActive", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (s_bloodMoonActiveProp != null) { break; } } } } catch { } } if (s_bloodMoonActiveProp != null) { try { return (bool)s_bloodMoonActiveProp.GetValue(null, null); } catch { } } return false; } public static bool IsTestEnvironment() { return false; } public static float GetReanimationChanceForCharacter(Character c, bool isTamed) { return GetReanimationChance(isTamed); } public static float GetReanimationChance(bool isTamed) { bool isNight = false; try { isNight = (Object)(object)EnvMan.instance != (Object)null && EnvMan.IsNight(); } catch { } bool isBloodMoon = IsBloodMoonActive(); return GetReanimationChanceExplicit(isTamed, isNight, isBloodMoon); } public static float GetReanimationChanceExplicit(bool isTamed, bool isNight, bool isBloodMoon) { if (isTamed) { if (isBloodMoon) { if (!isNight) { return 0.03f; } return 0.04f; } if (!isNight) { return 0.01f; } return 0.02f; } if (isBloodMoon) { if (!isNight) { return 0.07f; } return 0.1f; } if (!isNight) { return 0.03f; } return 0.05f; } public static IEnumerable TryReanimateDefeated_Transpiler(IEnumerable instructions) { //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Expected O, but got Unknown List list = new List(instructions); int num = -1; for (int i = 0; i < list.Count; i++) { CodeInstruction val = list[i]; if (val.opcode == OpCodes.Call && val.operand is MethodInfo) { MethodInfo methodInfo = (MethodInfo)val.operand; if (methodInfo.DeclaringType == typeof(Random) && methodInfo.Name == "get_value") { num = i; break; } } } if (num == -1 || num + 1 >= list.Count) { string message = "[ReanimationSync] Transpiler FAILED: call UnityEngine.Random::get_value() not found in TryReanimateDefeated. Patch NOT applied."; LogDiagnosticError(message); throw new NotSupportedException(message); } CodeInstruction val2 = list[num + 1]; if (val2.opcode != OpCodes.Ldloc && val2.opcode != OpCodes.Ldloc_S && val2.opcode != OpCodes.Ldloc_0 && val2.opcode != OpCodes.Ldloc_1 && val2.opcode != OpCodes.Ldloc_2 && val2.opcode != OpCodes.Ldloc_3) { string message2 = string.Concat("[ReanimationSync] Transpiler FAILED: Instruction after Random::get_value() is not ldloc (found ", val2.opcode, "). Patch NOT applied."); LogDiagnosticError(message2); throw new NotSupportedException(message2); } MethodInfo methodInfo2 = AccessTools.Method(typeof(ReanimationSync), "GetReanimationChanceForCharacter", new Type[2] { typeof(Character), typeof(bool) }, (Type[])null); if (methodInfo2 == null) { methodInfo2 = AccessTools.Method(typeof(ReanimationSync), "GetReanimationChance", new Type[1] { typeof(bool) }, (Type[])null); } if (methodInfo2 == null) { string message3 = "[ReanimationSync] Transpiler FAILED: ReanimationSync.GetReanimationChanceForCharacter method not found."; LogDiagnosticError(message3); throw new NotSupportedException(message3); } val2.opcode = OpCodes.Ldarg_0; val2.operand = null; list.Insert(num + 2, new CodeInstruction(OpCodes.Ldarg_1, (object)null)); list.Insert(num + 3, new CodeInstruction(OpCodes.Call, (object)methodInfo2)); MethodInfo methodInfo3 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "AuthorizedReanimationTransfer", (Type[])null, (Type[])null); int num2 = 0; foreach (CodeInstruction item in list) { MethodInfo methodInfo4 = item.operand as MethodInfo; if (!(item.opcode != OpCodes.Call) && !(methodInfo4 == null) && !(methodInfo4.DeclaringType == null) && !(methodInfo4.DeclaringType.FullName != "TameMate.CompanionSaddlebags") && !(methodInfo4.Name != "TransferToReanimated")) { ParameterInfo[] parameters = methodInfo4.GetParameters(); if (methodInfo4.ReturnType != typeof(void) || parameters.Length != 2 || parameters[0].ParameterType != typeof(Character) || parameters[1].ParameterType != typeof(Character) || methodInfo3 == null) { throw new NotSupportedException("Unrecognized reanimation delivery call signature; adapter not installed."); } item.operand = methodInfo3; num2++; } } if (num2 != 1) { throw new NotSupportedException("Expected exactly one frozen reanimation transfer site; adapter not installed."); } s_transpilerApplied = true; LogDiagnostic("[ReanimationSync] Transpiler SUCCESS: Replaced probability threshold with exact 8-scenario table and targeted companion evaluation. Single RNG roll guaranteed."); return list; } public static void Install(Harmony harmony, Assembly coreAssembly) { //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Expected O, but got Unknown //IL_0128: 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_0135: 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_0147: Expected O, but got Unknown //IL_0147: Expected O, but got Unknown //IL_0147: Expected O, but got Unknown //IL_0147: Expected O, but got Unknown if (s_installed) { return; } Type type = coreAssembly.GetType("TameMate.UndeadSystem"); if (type == null) { LogDiagnosticError("[ReanimationSync] UndeadSystem type not found in core assembly."); return; } MethodInfo methodInfo = AccessTools.Method(type, "TryReanimateDefeated", new Type[4] { typeof(Character), typeof(bool), typeof(long), typeof(int) }, (Type[])null); if (methodInfo == null) { LogDiagnosticError("[ReanimationSync] TryReanimateDefeated method not found on UndeadSystem."); return; } MethodInfo methodInfo2 = AccessTools.Method(typeof(ReanimationSync), "TryReanimateDefeated_Transpiler", (Type[])null, (Type[])null); if (methodInfo2 == null) { LogDiagnosticError("[ReanimationSync] TryReanimateDefeated_Transpiler method not found."); return; } MethodInfo methodInfo3 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "BeginDeliveryReanimationScope", (Type[])null, (Type[])null); MethodInfo methodInfo4 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "CompleteDeliveryReanimationScope", (Type[])null, (Type[])null); MethodInfo methodInfo5 = AccessTools.Method(typeof(CompanionSaddlebagsSync), "EndDeliveryReanimationScope", (Type[])null, (Type[])null); if (methodInfo3 == null || methodInfo4 == null || methodInfo5 == null) { throw new NotSupportedException("Prior-delivery scope hooks unavailable; adapter not installed."); } harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo3), new HarmonyMethod(methodInfo4), new HarmonyMethod(methodInfo2), new HarmonyMethod(methodInfo5), (HarmonyMethod)null); try { CompanionSaddlebagsSync.InstallDefinitiveDeathAdapter(harmony, coreAssembly, methodInfo); } catch (Exception ex) { LogDiagnosticError("[A-01M.4] Definitive drops remain blocked: " + ex.Message); } s_installed = true; LogDiagnostic("[ReanimationSync] Successfully installed TryReanimateDefeated Transpiler."); try { Type type2 = AccessTools.TypeByName("TameMate.OceanHorn.RiderCollisionGuard0739"); if (type2 != null) { MethodInfo methodInfo6 = AccessTools.Method(type2, "Restore", (Type[])null, (Type[])null); if (methodInfo6 != null) { harmony.Patch((MethodBase)methodInfo6, new HarmonyMethod(AccessTools.Method(typeof(ReanimationSync), "RiderCollisionGuard_Restore_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); LogDiagnostic("[ReanimationSync] Successfully installed RiderCollisionGuard mount death crash protection."); } } } catch (Exception ex2) { LogDiagnosticWarning("[ReanimationSync] RiderCollisionGuard patch skipped: " + ex2.Message); } } public static bool RiderCollisionGuard_Restore_Prefix(MonoBehaviour __instance) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null) { return true; } try { FieldInfo fieldInfo = AccessTools.Field(((object)__instance).GetType(), "creature"); Character val = ((!(fieldInfo != null)) ? ((Character)null) : ((Character)fieldInfo.GetValue(__instance))); if ((Object)(object)val == (Object)null || val.IsDead() || !Object.op_Implicit((Object)(object)((Component)val).gameObject)) { FieldInfo fieldInfo2 = AccessTools.Field(((object)__instance).GetType(), "pairs"); if (fieldInfo2 != null && fieldInfo2.GetValue(__instance) is IList list) { list.Clear(); } FieldInfo fieldInfo3 = AccessTools.Field(((object)__instance).GetType(), "rider"); if (fieldInfo3 != null) { fieldInfo3.SetValue(__instance, null); } FieldInfo fieldInfo4 = AccessTools.Field(((object)__instance).GetType(), "probe"); if (fieldInfo4 != null) { object value = fieldInfo4.GetValue(__instance); if (value != null) { MethodInfo methodInfo = AccessTools.Method(value.GetType(), "SetActive", new Type[1] { typeof(bool) }, (Type[])null); if (methodInfo != null) { methodInfo.Invoke(value, new object[1] { false }); } } } return false; } } catch (Exception ex) { LogDiagnosticWarning("[ReanimationSync] RiderCollisionGuard safe restore fallback: " + ex.Message); } return true; } public static bool TryInstallServerDevcommandsBypass(Harmony harmonyInstance = null) { return false; } } public sealed class TamingStatusInfo { public Character Target; public Tameable Tameable; public string Name; public string Species; public string TierBadge; public int Stars; public float Distance; public float TamingProgress01; public int Tameness; public float TimeRemaining; public bool IsHungry; public bool IsAlerted; public bool IsSimulating; public string FedStatusText; public string SimulationStatusText; public int CompatibleFoodInChests; public string ChestFoodName; public float ChestFeedingRange; public bool ChestFeedingEnabled; } public static class RemoteTamingTracker { public static ConfigEntry TameInspectionRange; public static ConfigEntry ShowRemoteTamingHud; private static float s_lastChestScanTime; private static int s_cachedFoodCount; private static string s_cachedFoodName = ""; private static int s_lastScannedCreatureId; private static float s_cachedChestRange; private static bool s_cachedFeedingEnabled; private static bool s_cachedOnlyFood; private static MethodInfo s_getTierBadgeMethod; private static Func s_getTameness; private static Func s_getRemainingTime; public static void Init(Harmony harmony, ConfigFile config) { //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown if (config != null) { TameInspectionRange = config.Bind("RemoteTaming", "InspectionRange", 30f, "Distancia máxima en metros para consultar el porcentaje y estado de domesticación apuntando a la criatura (se sincroniza con el alcance de cofres)."); ShowRemoteTamingHud = config.Bind("RemoteTaming", "ShowRemoteTamingHud", true, "Muestra el estado detallado de domesticación, hambre y cofres en el punto de mira."); } if (harmony != null) { try { MethodInfo methodInfo = AccessTools.Method(typeof(Hud), "UpdateCrosshair", new Type[2] { typeof(Player), typeof(float) }, (Type[])null); if (methodInfo != null) { HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(RemoteTamingTracker), "Hud_UpdateCrosshair_Postfix", (Type[])null, (Type[])null)); harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate] RemoteTamingTracker crosshair patch warning: " + ex.Message)); } } try { ChestFoodQuery.Initialize(); Type type = Type.GetType("TameMate.SupremeTierEngine, TameMate"); if (type != null) { s_getTierBadgeMethod = type.GetMethod("GetTierBadge", new Type[1] { typeof(Character) }); } MethodInfo methodInfo2 = AccessTools.Method(typeof(Tameable), "GetTameness", (Type[])null, (Type[])null); if (methodInfo2 != null) { s_getTameness = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo2); } MethodInfo methodInfo3 = AccessTools.Method(typeof(Tameable), "GetRemainingTime", (Type[])null, (Type[])null); if (methodInfo3 != null) { s_getRemainingTime = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo3); } } catch { } } public static float GetMaxInspectionRange() { if (TameInspectionRange != null && TameInspectionRange.Value > 5f) { return TameInspectionRange.Value; } return 30f; } public static void Hud_UpdateCrosshair_Postfix(Hud __instance, Player player, float bowDrawPercentage) { UpdateRemoteHover(__instance, player); } public static void UpdateRemoteHover(Hud hud, Player player) { //IL_0082: 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_00fa: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)hud == (Object)null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || (ShowRemoteTamingHud != null && !ShowRemoteTamingHud.Value) || (Object)(object)((Humanoid)player).GetHoverObject() != (Object)null) { return; } Character hoverCreature = player.GetHoverCreature(); if ((Object)(object)hoverCreature == (Object)null || hoverCreature.IsPlayer()) { return; } Tameable component = ((Component)hoverCreature).GetComponent(); if ((Object)(object)component == (Object)null || hoverCreature.IsTamed()) { return; } ContextualAdviceEngine.OnHoverTameable(player, hoverCreature); float num = Vector3.Distance(((Component)player).transform.position, ((Component)hoverCreature).transform.position); float maxInspectionRange = GetMaxInspectionRange(); if (num > maxInspectionRange) { return; } TamingStatusInfo tamingStatusInfo = InspectCreature(hoverCreature, component, player, num); if (tamingStatusInfo == null) { return; } string text = FormatRemoteHoverText(tamingStatusInfo); if (!string.IsNullOrEmpty(text)) { ((TMP_Text)hud.m_hoverName).text = text; if ((Object)(object)hud.m_crosshair != (Object)null) { ((Graphic)hud.m_crosshair).color = new Color(0.2f, 0.9f, 1f, 0.95f); } } } public static TamingStatusInfo InspectCreature(Character c, Tameable t, Player p, float dist) { if ((Object)(object)c == (Object)null || (Object)(object)t == (Object)null) { return null; } int num = ((s_getTameness != null) ? s_getTameness(t) : 0); float tamingProgress = Mathf.Clamp01((float)num / 100f); float timeRemaining = ((s_getRemainingTime != null) ? s_getRemainingTime(t) : 0f); bool flag = t.IsHungry(); BaseAI component = ((Component)c).GetComponent(); bool flag2 = (Object)(object)component != (Object)null && component.IsAlerted(); ZNetView component2 = ((Component)c).GetComponent(); bool flag3 = (Object)(object)component2 != (Object)null && component2.IsValid(); bool isSimulating = flag3 && !flag2 && !flag; ScanChestsForFood(c, out var totalCount, out var sampleName); int stars = Mathf.Max(0, c.GetLevel() - 1); string tierBadge = GetTierBadge(c); string fedStatusText = ((!flag) ? "Saciado (comiendo)" : "Hambriento"); string simulationStatusText = ((!flag3) ? (ModLanguage.IsEnglish ? "Waiting for creature state" : "Esperando estado de la criatura") : (flag2 ? "Pausado (Asustado / En alerta)" : ((!flag) ? "Activo (Domesticándose...)" : "Pausado (Esperando alimento)"))); TamingStatusInfo tamingStatusInfo = new TamingStatusInfo(); tamingStatusInfo.Target = c; tamingStatusInfo.Tameable = t; tamingStatusInfo.Name = c.GetHoverName(); tamingStatusInfo.Species = c.m_name; tamingStatusInfo.TierBadge = tierBadge; tamingStatusInfo.Stars = stars; tamingStatusInfo.Distance = dist; tamingStatusInfo.TamingProgress01 = tamingProgress; tamingStatusInfo.Tameness = num; tamingStatusInfo.TimeRemaining = timeRemaining; tamingStatusInfo.IsHungry = flag; tamingStatusInfo.IsAlerted = flag2; tamingStatusInfo.IsSimulating = isSimulating; tamingStatusInfo.FedStatusText = fedStatusText; tamingStatusInfo.SimulationStatusText = simulationStatusText; tamingStatusInfo.CompatibleFoodInChests = totalCount; tamingStatusInfo.ChestFoodName = (string.IsNullOrEmpty(sampleName) ? "Sin comida en cofres" : sampleName); tamingStatusInfo.ChestFeedingRange = ChestFoodQuery.Range; tamingStatusInfo.ChestFeedingEnabled = ChestFoodQuery.Enabled(c); return tamingStatusInfo; } private static void ScanChestsForFood(Character c, out int totalCount, out string sampleName) { totalCount = 0; sampleName = ""; if ((Object)(object)c == (Object)null) { return; } int instanceID = ((Object)c).GetInstanceID(); float range = ChestFoodQuery.Range; bool flag = ChestFoodQuery.Enabled(c); bool onlyFoodChests = ChestFoodQuery.OnlyFoodChests; if (instanceID == s_lastScannedCreatureId && Time.time - s_lastChestScanTime < 2f && range == s_cachedChestRange && flag == s_cachedFeedingEnabled && onlyFoodChests == s_cachedOnlyFood) { totalCount = s_cachedFoodCount; sampleName = s_cachedFoodName; return; } s_lastScannedCreatureId = instanceID; s_lastChestScanTime = Time.time; s_cachedChestRange = range; s_cachedFeedingEnabled = flag; s_cachedOnlyFood = onlyFoodChests; totalCount = ChestFoodQuery.Find(c, firstOnly: false, out var _, out var _, out sampleName); if (!string.IsNullOrEmpty(sampleName) && Localization.instance != null) { sampleName = Localization.instance.Localize(sampleName); } if (totalCount > 0 && !string.IsNullOrEmpty(sampleName)) { sampleName = sampleName + " (" + totalCount + ")"; } s_cachedFoodCount = totalCount; s_cachedFoodName = sampleName; } private static string GetTierBadge(Character c) { try { if (s_getTierBadgeMethod != null) { return (string)s_getTierBadgeMethod.Invoke(null, new object[1] { c }); } } catch { } return ""; } public static string FormatRemoteHoverText(TamingStatusInfo info) { if (info == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("").Append(info.Name).Append(""); if (info.Stars > 0) { stringBuilder.Append(" "); for (int i = 0; i < info.Stars; i++) { stringBuilder.Append("★"); } stringBuilder.Append(""); } if (!string.IsNullOrEmpty(info.TierBadge)) { stringBuilder.Append(" ").Append(info.TierBadge); } stringBuilder.Append(" (").Append(info.Distance.ToString("F1")).Append("m)\n"); int num = 16; int num2 = Mathf.RoundToInt(info.TamingProgress01 * (float)num); string value = new string('█', num2) + new string('░', Mathf.Max(0, num - num2)); string value2 = ((info.Tameness >= 80) ? "#00FF7F" : ((info.Tameness >= 40) ? "#00E5FF" : "#FFD700")); stringBuilder.Append("Doma: [") .Append(value) .Append("] ") .Append(info.Tameness) .Append("%"); if (info.TimeRemaining > 0f && info.IsSimulating) { int value3 = Mathf.FloorToInt(info.TimeRemaining / 60f); int value4 = Mathf.FloorToInt(info.TimeRemaining % 60f); stringBuilder.Append(" (~").Append(value3).Append("m ") .Append(value4) .Append("s)"); } stringBuilder.Append("\n"); stringBuilder.Append("• Alimentación: ").Append(info.FedStatusText).Append("\n"); stringBuilder.Append("• Simulación: ").Append(info.SimulationStatusText).Append("\n"); if (!info.ChestFeedingEnabled) { stringBuilder.Append(ModLanguage.IsEnglish ? "• Corral chests: disabled in settings" : "• Cofres de corral: desactivados en configuración"); } else if (info.CompatibleFoodInChests > 0) { stringBuilder.Append("• Cofres de corral: ").Append(info.ChestFoodName).Append(" disponibles"); } else { stringBuilder.Append(ModLanguage.IsEnglish ? "• Corral chests: No compatible food within " : "• Cofres de corral: Sin alimento compatible en ").Append(info.ChestFeedingRange.ToString("0.#")).Append(" m"); } return stringBuilder.ToString(); } public static List ScanLocalTamingCreatures(float radius) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) List list = new List(); Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return list; } Vector3 position = ((Component)localPlayer).transform.position; List allCharacters = Character.GetAllCharacters(); if (allCharacters == null) { return list; } for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if ((Object)(object)val == (Object)null || val.IsPlayer() || val.IsTamed() || val.IsDead()) { continue; } Tameable component = ((Component)val).GetComponent(); if ((Object)(object)component == (Object)null) { continue; } float num = Vector3.Distance(position, ((Component)val).transform.position); if (num <= radius) { TamingStatusInfo tamingStatusInfo = InspectCreature(val, component, localPlayer, num); if (tamingStatusInfo != null) { list.Add(tamingStatusInfo); } } } list.Sort((TamingStatusInfo a, TamingStatusInfo b) => a.Distance.CompareTo(b.Distance)); return list; } } internal interface IRitualLiveTarget : IRitualTransactionWriter, IZdoExtendedPropertyReader, IZdoPropertyReader { long ActualWorldUid { get; } int ActualPrefabHash { get; } long ActualOwnerId { get; } bool HasAuthority { get; } bool IsAlive { get; } float EffectiveMaxHealth { get; } void RefreshDerivedState(Action checkpoint); } internal sealed class RitualExecutionContext { internal const string TestProfile = "Valheim Supreme - Test 0752"; internal bool DiagnosticBuild; internal bool ExplicitAuthorization; internal string ProfileName; internal string FixtureGuid; internal string FixtureNonce; internal string RequestingPlayerId; internal long WorldUid; internal long AuthorizedWorldUid; internal int PrefabHash; internal DateTime AuthorizationExpiresUtc; internal ZdoInspectionScope Scope; internal IEnumerable WorldReaders; internal string ScopeEvidence; internal string CensusSnapshotHash; internal int CensusTotalZdoCount; internal Func SessionStillValid; internal static readonly int FixtureKey = StringExtensionMethods.GetStableHashCode("tm_ritual_lab_fixture"); internal static readonly int FixtureWorldKey = StringExtensionMethods.GetStableHashCode("tm_ritual_lab_world"); internal static readonly int FixtureNonceKey = StringExtensionMethods.GetStableHashCode("tm_ritual_lab_nonce"); internal bool Validate(IRitualLiveTarget target, out string reason) { reason = null; if (!DiagnosticBuild) { reason = "Compilación sin autorización diagnóstica de ejecución."; } else if (!string.Equals(ProfileName, "Valheim Supreme - Test 0752", StringComparison.Ordinal)) { reason = "Perfil de producción/no autorizado."; } else if (!ExplicitAuthorization || WorldUid == 0 || AuthorizedWorldUid != WorldUid || DateTime.UtcNow > AuthorizationExpiresUtc) { reason = "Falta autorización explícita vigente del mundo de pruebas."; } else if (SessionStillValid == null || !SessionStillValid()) { reason = "La sesión autorizada cambió."; } else if (target == null || !target.IsAlive || !target.IsTamed || target.IsBoss) { reason = "Solo se admite un compañero de laboratorio vivo, domesticado y no jefe."; } else if (!target.HasAuthority) { reason = "Autoridad de red ausente; no se solicita ClaimOwnership."; } else if (target.ActualWorldUid != WorldUid || target.ActualPrefabHash != PrefabHash || PrefabHash == 0) { reason = "WorldUid/PrefabHash reales no coinciden con la autorización."; } else if (string.IsNullOrEmpty(RequestingPlayerId) || target.ActualOwnerId <= 0 || target.ActualOwnerId.ToString(CultureInfo.InvariantCulture) != RequestingPlayerId) { reason = "Propietario nativo (tm_owner long) ajeno o ausente."; } else if (!CataclysmicStateReader.IsValidCompanionGuid(FixtureGuid) || target.GetString(CataclysmicStateReader.CompanionGuidKey) != FixtureGuid || target.GetLong(CataclysmicStateReader.CompanionWorldUidKey, 0L) != WorldUid || target.GetInt(CataclysmicStateReader.CompanionPrefabHashKey) != PrefabHash) { reason = "Identidad persistente ausente o contradictoria; no se asigna GUID durante el ritual."; } else if (target.GetString(FixtureKey) != FixtureGuid || target.GetLong(FixtureWorldKey, 0L) != WorldUid || !CataclysmicStateReader.IsValidCompanionGuid(FixtureNonce) || target.GetString(FixtureNonceKey) != FixtureNonce) { reason = "Falta la marca exclusiva de criatura sintética de armonización."; } if (reason != null) { return false; } CompanionIdentityResolution companionIdentityResolution = CataclysmicStateReader.ResolveCompanionIdentity(FixtureGuid, WorldUid, PrefabHash, WorldReaders, Scope); if (!companionIdentityResolution.IsGlobalUniquenessProven || !companionIdentityResolution.IsUnambiguousAndSafe || !object.ReferenceEquals(companionIdentityResolution.MatchedReader, target)) { reason = "Unicidad global no demostrada: " + (companionIdentityResolution.FailureReason ?? ScopeEvidence); return false; } if (!string.IsNullOrEmpty(CensusSnapshotHash)) { CompanionZdoSnapshot companionZdoSnapshot = CompanionZdoSnapshot.CreateFromReader(target, WorldUid, 0L, 0u, PrefabHash); if (companionZdoSnapshot == null || !string.Equals(companionZdoSnapshot.ComputeSessionIndependentContentSha256(), CensusSnapshotHash, StringComparison.Ordinal)) { reason = "El estado del compañero cambió después del censo de laboratorio; lease invalidada."; return false; } } return true; } } internal sealed class RitualGuardedWriter : IRitualTransactionWriter, IZdoExtendedPropertyReader, IZdoPropertyReader { private readonly IRitualLiveTarget target; private readonly RitualExecutionContext context; private bool active; private readonly HashSet ints = new HashSet { CataclysmicStateReader.SavedTierKey, CataclysmicStateReader.TierOverrideKey, CataclysmicStateReader.IsCataclysmicKey, CataclysmicStateReader.RitualTxStateKey, CataclysmicStateReader.HarmonizedFromLegacyKey, CataclysmicStateReader.HarmonizedTargetTierKey }; private readonly HashSet strings = new HashSet { CataclysmicStateReader.RitualTxIdKey, CataclysmicStateReader.HarmonizedTimestampKey }; internal string TransactionId { get; private set; } internal float EffectiveMaxHealth => target.EffectiveMaxHealth; public bool IsBoss => target.IsBoss; public bool IsTamed => target.IsTamed; public float NativeBaseHealth => target.NativeBaseHealth; public Action MidWriteFaultInjector { get { return null; } set { throw new InvalidOperationException("No live fault injection."); } } internal RitualGuardedWriter(IRitualLiveTarget subject, RitualExecutionContext permit, string transactionId = null) { target = subject; context = permit; TransactionId = transactionId; } internal void Begin() { active = true; Checkpoint(); } internal void End() { active = false; } internal void Checkpoint() { string reason = null; if (!active || !context.Validate(target, out reason)) { throw new InvalidOperationException(active ? reason : "Lease de ritual cerrada."); } } internal void RefreshDerivedState() { Checkpoint(); target.RefreshDerivedState(Checkpoint); Checkpoint(); } internal void RestoreOriginalLineage(CompanionZdoSnapshot origin) { if (origin == null || !origin.VerifyIntegrity() || origin.WorldUid != context.WorldUid || origin.CompanionGuid != context.FixtureGuid || origin.PrefabHash != context.PrefabHash) { throw new InvalidOperationException("Respaldo Legacy contradictorio."); } int[] array = new int[5] { CataclysmicStateReader.SavedTierKey, CataclysmicStateReader.TierOverrideKey, CataclysmicStateReader.IsCataclysmicKey, CataclysmicStateReader.HarmonizedFromLegacyKey, CataclysmicStateReader.HarmonizedTargetTierKey }; foreach (int num in array) { if (origin.IntValues.TryGetValue(num, out var value)) { SetInt(num, value); continue; } if (origin.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('I', num))) { RemoveKey(num); continue; } throw new InvalidOperationException("Respaldo incompleto para la clave de linaje."); } foreach (int @string in strings) { if (origin.StringValues.TryGetValue(@string, out var value2)) { SetString(@string, value2); continue; } if (origin.AbsentKeys.Contains(CompanionZdoSnapshot.FormatAbsentToken('S', @string))) { RemoveKey(@string); continue; } throw new InvalidOperationException("Respaldo incompleto para la clave de linaje."); } SetInt(CataclysmicStateReader.RitualTxStateKey, 0); } public void SetInt(int k, int v) { Checkpoint(); if (!ints.Contains(k)) { throw new InvalidOperationException("Clave int fuera de allowlist."); } target.SetInt(k, v); } public void SetString(int k, string v) { Checkpoint(); if (!strings.Contains(k)) { throw new InvalidOperationException("Clave string fuera de allowlist."); } target.SetString(k, v); } public bool RemoveKey(int k) { Checkpoint(); if (!ints.Contains(k) && !strings.Contains(k)) { throw new InvalidOperationException("Borrado fuera de allowlist."); } return target.RemoveKey(k); } public void SetFloat(int k, float v) { throw new InvalidOperationException("Derivados solo mediante recálculo nativo."); } public void SetLong(int k, long v) { throw new InvalidOperationException("Identidad/propietario inmutables."); } public void SetByteArray(int k, byte[] v) { throw new InvalidOperationException("Inventario protegido."); } public void SetVec3(int k, Vector3 v) { throw new InvalidOperationException("Posición protegida."); } public int GetInt(int k, int d = 0) { return target.GetInt(k, d); } public string GetString(int k, string d = "") { return target.GetString(k, d); } public float GetFloat(int k, float d = 0f) { return target.GetFloat(k, d); } public bool GetBool(int k, bool d = false) { return target.GetBool(k, d); } public long GetLong(int k, long d = 0L) { return target.GetLong(k, d); } public bool TryGetInt(int k, out int v) { return target.TryGetInt(k, out v); } public bool TryGetString(int k, out string v) { return target.TryGetString(k, out v); } public bool TryGetFloat(int k, out float v) { return target.TryGetFloat(k, out v); } public bool TryGetLong(int k, out long v) { return target.TryGetLong(k, out v); } public bool TryGetByteArray(int k, out byte[] v) { return target.TryGetByteArray(k, out v); } public bool TryGetVec3(int k, out Vector3 v) { return target.TryGetVec3(k, out v); } } internal enum RitualOperation { Harmonize, Rollback, Recovery } internal sealed class RitualLiveSession { private readonly IRitualLiveTarget target; private readonly RitualExecutionContext context; private PendingRitualTicket pending; private RitualOperation operation; private bool quarantined; internal RitualLiveSession(IRitualLiveTarget subject, RitualExecutionContext permit) { target = subject; context = permit; } private CompanionZdoSnapshot Snapshot() { return CompanionZdoSnapshot.CreateFromReader(target, context.WorldUid, 0L, 0u, context.PrefabHash); } private bool Preconditions(RitualOperation action, out string reason) { if (!context.Validate(target, out reason)) { return false; } if (quarantined && action != RitualOperation.Recovery) { reason = "Sesión en cuarentena; solo diagnóstico/recuperación explícita."; return false; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify((IZdoPropertyReader)target); if (action == RitualOperation.Harmonize && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguous && cataclysmicClassification != CataclysmicClassification.LegacyAmbiguousUndead) { reason = "La armonización solo acepta LegacyAmbiguous o LegacyAmbiguousUndead."; return false; } if (action == RitualOperation.Harmonize && target.GetInt(CataclysmicStateReader.RitualTxStateKey) != 0) { reason = "Existe una transacción pendiente en el ZDO; bloquear y revisar recuperación."; return false; } if (action == RitualOperation.Rollback && cataclysmicClassification != CataclysmicClassification.DecoupledCataclysmic) { reason = "Rollback requiere una armonización existente."; return false; } CompanionZdoSnapshot companionZdoSnapshot = CompanionPersistentBackup.LoadLegacyOriginBackup(context.WorldUid, context.FixtureGuid, context.PrefabHash, out reason); if (companionZdoSnapshot == null || !companionZdoSnapshot.VerifyIntegrity()) { reason = "Falta respaldo Legacy original íntegro: " + reason; return false; } if (!companionZdoSnapshot.IntValues.TryGetValue(CataclysmicStateReader.SavedTierKey, out var value) || value != 9) { reason = "El respaldo original no acredita Tier 9 Legacy."; return false; } string journalFilePath = CompanionPersistentBackup.GetJournalFilePath(context.WorldUid, context.FixtureGuid); if (File.Exists(journalFilePath)) { RitualTransactionJournal ritualTransactionJournal = CompanionPersistentBackup.LoadJournal(context.WorldUid, context.FixtureGuid, out reason); if (ritualTransactionJournal == null || !ritualTransactionJournal.VerifyIntegrity() || ritualTransactionJournal.PrefabHash != context.PrefabHash) { reason = "Journal corrupto o contradictorio; bloqueado sin reemplazarlo."; return false; } switch (action) { case RitualOperation.Harmonize: reason = "Ya existe un journal; revisar persistencia/recuperación antes de otra armonización."; return false; case RitualOperation.Rollback: if (ritualTransactionJournal.State != RitualJournalState.CommittedInMemory) { reason = "Journal interrumpido o no confirmado para rollback; requiere revisión de recuperación."; return false; } break; } } else if (action != RitualOperation.Harmonize) { reason = "No existe journal de transacción para revertir/recuperar."; return false; } reason = null; return true; } internal bool Prepare(RitualOperation action, int tier, out string ticketId, out string reason) { ticketId = null; pending = null; if (!Preconditions(action, out reason)) { return false; } if (action == RitualOperation.Harmonize && (tier < 1 || tier > 10 || tier == 9)) { reason = "Tier biológico inválido (1..8 o 10)."; return false; } PendingRitualTicket pendingRitualTicket = CataclysmicHarmonizationRitual.PrepareHarmonizationTicket(target, (action == RitualOperation.Harmonize) ? tier : 9, context.RequestingPlayerId, context.WorldUid, context.PrefabHash, target.NativeBaseHealth, target.HasAuthority); if (action == RitualOperation.Harmonize && (pendingRitualTicket == null || !pendingRitualTicket.SimulationReport.IsValid)) { reason = ((pendingRitualTicket == null) ? "Prepare no disponible." : pendingRitualTicket.SimulationReport.ErrorMessage); return false; } pending = pendingRitualTicket; operation = action; ticketId = pendingRitualTicket.TicketId; reason = "Preparado sin escrituras. Confirmar explícitamente el ticket y tier antes de 60 s."; return true; } internal bool Confirm(string ticketId, int confirmedTier, string playerId, bool explicitConfirmation, out string reason) { PendingRitualTicket pendingRitualTicket = pending; pending = null; if (pendingRitualTicket == null || !explicitConfirmation || pendingRitualTicket.TicketId != ticketId || pendingRitualTicket.RequestingPlayerId != playerId || !pendingRitualTicket.IsValidAndActive(DateTime.UtcNow) || pendingRitualTicket.TargetBiologicalTier != confirmedTier) { reason = "Confirmación inválida, expirada, reutilizada o de otro jugador/tier."; return false; } if (!Preconditions(operation, out reason)) { return false; } if (Snapshot().ComputeSessionIndependentContentSha256() != pendingRitualTicket.PreStateSha256) { reason = "El estado original cambió desde Prepare; se requiere otro ticket."; return false; } CataclysmicClassification cataclysmicClassification = CataclysmicStateReader.Classify((IZdoPropertyReader)target); if (operation == RitualOperation.Recovery && target.GetInt(CataclysmicStateReader.RitualTxStateKey) == 0 && (cataclysmicClassification == CataclysmicClassification.LegacyAmbiguous || cataclysmicClassification == CataclysmicClassification.LegacyAmbiguousUndead)) { pendingRitualTicket.IsConsumed = true; reason = "Legacy intacto: recuperación innecesaria, cero escrituras. Se conserva journal; guardado no acreditado."; return true; } RitualGuardedWriter ritualGuardedWriter = new RitualGuardedWriter(target, context, pendingRitualTicket.TicketId); try { ritualGuardedWriter.Begin(); bool flag; if (operation == RitualOperation.Harmonize) { flag = CataclysmicHarmonizationRitual.BackupAndCommit(ritualGuardedWriter, pendingRitualTicket, confirmedTier, playerId, context.WorldReaders, context.Scope, hasWriteAuthority: true, out reason); } else { pendingRitualTicket.IsConsumed = true; flag = CataclysmicHarmonizationRitual.RollbackLineageOnly(ritualGuardedWriter, context.WorldUid, context.PrefabHash, context.WorldReaders, context.Scope, playerId, hasWriteAuthority: true, out reason); } if (!flag) { Quarantine(reason); return false; } if (operation == RitualOperation.Recovery) { quarantined = false; } reason = string.Concat("Transacción controlada verificada EN MEMORIA (", operation, "). Guardado del mundo NO confirmado. Identidad, linaje y datos protegidos comprobados; revisar journal y persistencia antes de continuar."); return true; } catch (Exception ex) { reason = "Operación interrumpida: " + ex.Message + ". Sin restauración automática; revisar journal/respaldo."; Quarantine(reason); return false; } finally { ritualGuardedWriter.End(); } } private void Quarantine(string reason) { quarantined = true; string error; RitualTransactionJournal ritualTransactionJournal = CompanionPersistentBackup.LoadJournal(context.WorldUid, context.FixtureGuid, out error); if (ritualTransactionJournal != null) { ritualTransactionJournal.State = RitualJournalState.QuarantinedInterrupted; CompanionPersistentBackup.SaveJournal(ritualTransactionJournal, out var _, out error); } } internal string RecoveryStatus() { if (!context.Validate(target, out var reason)) { return "BLOQUEADO: " + reason; } RitualTransactionJournal ritualTransactionJournal = CompanionPersistentBackup.LoadJournal(context.WorldUid, context.FixtureGuid, out reason); if (ritualTransactionJournal != null) { return string.Concat("Journal=", ritualTransactionJournal.State, "; guardado del mundo NO confirmado. Inspección sin restauración automática."); } return "Journal ausente/inválido: " + reason; } } internal sealed class RitualNativeWriteScope : IDisposable { private static RitualNativeWriteScope current; private readonly Harmony harmony; private readonly ZDO subject; private readonly Action checkpoint; private string violation; private readonly Dictionary valueTypes = new Dictionary(); internal RitualNativeWriteScope(ZDO target, Action validate) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown if (current != null) { throw new InvalidOperationException("Recálculo de ritual reentrante."); } subject = target; checkpoint = validate; harmony = new Harmony("mitsu.tamemate.ritual.nativewrite." + Guid.NewGuid().ToString("N")); current = this; try { int num = 0; MethodInfo[] methods = typeof(ZDO).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length != 0 && !(parameters[0].ParameterType != typeof(int)) && (!(methodInfo.Name != "Set") || methodInfo.Name.StartsWith("Remove", StringComparison.Ordinal))) { valueTypes[methodInfo] = ((methodInfo.Name == "Set" && parameters.Length == 2) ? parameters[1].ParameterType : null); Harmony obj = harmony; HarmonyMethod val = new HarmonyMethod(typeof(RitualNativeWriteScope), "BeforeWrite", (Type[])null); val.priority = 800; obj.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); num++; } } if (num == 0) { throw new MissingMethodException("No se pudieron vigilar las escrituras nativas ZDO."); } } catch { Dispose(); throw; } } private static void BeforeWrite(ZDO __instance, int __0, MethodBase __originalMethod) { RitualNativeWriteScope ritualNativeWriteScope = current; if (ritualNativeWriteScope != null && object.ReferenceEquals(ritualNativeWriteScope.subject, __instance)) { try { ritualNativeWriteScope.checkpoint(); } catch (Exception ex) { ritualNativeWriteScope.violation = ex.Message; throw; } if (!ritualNativeWriteScope.valueTypes.TryGetValue(__originalMethod, out var value) || ((!(value == typeof(int)) || (__0 != CataclysmicStateReader.TierHpInitKey && __0 != CataclysmicStateReader.SpecialProfileKey)) && (!(value == typeof(float)) || (__0 != CataclysmicStateReader.MaxHealthKey && __0 != CataclysmicStateReader.HealthKey)))) { ritualNativeWriteScope.violation = "El recálculo intentó modificar una clave fuera del subconjunto derivado: " + __0; throw new InvalidOperationException(ritualNativeWriteScope.violation); } } } public void Dispose() { try { harmony.UnpatchSelf(); } finally { if (object.ReferenceEquals(current, this)) { current = null; } } if (violation != null) { throw new InvalidOperationException(violation); } } } internal sealed class RitualValheimTarget : IRitualLiveTarget, IRitualTransactionWriter, IZdoExtendedPropertyReader, IZdoPropertyReader { private readonly Character character; private readonly ZNetView view; private readonly ZDO zdo; private readonly ValheimZdoReader reader; private static Func healthMultiplier; public long ActualWorldUid { get { if (!((Object)(object)ZNet.instance == (Object)null)) { return ZNet.instance.GetWorldUID(); } return 0L; } } public int ActualPrefabHash { get { if (zdo != null) { return zdo.GetPrefab(); } return 0; } } public long ActualOwnerId => reader.GetLong(CataclysmicStateReader.OwnerIdKey, 0L); public bool HasAuthority { get { if ((Object)(object)view != (Object)null && view.IsValid() && view.GetZDO() == zdo) { return view.IsOwner(); } return false; } } public bool IsAlive { get { if ((Object)(object)character != (Object)null && zdo != null && !character.IsPlayer()) { return !character.IsDead(); } return false; } } public bool IsBoss { get { if (!((Object)(object)character == (Object)null) && !character.IsBoss()) { return reader.GetBool(StringExtensionMethods.GetStableHashCode("is_boss")); } return true; } } public bool IsTamed { get { if ((Object)(object)character != (Object)null && character.IsTamed()) { return reader.GetBool(CataclysmicStateReader.TamedBoolKey); } return false; } } public float NativeBaseHealth { get { if (!((Object)(object)character == (Object)null)) { return character.GetMaxHealthBase(); } return 0f; } } public float EffectiveMaxHealth { get { if (!((Object)(object)character == (Object)null)) { return character.GetMaxHealth(); } return 0f; } } internal ZDO IdentityHandle => zdo; internal Character Subject => character; public Action MidWriteFaultInjector { get { return null; } set { throw new InvalidOperationException(); } } internal RitualValheimTarget(Character c) { character = c; view = (((Object)(object)c == (Object)null) ? null : ((Component)c).GetComponent()); zdo = (((Object)(object)view != (Object)null && view.IsValid()) ? view.GetZDO() : null); reader = new ValheimZdoReader(zdo); } public void RefreshDerivedState(Action checkpoint) { if (!HasAuthority) { throw new InvalidOperationException("Autoridad perdida antes del recálculo."); } if (healthMultiplier == null) { Type type = Type.GetType("TameMate.SupremeTierEngine, TameMate", throwOnError: true); MethodInfo method = type.GetMethod("GetTierHealthMultiplier", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Character) }, null); if (method == null || method.ReturnType != typeof(float)) { throw new MissingMethodException("GetTierHealthMultiplier(Character)"); } healthMultiplier = (Func)Delegate.CreateDelegate(typeof(Func), method); } float num = Mathf.Clamp01(character.GetHealth() / Mathf.Max(1f, character.GetMaxHealth())); using (new RitualNativeWriteScope(zdo, checkpoint)) { CataclysmicHudFormatter.RefreshCompanionLiveState(character); float num2 = healthMultiplier(character); if (float.IsNaN(num2) || float.IsInfinity(num2) || num2 <= 0f) { throw new InvalidOperationException("Multiplicador nativo inválido."); } if (num2 <= 1.001f) { checkpoint(); zdo.Set(CataclysmicStateReader.TierHpInitKey, 1, false); checkpoint(); zdo.Set(CataclysmicStateReader.SpecialProfileKey, 0, false); checkpoint(); character.SetMaxHealth(NativeBaseHealth * (float)character.GetLevel() * num2); checkpoint(); character.SetHealth(Mathf.Clamp(character.GetMaxHealth() * num, 1f, character.GetMaxHealth())); } } if (!HasAuthority) { throw new InvalidOperationException("Autoridad perdida durante el recálculo."); } if (character.GetMaxHealth() <= 0f || float.IsNaN(character.GetMaxHealth())) { throw new InvalidOperationException("Recálculo inválido."); } } public void SetInt(int k, int v) { zdo.Set(k, v, false); } public void SetString(int k, string v) { zdo.Set(k, v); } public void SetFloat(int k, float v) { throw new InvalidOperationException(); } public void SetLong(int k, long v) { throw new InvalidOperationException(); } public void SetByteArray(int k, byte[] v) { throw new InvalidOperationException(); } public void SetVec3(int k, Vector3 v) { throw new InvalidOperationException(); } public bool RemoveKey(int k) { if (k == CataclysmicStateReader.RitualTxIdKey || k == CataclysmicStateReader.HarmonizedTimestampKey) { zdo.RemoveString(k); } else { zdo.RemoveInt(k); } return true; } public int GetInt(int k, int d = 0) { return reader.GetInt(k, d); } public string GetString(int k, string d = "") { return reader.GetString(k, d); } public float GetFloat(int k, float d = 0f) { return reader.GetFloat(k, d); } public bool GetBool(int k, bool d = false) { return reader.GetBool(k, d); } public long GetLong(int k, long d = 0L) { return reader.GetLong(k, d); } public bool TryGetInt(int k, out int v) { return reader.TryGetInt(k, out v); } public bool TryGetString(int k, out string v) { return reader.TryGetString(k, out v); } public bool TryGetFloat(int k, out float v) { return reader.TryGetFloat(k, out v); } public bool TryGetLong(int k, out long v) { return reader.TryGetLong(k, out v); } public bool TryGetByteArray(int k, out byte[] v) { return reader.TryGetByteArray(k, out v); } public bool TryGetVec3(int k, out Vector3 v) { return reader.TryGetVec3(k, out v); } } internal static class RitualValheimIntegration { private static RitualLiveSession session; private static Character authorizedTarget; private static long authorizedWorld; private static long authorizedPlayer; private static DateTime expires; private static readonly FieldInfo loadedZdosField = typeof(ZDOMan).GetField("m_objectsByID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static bool DiagnosticExecutionBuild => false; private static string ProfileName() { Type type = Type.GetType("BepInEx.Paths, BepInEx"); PropertyInfo propertyInfo = ((type == null) ? null : type.GetProperty("ConfigPath")); string configPath = ((propertyInfo == null) ? null : (propertyInfo.GetValue(null, null) as string)); if (!IsAuthorizedConfigPath(configPath, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))) { return ""; } return "Valheim Supreme - Test 0752"; } internal static bool IsAuthorizedConfigPath(string configPath, string appData) { if (string.IsNullOrEmpty(configPath) || string.IsNullOrEmpty(appData)) { return false; } try { string path = Path.Combine(appData, "Thunderstore Mod Manager", "DataFolder", "Valheim", "profiles", "Valheim Supreme - Test 0752", "BepInEx", "config"); return string.Equals(Path.GetFullPath(configPath).TrimEnd(new char[1] { Path.DirectorySeparatorChar }), Path.GetFullPath(path).TrimEnd(new char[1] { Path.DirectorySeparatorChar }), StringComparison.OrdinalIgnoreCase); } catch { return false; } } private static RitualExecutionContext Context(Player player, RitualValheimTarget target) { int loadedZdoCount; WorldExecutionMode mode; string explanation; ZdoInspectionScope scope = CataclysmicStateReader.AssessCompleteWorldZdoScope(out loadedZdoCount, out mode, out explanation); IEnumerable worldReaders = InspectLoadedMatches(target); CompanionZdoSnapshot companionZdoSnapshot = ((target != null) ? CompanionZdoSnapshot.CreateFromReader(target, target.ActualWorldUid, 0L, 0u, target.ActualPrefabHash) : null); RitualExecutionContext ritualExecutionContext = new RitualExecutionContext(); ritualExecutionContext.DiagnosticBuild = DiagnosticExecutionBuild; ritualExecutionContext.ProfileName = ProfileName(); ritualExecutionContext.ExplicitAuthorization = (Object)(object)authorizedTarget != (Object)null && authorizedPlayer == player.GetPlayerID(); ritualExecutionContext.WorldUid = target.ActualWorldUid; ritualExecutionContext.AuthorizedWorldUid = authorizedWorld; ritualExecutionContext.PrefabHash = target.ActualPrefabHash; ritualExecutionContext.FixtureGuid = target.GetString(CataclysmicStateReader.CompanionGuidKey); ritualExecutionContext.FixtureNonce = target.GetString(RitualExecutionContext.FixtureNonceKey); ritualExecutionContext.RequestingPlayerId = player.GetPlayerID().ToString(CultureInfo.InvariantCulture); ritualExecutionContext.AuthorizationExpiresUtc = expires; ritualExecutionContext.Scope = scope; ritualExecutionContext.ScopeEvidence = explanation; ritualExecutionContext.WorldReaders = worldReaders; ritualExecutionContext.CensusSnapshotHash = companionZdoSnapshot?.ComputeSessionIndependentContentSha256(); ritualExecutionContext.CensusTotalZdoCount = loadedZdoCount; ritualExecutionContext.SessionStillValid = () => (Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer && !((Character)player).IsDead() && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.GetWorldUID() == authorizedWorld && ProfileName() == "Valheim Supreme - Test 0752" && (Object)(object)authorizedTarget == (Object)(object)target.Subject && authorizedPlayer == player.GetPlayerID() && CataclysmicStateReader.IsSaveStateSafe(out var _) && CataclysmicStateReader.IsWorldLoadingCompleted(out var _); return ritualExecutionContext; } private static IEnumerable InspectLoadedMatches(RitualValheimTarget target) { string text = target.GetString(CataclysmicStateReader.CompanionGuidKey); if (!CataclysmicStateReader.IsValidCompanionGuid(text)) { return null; } try { IDictionary dictionary = ((ZDOMan.instance == null || loadedZdosField == null) ? null : (loadedZdosField.GetValue(ZDOMan.instance) as IDictionary)); if (dictionary == null || dictionary.Count > 300000) { return null; } List list = new List(); foreach (ZDO value in dictionary.Values) { if (value != null && !(value.GetString(CataclysmicStateReader.CompanionGuidKey, "") != text)) { object item; if (!object.ReferenceEquals(value, target.IdentityHandle)) { IZdoPropertyReader zdoPropertyReader = new ValheimZdoReader(value); item = zdoPropertyReader; } else { item = target; } list.Add((IZdoPropertyReader)item); } } return list; } catch { return null; } } public static bool ShouldBypassServerDevcommands(string raw, object[] args = null) { string text = raw; if (string.IsNullOrEmpty(text) && args != null && args.Length > 1) { text = args[1] as string; } if (string.IsNullOrEmpty(text)) { return false; } if (text.IndexOf('\n') >= 0 || text.IndexOf('\r') >= 0) { string[] array = text.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text2 in array2) { if (text2.Trim().StartsWith("tm_", StringComparison.OrdinalIgnoreCase)) { return true; } } } return text.Trim().StartsWith("tm_", StringComparison.OrdinalIgnoreCase); } internal static Character FindActiveLabBoar() { try { List allCharacters = Character.GetAllCharacters(); if (allCharacters == null) { return null; } long num = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetWorldUID() : 0); int stableHashCode = StringExtensionMethods.GetStableHashCode("Boar"); Character val = null; int num2 = 0; foreach (Character item in allCharacters) { if ((Object)(object)item == (Object)null || item.IsDead() || (Object)(object)((Component)item).gameObject == (Object)null || !string.Equals(Utils.GetPrefabName(((Component)item).gameObject), "Boar", StringComparison.OrdinalIgnoreCase)) { continue; } ZNetView component = ((Component)item).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { continue; } ZDO zDO = component.GetZDO(); if (zDO != null && zDO.GetString("tm_test_scenario", "") == "ritual_lab_boar" && zDO.GetBool("tm_is_test_subject", false) && zDO.GetInt(CataclysmicStateReader.CompanionPrefabHashKey, 0) == stableHashCode) { string text = zDO.GetString(CataclysmicStateReader.CompanionGuidKey, ""); string text2 = zDO.GetString(RitualExecutionContext.FixtureKey, ""); string guid = zDO.GetString(RitualExecutionContext.FixtureNonceKey, ""); long num3 = zDO.GetLong(CataclysmicStateReader.CompanionWorldUidKey, 0L); long num4 = zDO.GetLong(RitualExecutionContext.FixtureWorldKey, 0L); if (CataclysmicStateReader.IsValidCompanionGuid(text) && text == text2 && CataclysmicStateReader.IsValidCompanionGuid(guid) && (num == 0 || (num3 == num && num4 == num))) { val = item; num2++; } } } return (num2 == 1) ? val : null; } catch { return null; } } internal static bool HandleCommand(Player player, Character character, string[] args, out string message) { //IL_02f6: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_030b: 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_0315: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0324: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0336: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) message = null; string text = ((args != null && args.Length > 1) ? args[1].ToLowerInvariant() : ""); switch (text) { case "scope": case "census": { int loadedZdoCount; WorldExecutionMode mode; string explanation; ZdoInspectionScope zdoInspectionScope = CataclysmicStateReader.AssessCompleteWorldZdoScope(out loadedZdoCount, out mode, out explanation); string text4 = "Ninguna criatura seleccionada."; Character val2 = character; if ((Object)(object)val2 == (Object)null || Utils.GetPrefabName(((Component)val2).gameObject).Equals("Lox", StringComparison.OrdinalIgnoreCase)) { Character val3 = FindActiveLabBoar(); if ((Object)(object)val3 != (Object)null) { val2 = val3; } } if ((Object)(object)val2 != (Object)null) { if (Utils.GetPrefabName(((Component)val2).gameObject).Equals("Lox", StringComparison.OrdinalIgnoreCase)) { text4 = "Sujeto: Lox (EXCLUIDO POR POLÍTICA DE SEGURIDAD)."; } else { RitualValheimTarget ritualValheimTarget2 = new RitualValheimTarget(val2); string text5 = ritualValheimTarget2.GetString(CataclysmicStateReader.CompanionGuidKey); int num4 = 0; IEnumerable enumerable = InspectLoadedMatches(ritualValheimTarget2); if (enumerable != null) { foreach (IZdoPropertyReader item in enumerable) { _ = item; num4++; } } text4 = string.Format(CultureInfo.InvariantCulture, "Sujeto: {0} | GUID: {1} | Coincidencias en memoria: {2} | WorldUid: {3} | Prefab: {4}", Utils.GetPrefabName(((Component)val2).gameObject), string.IsNullOrEmpty(text5) ? "ninguno" : text5, num4, ritualValheimTarget2.ActualWorldUid, ritualValheimTarget2.ActualPrefabHash); } } message = string.Format(CultureInfo.InvariantCulture, "DIAGNÓSTICO READ-ONLY: Modo={0} | ZDOs={1} | Alcance={2} | Detalle={3} | {4}", mode, loadedZdoCount, zdoInspectionScope, explanation, text4); return true; } case "setup_boar": { if (args.Length < 3 || !string.Equals(args[2], "CONFIRMAR_LAB", StringComparison.Ordinal)) { message = "Uso: tm_ritual setup_boar CONFIRMAR_LAB. Requiere confirmación explícita para instanciar el Boar de laboratorio."; return true; } if ((Object)(object)player == (Object)null) { message = "BLOQUEADO: Jugador local no disponible."; return true; } if (ProfileName() != "Valheim Supreme - Test 0752") { message = "BLOQUEADO: perfil de producción/no autorizado ('" + ProfileName() + "'). Se requiere 'Valheim Supreme - Test 0752'."; return true; } int loadedZdoCount2; WorldExecutionMode mode2; string explanation2; ZdoInspectionScope zdoInspectionScope2 = CataclysmicStateReader.AssessCompleteWorldZdoScope(out loadedZdoCount2, out mode2, out explanation2); if (zdoInspectionScope2 != ZdoInspectionScope.CompleteWorldVerified || mode2 != WorldExecutionMode.Singleplayer) { message = "BLOQUEADO: Se requiere Singleplayer y CompleteWorldVerified (" + explanation2 + ")."; return true; } long num5 = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetWorldUID() : 0); if (num5 == 0) { message = "BLOQUEADO: WorldUID inválido o cero."; return true; } if ((Object)(object)ZNetScene.instance == (Object)null) { message = "BLOQUEADO: ZNetScene no inicializado."; return true; } Character val4 = FindActiveLabBoar(); if ((Object)(object)val4 != (Object)null) { message = "BLOQUEADO: Ya existe un Boar de laboratorio activo (" + val4.GetHoverName() + "). Ejecuta primero 'tm_ritual cleanup_boar CONFIRMAR_LAB'."; return true; } GameObject prefab = ZNetScene.instance.GetPrefab("Boar"); if ((Object)(object)prefab == (Object)null) { message = "BLOQUEADO: Prefab 'Boar' no encontrado en ZNetScene."; return true; } Vector3 val5 = ((Component)player).transform.position + ((Component)player).transform.forward * 2.5f + Vector3.up * 0.2f; Quaternion val6 = Quaternion.LookRotation(-((Component)player).transform.forward, Vector3.up); GameObject val7 = Object.Instantiate(prefab, val5, val6); Character component3 = val7.GetComponent(); ZNetView component4 = val7.GetComponent(); if ((Object)(object)component3 == (Object)null || (Object)(object)component4 == (Object)null || !component4.IsValid() || component4.GetZDO() == null) { if ((Object)(object)val7 != (Object)null) { Object.Destroy((Object)(object)val7); } message = "ERROR: Fallo al instanciar componentes de red para Boar de laboratorio."; return true; } component3.SetTamed(true); component3.m_faction = (Faction)0; ZDO zDO2 = component4.GetZDO(); string text6 = CataclysmicStateReader.GenerateCompanionGuid(); string text7 = CataclysmicStateReader.GenerateCompanionGuid(); int stableHashCode2 = StringExtensionMethods.GetStableHashCode("Boar"); zDO2.Set(CataclysmicStateReader.CompanionGuidKey, text6); zDO2.Set(CataclysmicStateReader.CompanionWorldUidKey, num5); zDO2.Set(CataclysmicStateReader.CompanionPrefabHashKey, stableHashCode2, false); zDO2.Set(CataclysmicStateReader.OwnerIdKey, player.GetPlayerID()); zDO2.Set(CataclysmicStateReader.TamedBoolKey, true); zDO2.Set(CataclysmicStateReader.TamedNameKey, "BoarLab-0754"); zDO2.Set(CataclysmicStateReader.SavedTierKey, 9, false); zDO2.Set(CataclysmicStateReader.TierOverrideKey, 9, false); zDO2.Set(CataclysmicStateReader.SavedEventKey, "MeteorShower"); zDO2.Set(CataclysmicStateReader.IsUndeadKey, 0, false); zDO2.Set(CataclysmicStateReader.IsCataclysmicKey, 0, false); zDO2.Set(CataclysmicStateReader.HarmonizedFromLegacyKey, 0, false); zDO2.Set(CataclysmicStateReader.RitualTxStateKey, 0, false); zDO2.Set(RitualExecutionContext.FixtureKey, text6); zDO2.Set(RitualExecutionContext.FixtureWorldKey, num5); zDO2.Set(RitualExecutionContext.FixtureNonceKey, text7); zDO2.Set("tm_is_test_subject", true); zDO2.Set("tm_test_scenario", "ritual_lab_boar"); try { ValheimZdoReader reader = new ValheimZdoReader(zDO2); CompanionZdoSnapshot companionZdoSnapshot = CompanionZdoSnapshot.CreateFromReader(reader, num5, 0L, 0u, stableHashCode2); if (companionZdoSnapshot != null) { CompanionPersistentBackup.SaveLegacyOriginBackupWriteOnce(companionZdoSnapshot, "Lab Boar Legacy Backup", out var _, out var _); } } catch (Exception ex2) { Debug.LogWarning((object)("[TameMate Ritual] Error creando respaldo Legacy para Boar: " + ex2.Message)); } CataclysmicHudFormatter.RefreshCompanionLiveState(component3); message = string.Format(CultureInfo.InvariantCulture, "Boar de laboratorio inicializado con éxito. GUID={0} | Nonce={1} | WorldUid={2} | Prefab={3} | Clasificación=LegacyAmbiguous (Tier 9, MeteorShower) | Respaldo Legacy creado en disco.", text6, text7, num5, stableHashCode2); return true; } case "cleanup_boar": { if (args.Length < 3 || !string.Equals(args[2], "CONFIRMAR_LAB", StringComparison.Ordinal)) { message = "Uso: tm_ritual cleanup_boar CONFIRMAR_LAB. Requiere confirmación explícita para destruir el Boar de laboratorio."; return true; } if ((Object)(object)player == (Object)null) { message = "BLOQUEADO: Jugador local no disponible."; return true; } if (ProfileName() != "Valheim Supreme - Test 0752") { message = "BLOQUEADO: perfil de producción/no autorizado ('" + ProfileName() + "'). Se requiere 'Valheim Supreme - Test 0752'."; return true; } long num = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetWorldUID() : 0); int stableHashCode = StringExtensionMethods.GetStableHashCode("Boar"); List list = new List(); try { List allCharacters = Character.GetAllCharacters(); if (allCharacters != null) { foreach (Character item2 in allCharacters) { if ((Object)(object)item2 == (Object)null || item2.IsDead() || (Object)(object)((Component)item2).gameObject == (Object)null) { continue; } string prefabName = Utils.GetPrefabName(((Component)item2).gameObject); if (string.Equals(prefabName, "Lox", StringComparison.OrdinalIgnoreCase) || !string.Equals(prefabName, "Boar", StringComparison.OrdinalIgnoreCase)) { continue; } ZNetView component = ((Component)item2).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { continue; } ZDO zDO = component.GetZDO(); if (zDO != null && zDO.GetString("tm_test_scenario", "") == "ritual_lab_boar" && zDO.GetBool("tm_is_test_subject", false) && zDO.GetInt(CataclysmicStateReader.CompanionPrefabHashKey, 0) == stableHashCode) { string text2 = zDO.GetString(CataclysmicStateReader.CompanionGuidKey, ""); string text3 = zDO.GetString(RitualExecutionContext.FixtureKey, ""); string guid = zDO.GetString(RitualExecutionContext.FixtureNonceKey, ""); long num2 = zDO.GetLong(CataclysmicStateReader.CompanionWorldUidKey, 0L); long num3 = zDO.GetLong(RitualExecutionContext.FixtureWorldKey, 0L); if (CataclysmicStateReader.IsValidCompanionGuid(text2) && text2 == text3 && CataclysmicStateReader.IsValidCompanionGuid(guid) && (num == 0 || (num2 == num && num3 == num))) { list.Add(item2); } } } } } catch (Exception ex) { message = "ERROR en escaneo de entidades para limpieza: " + ex.Message; return true; } if (list.Count == 0) { message = "No se encontró ningún Boar de laboratorio activo para limpiar."; return true; } if (list.Count > 1) { message = string.Format(CultureInfo.InvariantCulture, "CRÍTICO / ABORTO: Se detectaron {0} Boars de laboratorio. Ambigüedad peligrosa detectada; limpieza cancelada para proteger el estado del mundo.", list.Count); return true; } Character val = list[0]; ZNetView component2 = ((Component)val).GetComponent(); if ((Object)(object)component2 == (Object)null || !component2.IsValid() || !component2.IsOwner()) { message = "BLOQUEADO: Sin autoridad de red sobre el Boar de laboratorio para destruirlo."; return true; } string arg = component2.GetZDO().GetString(CataclysmicStateReader.CompanionGuidKey, ""); ZNetScene.instance.Destroy(((Component)val).gameObject); message = string.Format(CultureInfo.InvariantCulture, "Boar de laboratorio destruido exitosamente. GUID={0}. Respaldos y journals en disco conservados intactos.", arg); return true; } case "labplan": message = "Plan (sin crear entidades): autorizar explícitamente perfil 'Valheim Supreme - Test 0752' y WorldUid; crear después un Boar de laboratorio independiente (NUNCA el Lox actual), GUID y nonce nuevos, marcas tm_ritual_lab_fixture/world/nonce y respaldo Legacy write-once. Falta verificador global del mundo persistido; ejecución bloqueada."; return true; default: { if (text != "authorize" && text != "prepare" && text != "confirm" && text != "commit" && text != "rollback" && text != "recover" && text != "recovery" && text != "prepare-rollback" && text != "prepare-recovery") { return false; } if ((Object)(object)player == (Object)null || (Object)(object)character == (Object)null) { message = "Jugador/compañero no disponible."; return true; } if (!DiagnosticExecutionBuild) { message = "BLOQUEADO: compilación sin RITUAL_LAB_EXECUTION + TEST_DIAGNOSTICS."; return true; } if (ProfileName() != "Valheim Supreme - Test 0752") { message = "BLOQUEADO: perfil de producción/no autorizado."; return true; } if (Utils.GetPrefabName(((Component)character).gameObject).Equals("Lox", StringComparison.OrdinalIgnoreCase)) { message = "BLOQUEADO: el Lox existente no es sujeto del ritual."; return true; } RitualValheimTarget ritualValheimTarget = new RitualValheimTarget(character); if (text == "authorize") { if (args.Length != 4 || !long.TryParse(args[2], out var result) || result == 0 || result != ritualValheimTarget.ActualWorldUid || args[3] != "CONFIRMAR_LAB") { message = "Uso futuro: tm_ritual authorize CONFIRMAR_LAB. No realiza escrituras."; return true; } authorizedTarget = character; authorizedWorld = result; authorizedPlayer = player.GetPlayerID(); expires = DateTime.UtcNow.AddMinutes(5.0); session = new RitualLiveSession(ritualValheimTarget, Context(player, ritualValheimTarget)); message = "Autorización temporal en memoria registrada; aún requiere marca sintética, identidad, respaldo y unicidad global verificable."; return true; } if (session == null || (Object)(object)authorizedTarget != (Object)(object)character || authorizedPlayer != player.GetPlayerID()) { message = "BLOQUEADO: falta autorización explícita de este sujeto/mundo; no se usa cercanía como identidad."; return true; } switch (text) { case "prepare": case "prepare-rollback": case "prepare-recovery": { int result3 = 9; if (text == "prepare" && (args.Length != 3 || !int.TryParse(args[2], out result3))) { message = "Uso: tm_ritual prepare <1..8|10>."; return true; } session.Prepare((!(text == "prepare")) ? ((text == "prepare-rollback") ? RitualOperation.Rollback : RitualOperation.Recovery) : RitualOperation.Harmonize, result3, out var ticketId, out message); if (ticketId != null) { object obj = message; message = string.Concat(obj, " Ticket=", ticketId, " Tier=", result3); } break; } case "confirm": { if (args.Length != 5 || !int.TryParse(args[3], out var result2) || args[4] != "CONFIRMAR") { message = "Uso: tm_ritual confirm CONFIRMAR."; return true; } session.Confirm(args[2], result2, player.GetPlayerID().ToString(CultureInfo.InvariantCulture), explicitConfirmation: true, out message); break; } default: message = session.RecoveryStatus() + " Usar prepare-rollback/prepare-recovery y confirmar su ticket; commit directo deshabilitado."; break; } return true; } } } } public enum RpgArchetypeId { Neutral, Tank, Warrior, Berserker, Assassin, Lancer, Archer, Mage, Tamer, Hybrid } public enum RpgHybridIdentityId { None, Tank_Warrior, Tank_Berserker, Tank_Assassin, Tank_Lancer, Tank_Archer, Tank_Mage, Tank_Tamer, Warrior_Berserker, Warrior_Assassin, Warrior_Lancer, Warrior_Archer, Warrior_Mage, Warrior_Tamer, Berserker_Assassin, Berserker_Lancer, Berserker_Archer, Berserker_Mage, Berserker_Tamer, Assassin_Lancer, Assassin_Archer, Assassin_Mage, Assassin_Tamer, Lancer_Archer, Lancer_Mage, Lancer_Tamer, Archer_Mage, Archer_Tamer, Mage_Tamer } public enum ArchetypeSpecializationTier { Novice, Developing, Specialized, Master } public struct ArchetypeAffinityScore { public RpgArchetypeId Archetype; public float Score; public string PrimaryFactor; public string Details; public ArchetypeAffinityScore(RpgArchetypeId archetype, float score, string factor, string details = "") { Archetype = archetype; Score = Mathf.Clamp01(score); PrimaryFactor = factor ?? string.Empty; Details = details ?? string.Empty; } } public struct RpgHybridSpecializationDefinition { public readonly RpgHybridIdentityId IdentityId; public readonly RpgArchetypeId AspectA; public readonly RpgArchetypeId AspectB; public readonly string DisplayTitleEs; public readonly string DisplayTitleEn; public readonly string DescriptionEs; public readonly string DescriptionEn; public RpgHybridSpecializationDefinition(RpgHybridIdentityId id, RpgArchetypeId a, RpgArchetypeId b, string titleEs, string titleEn, string descEs, string descEn) { IdentityId = id; AspectA = a; AspectB = b; DisplayTitleEs = titleEs ?? string.Empty; DisplayTitleEn = titleEn ?? string.Empty; DescriptionEs = descEs ?? string.Empty; DescriptionEn = descEn ?? string.Empty; } public string GetLocalizedTitle(string language) { if (string.Equals(language, "English", StringComparison.OrdinalIgnoreCase)) { return DisplayTitleEn; } return DisplayTitleEs; } public string GetLocalizedDescription(string language) { if (string.Equals(language, "English", StringComparison.OrdinalIgnoreCase)) { return DescriptionEn; } return DescriptionEs; } } public static class RpgHybridRegistry { private static readonly Dictionary s_definitions; private static readonly Dictionary s_lookupTable; public static int Count => s_definitions.Count; static RpgHybridRegistry() { s_definitions = new Dictionary(29); s_lookupTable = new Dictionary(64); Register(RpgHybridIdentityId.Tank_Warrior, RpgArchetypeId.Tank, RpgArchetypeId.Warrior, "Baluarte", "Bulwark", "Defensa inquebrantable y disciplina marcial con armas cuerpo a cuerpo.", "Unshakeable defense and martial discipline with melee armaments."); Register(RpgHybridIdentityId.Tank_Berserker, RpgArchetypeId.Tank, RpgArchetypeId.Berserker, "Juggernaut", "Juggernaut", "Resistencia sobrehumana que absorbe castigo brutal mientras desata furia física.", "Superhuman resilience absorbing brutal punishment while unleashing physical fury."); Register(RpgHybridIdentityId.Tank_Assassin, RpgArchetypeId.Tank, RpgArchetypeId.Assassin, "Sombra Acorazada", "Iron Shadow", "Infiltración táctica protegida por armadura pesada y contragolpes precisos.", "Tactical infiltration protected by heavy armor and precision counters."); Register(RpgHybridIdentityId.Tank_Lancer, RpgArchetypeId.Tank, RpgArchetypeId.Lancer, "Centinela", "Sentinel", "Control de distancias con armas de asta tras un muro impenetrable de defensa.", "Distance control with polearms behind an impenetrable wall of defense."); Register(RpgHybridIdentityId.Tank_Archer, RpgArchetypeId.Tank, RpgArchetypeId.Archer, "Defensor Balístico", "Ballistier", "Fortaleza móvil que repele amenazas a distancia antes de resistir el embate cuerpo a cuerpo.", "Mobile fortress repelling distant threats before withstanding melee onslaught."); Register(RpgHybridIdentityId.Tank_Mage, RpgArchetypeId.Tank, RpgArchetypeId.Mage, "Guardián Arcano", "Arcane Guardian", "Baliza mágica acorazada que combina barreras arcanas con mitigación física pesada.", "Armored magical beacon combining arcane barriers with heavy physical mitigation."); Register(RpgHybridIdentityId.Tank_Tamer, RpgArchetypeId.Tank, RpgArchetypeId.Tamer, "Guardián de las Bestias", "Beast Guardian", "Protector inamovible que absorbe el daño para permitir la supremacía de sus compañeros.", "Immovable protector absorbing incoming damage to unleash companion supremacy."); Register(RpgHybridIdentityId.Warrior_Berserker, RpgArchetypeId.Warrior, RpgArchetypeId.Berserker, "Señor de la Guerra", "Warlord", "Maestría marcial implacable que equilibra técnica refinada con ferocidad salvaje.", "Relentless martial prowess balancing refined technique with savage ferocity."); Register(RpgHybridIdentityId.Warrior_Assassin, RpgArchetypeId.Warrior, RpgArchetypeId.Assassin, "Duelista", "Duelist", "Dominio de hojas de combate combinando estocadas letales, agilidad y esgrima.", "Blade mastery combining lethal thrusts, fluid agility, and swordplay."); Register(RpgHybridIdentityId.Warrior_Lancer, RpgArchetypeId.Warrior, RpgArchetypeId.Lancer, "Hoplita", "Hoplite", "Formación clásica de choque que conjuga alcance de asta con resistencia marcial.", "Classical shock formation combining polearm reach with disciplined martial combat."); Register(RpgHybridIdentityId.Warrior_Archer, RpgArchetypeId.Warrior, RpgArchetypeId.Archer, "Montaraz", "Skirmisher", "Versatilidad total entre el combate a distancia y el acero en combate cerrado.", "Total versatility alternating between ranged marksmanship and close-quarters steel."); Register(RpgHybridIdentityId.Warrior_Mage, RpgArchetypeId.Warrior, RpgArchetypeId.Mage, "Guerrero Arcano", "Spellblade", "Espada imbuida con energías elementales y soporte mágico de combate.", "Blades infused with elemental energies and spell-weaving combat support."); Register(RpgHybridIdentityId.Warrior_Tamer, RpgArchetypeId.Warrior, RpgArchetypeId.Tamer, "Líder de Manada", "Pack Leader", "Comandante marcial de vanguardia que lucha hombro con hombro junto a sus criaturas.", "Frontline martial commander fighting shoulder to shoulder with loyal beasts."); Register(RpgHybridIdentityId.Berserker_Assassin, RpgArchetypeId.Berserker, RpgArchetypeId.Assassin, "Descuartizador", "Ravager", "Velocidad salvaje y ataques demoledores a puntos vitales sin piedad.", "Savage burst speed and devastating strikes directed at vital points without mercy."); Register(RpgHybridIdentityId.Berserker_Lancer, RpgArchetypeId.Berserker, RpgArchetypeId.Lancer, "Empalador Feroz", "Vicious Impaler", "Acometidas de impacto masivo con armas de asta y furor imparable.", "Massive impact charges wielding heavy reach weapons with unstoppable momentum."); Register(RpgHybridIdentityId.Berserker_Archer, RpgArchetypeId.Berserker, RpgArchetypeId.Archer, "Hostigador Salvaje", "Savage Hunter", "Fuerza bruta aplicada a proyectiles pesados y persecución implacable.", "Brute force applied to heavy projectile volleys and relentless pursuit."); Register(RpgHybridIdentityId.Berserker_Mage, RpgArchetypeId.Berserker, RpgArchetypeId.Mage, "Chamán de Guerra", "War Shaman", "Canalización de magia destructiva y furia sanguínea en el vórtice del combate.", "Channeling destructive magic and blood frenzy at the very heart of the maelstrom."); Register(RpgHybridIdentityId.Berserker_Tamer, RpgArchetypeId.Berserker, RpgArchetypeId.Tamer, "Señor de las Bestias", "Beast Lord", "Ferocidad compartida que impulsa a bestias y amo hacia un frenesí destructivo.", "Shared predatory ferocity driving master and companions into destructive frenzy."); Register(RpgHybridIdentityId.Assassin_Lancer, RpgArchetypeId.Assassin, RpgArchetypeId.Lancer, "Víbora de Asta", "Viper", "Ataques sorpresa a distancia media con puntas envenenadas y evasión letal.", "Mid-range surprise strikes with piercing tips and lethal evasive footwork."); Register(RpgHybridIdentityId.Assassin_Archer, RpgArchetypeId.Assassin, RpgArchetypeId.Archer, "Acechador", "Stalker", "Tirador invisible desde las sombras con precisión milimétrica y emboscadas letales.", "Unseen marksman operating from the shadows with pinpoint accuracy and ambushes."); Register(RpgHybridIdentityId.Assassin_Mage, RpgArchetypeId.Assassin, RpgArchetypeId.Mage, "Sombra Arcana", "Arcane Shadow", "Manipulación de magia de sigilo, teletransporte y dagas imbuidas de éter.", "Mastery of concealment sorcery, ethereal steps, and infused daggers."); Register(RpgHybridIdentityId.Assassin_Tamer, RpgArchetypeId.Assassin, RpgArchetypeId.Tamer, "Cazador Furtivo", "Shadow Stalker", "Coordinación silenciosa entre depredador y bestias en emboscadas sincronizadas.", "Silent predatory coordination orchestrating synchronized ambushes with tamed beasts."); Register(RpgHybridIdentityId.Lancer_Archer, RpgArchetypeId.Lancer, RpgArchetypeId.Archer, "Hostigador Táctico", "Outrider", "Control total del campo de batalla mediante proyectiles lejanos y picas a media distancia.", "Battlefield zoning utilizing long-range volleys followed by mid-range pike defense."); Register(RpgHybridIdentityId.Lancer_Mage, RpgArchetypeId.Lancer, RpgArchetypeId.Mage, "Lancero Arcano", "Arcane Lancer", "Armas de asta canalizadoras de relámpagos, escarcha y explosiones de éter.", "Polearms serving as conductors for lightning, frost, and directional Eitr bursts."); Register(RpgHybridIdentityId.Lancer_Tamer, RpgArchetypeId.Lancer, RpgArchetypeId.Tamer, "Custodio de Bestias", "Beast Warder", "Mantiene a raya a las amenazas mediante lanzas mientras sus aliados animales flanquean.", "Keeps threats at bay with defensive reach while animal allies flank relentlessly."); Register(RpgHybridIdentityId.Archer_Mage, RpgArchetypeId.Archer, RpgArchetypeId.Mage, "Arquero Arcano", "Arcane Archer", "Flechas encantadas con fuego, escarcha y magia de sangre a larga distancia.", "Arrows enchanted with fire, frost, and blood sorcery over vast distances."); Register(RpgHybridIdentityId.Archer_Tamer, RpgArchetypeId.Archer, RpgArchetypeId.Tamer, "Cazador de Bestias", "Beast Hunter", "Tirador de largo alcance apoyado por rastreadores y bestias de presa fieles.", "Long-range marksman supported by loyal hounds and predatory trackers."); Register(RpgHybridIdentityId.Mage_Tamer, RpgArchetypeId.Mage, RpgArchetypeId.Tamer, "Domador Arcano", "Spirit Binder", "Fortalece, cura y protege a sus criaturas mediante hechizos protectores y éter.", "Empowers, heals, and shields animal companions through weaving supportive Eitr."); } private static void Register(RpgHybridIdentityId id, RpgArchetypeId a, RpgArchetypeId b, string titleEs, string titleEn, string descEs, string descEn) { RpgHybridSpecializationDefinition value = new RpgHybridSpecializationDefinition(id, a, b, titleEs, titleEn, descEs, descEn); s_definitions[id] = value; int key = ComputeKey(a, b); int key2 = ComputeKey(b, a); s_lookupTable[key] = id; s_lookupTable[key2] = id; } private static int ComputeKey(RpgArchetypeId a, RpgArchetypeId b) { return (int)((int)a * 100 + b); } public static RpgHybridIdentityId ResolveIdentity(RpgArchetypeId a, RpgArchetypeId b) { if (a == b || a == RpgArchetypeId.Neutral || b == RpgArchetypeId.Neutral || a == RpgArchetypeId.Hybrid || b == RpgArchetypeId.Hybrid) { return RpgHybridIdentityId.None; } int key = ComputeKey(a, b); if (s_lookupTable.TryGetValue(key, out var value)) { return value; } return RpgHybridIdentityId.None; } public static RpgHybridSpecializationDefinition GetDefinition(RpgHybridIdentityId id) { if (s_definitions.TryGetValue(id, out var value)) { return value; } return new RpgHybridSpecializationDefinition(RpgHybridIdentityId.None, RpgArchetypeId.Neutral, RpgArchetypeId.Neutral, "Ninguno", "None", "Sin especialización híbrida activa.", "No active hybrid specialization."); } public static ICollection GetAllDefinitions() { return s_definitions.Values; } } public struct RpgArchetypeCapabilityBreakdown { public readonly string CapabilityName; public readonly float EffectiveValue; public readonly float PermanentShare; public readonly float EquipmentShare; public readonly string PrimarySourceDescription; public float PermanentPercent => PermanentShare; public float EquipmentPercent => EquipmentShare; public string ProvenanceSummary => PrimarySourceDescription; public RpgArchetypeCapabilityBreakdown(string name, float effective, float permanent, float equipment, string sourceDesc) { CapabilityName = name ?? string.Empty; EffectiveValue = Mathf.Clamp01(effective); PermanentShare = Mathf.Clamp01(permanent); EquipmentShare = Mathf.Clamp01(equipment); PrimarySourceDescription = sourceDesc ?? string.Empty; } } public sealed class RpgCodexCharacterProfile { private readonly Dictionary m_affinities; private readonly List m_capabilities; public string CharacterName { get; private set; } public RpgArchetypeId PrimaryArchetype { get; private set; } public RpgArchetypeId SecondaryArchetype { get; private set; } public RpgHybridIdentityId HybridIdentity { get; private set; } public string HybridTitle { get; private set; } public string HybridDescription { get; private set; } public bool IsHybrid { get; private set; } public bool HasSecondaryAffinity { get; private set; } public float PrimaryAffinity { get; private set; } public float SecondaryAffinity { get; private set; } public float Confidence { get; private set; } public float SpecializationIndex { get; private set; } public float EffectivePowerLevel { get; private set; } public ArchetypeSpecializationTier Tier { get; private set; } public int HighAffinityCount { get; private set; } public bool IsMultidisciplinaryMaster { get; private set; } public string DiagnosticExplanation { get; private set; } public string ProvenanceSummary { get; private set; } public DateTime TimestampUtc { get; private set; } public float GetAffinity(RpgArchetypeId archetype) { if (m_affinities != null && m_affinities.TryGetValue(archetype, out var value)) { return value; } return 0f; } public ICollection> GetAllAffinities() { return m_affinities; } public IList GetCapabilities() { return m_capabilities; } public RpgCodexCharacterProfile(ArchetypeClassificationResult rawResult, RpgPlayerCapabilitySnapshot snapshot) { rawResult = rawResult ?? new ArchetypeClassificationResult(); CharacterName = ((snapshot != null && !string.IsNullOrEmpty(snapshot.PlayerName)) ? snapshot.PlayerName : "Héroe"); PrimaryArchetype = rawResult.PrimaryArchetype; SecondaryArchetype = rawResult.SecondaryArchetype; HybridIdentity = rawResult.HybridIdentity; HybridTitle = rawResult.HybridTitle; IsHybrid = rawResult.IsHybrid; HasSecondaryAffinity = rawResult.HasSecondaryAffinity; Confidence = rawResult.Confidence; SpecializationIndex = rawResult.SpecializationIndex; EffectivePowerLevel = rawResult.EffectivePowerLevel; Tier = rawResult.Tier; HighAffinityCount = rawResult.HighAffinityCount; IsMultidisciplinaryMaster = rawResult.IsMultidisciplinaryMaster; DiagnosticExplanation = rawResult.DiagnosticExplanation; ProvenanceSummary = rawResult.ProvenanceSummary; TimestampUtc = rawResult.TimestampUtc; HybridDescription = RpgHybridRegistry.GetDefinition(HybridIdentity).DescriptionEs; PrimaryAffinity = rawResult.GetAffinity((PrimaryArchetype == RpgArchetypeId.Hybrid) ? rawResult.SecondaryArchetype : PrimaryArchetype); SecondaryAffinity = ((SecondaryArchetype != RpgArchetypeId.Neutral) ? rawResult.GetAffinity(SecondaryArchetype) : 0f); m_affinities = new Dictionary(rawResult.AllAffinities); m_capabilities = new List(); if (snapshot != null) { UniversalCapabilityVector universalCapabilityVector = snapshot.EffectiveProfile ?? new UniversalCapabilityVector(); UniversalCapabilityVector universalCapabilityVector2 = snapshot.PermanentProgression ?? new UniversalCapabilityVector(); UniversalCapabilityVector universalCapabilityVector3 = snapshot.ActiveEquipment ?? new UniversalCapabilityVector(); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Vitalidad", universalCapabilityVector.Vitality, universalCapabilityVector2.Vitality, universalCapabilityVector3.Vitality, "Salud, Vigor, Alimentos y Rasgos")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Poder Físico", universalCapabilityVector.PhysicalPower, universalCapabilityVector2.PhysicalPower, universalCapabilityVector3.PhysicalPower, "Fuerza, Habilidades marciales y Armas")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Defensa", universalCapabilityVector.Defense, universalCapabilityVector2.Defense, universalCapabilityVector3.Defense, "Armadura equipada, Escudos y Bloqueo")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Movilidad", universalCapabilityVector.Mobility, universalCapabilityVector2.Mobility, universalCapabilityVector3.Mobility, "Carrera, Salto y Evasión")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Estamina", universalCapabilityVector.StaminaMastery, universalCapabilityVector2.StaminaMastery, universalCapabilityVector3.StaminaMastery, "Reserva y regeneración de estamina")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Precisión", universalCapabilityVector.Precision, universalCapabilityVector2.Precision, universalCapabilityVector3.Precision, "Arquería, Sigilo y Cuchillos")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Hechicería", universalCapabilityVector.Sorcery, universalCapabilityVector2.Sorcery, universalCapabilityVector3.Sorcery, "Eitr, Elementos y Báculos")); m_capabilities.Add(new RpgArchetypeCapabilityBreakdown("Afinidad Bestias", universalCapabilityVector.CompanionAffinity, universalCapabilityVector2.CompanionAffinity, universalCapabilityVector3.CompanionAffinity, "Maestrías TameMate y Compañeros")); } } } public sealed class ArchetypeClassificationResult { public RpgArchetypeId PrimaryArchetype; public RpgArchetypeId SecondaryArchetype; public RpgHybridIdentityId HybridIdentity; public string HybridTitle = string.Empty; public string HybridDescription = string.Empty; public bool HasSecondaryAffinity; public float Confidence; public float SpecializationIndex; public float EffectivePowerLevel; public ArchetypeSpecializationTier Tier; public int HighAffinityCount; public bool IsMultidisciplinaryMaster; public readonly Dictionary AllAffinities = new Dictionary(); public string DiagnosticExplanation = string.Empty; public string ProvenanceSummary = string.Empty; public DateTime TimestampUtc = DateTime.UtcNow; public bool IsHybrid { get { if (PrimaryArchetype != RpgArchetypeId.Hybrid) { return HybridIdentity != RpgHybridIdentityId.None; } return true; } } public float GetAffinity(RpgArchetypeId archetype) { if (AllAffinities.TryGetValue(archetype, out var value)) { return value; } return 0f; } public RpgCodexCharacterProfile ToCodexProfile(RpgPlayerCapabilitySnapshot snapshot = null) { return new RpgCodexCharacterProfile(this, snapshot); } } public static class RpgArchetypeEngine { public const float MinSpecializationThreshold = 0.18f; public const float HybridCoDominanceMargin = 0.15f; public const float HybridMinAffinityThreshold = 0.3f; public const float SecondaryAffinityThreshold = 0.2f; public static ArchetypeClassificationResult Classify(RpgPlayerCapabilitySnapshot snapshot) { if (snapshot == null) { return CreateNeutralResult("Snapshot nulo provisto al motor de arquetipos."); } UniversalCapabilityVector eff = snapshot.EffectiveProfile ?? new UniversalCapabilityVector(); UniversalCapabilityVector perm = snapshot.PermanentProgression ?? new UniversalCapabilityVector(); UniversalCapabilityVector equip = snapshot.ActiveEquipment ?? new UniversalCapabilityVector(); RpgWeaponCategory activeWeaponCategory = snapshot.ActiveWeaponCategory; return ClassifyInternal(eff, perm, equip, activeWeaponCategory, snapshot.ActiveShieldType); } public static ArchetypeClassificationResult Classify(UniversalCapabilityVector effectiveProfile, UniversalCapabilityVector permanentProgression, UniversalCapabilityVector activeEquipment, RpgWeaponCategory activeWeapon = RpgWeaponCategory.None, string shieldType = "None") { UniversalCapabilityVector eff = effectiveProfile ?? new UniversalCapabilityVector(); UniversalCapabilityVector perm = permanentProgression ?? new UniversalCapabilityVector(); UniversalCapabilityVector equip = activeEquipment ?? new UniversalCapabilityVector(); return ClassifyInternal(eff, perm, equip, activeWeapon, shieldType); } private static ArchetypeClassificationResult ClassifyInternal(UniversalCapabilityVector eff, UniversalCapabilityVector perm, UniversalCapabilityVector equip, RpgWeaponCategory activeWeapon, string shieldType) { ArchetypeClassificationResult archetypeClassificationResult = new ArchetypeClassificationResult(); archetypeClassificationResult.TimestampUtc = DateTime.UtcNow; float totalMagnitude = eff.GetTotalMagnitude(); archetypeClassificationResult.EffectivePowerLevel = Mathf.Clamp01(totalMagnitude / 5.5f); float peakCapabilityValue = eff.GetPeakCapabilityValue(); if (archetypeClassificationResult.EffectivePowerLevel < 0.18f && peakCapabilityValue < 0.25f) { archetypeClassificationResult.Tier = ArchetypeSpecializationTier.Novice; } else if (archetypeClassificationResult.EffectivePowerLevel < 0.4f || peakCapabilityValue < 0.5f) { archetypeClassificationResult.Tier = ArchetypeSpecializationTier.Developing; } else if (archetypeClassificationResult.EffectivePowerLevel < 0.7f || peakCapabilityValue < 0.8f) { archetypeClassificationResult.Tier = ArchetypeSpecializationTier.Specialized; } else { archetypeClassificationResult.Tier = ArchetypeSpecializationTier.Master; } float value = CalculateTankAffinity(eff, equip, shieldType); float value2 = CalculateWarriorAffinity(eff, perm, equip); float value3 = CalculateBerserkerAffinity(eff, equip); float value4 = CalculateAssassinAffinity(eff, perm, equip); float value5 = CalculateLancerAffinity(eff, perm, equip); float value6 = CalculateArcherAffinity(eff, perm, equip); float value7 = CalculateMageAffinity(eff, perm, equip); float value8 = CalculateTamerAffinity(eff, perm); archetypeClassificationResult.AllAffinities[RpgArchetypeId.Tank] = value; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Warrior] = value2; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Berserker] = value3; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Assassin] = value4; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Lancer] = value5; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Archer] = value6; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Mage] = value7; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Tamer] = value8; RpgArchetypeId rpgArchetypeId = RpgArchetypeId.Neutral; float num = -1f; RpgArchetypeId rpgArchetypeId2 = RpgArchetypeId.Neutral; float num2 = -1f; int num3 = 0; foreach (KeyValuePair allAffinity in archetypeClassificationResult.AllAffinities) { if (allAffinity.Value >= 0.5f) { num3++; } if (allAffinity.Value > num) { num2 = num; rpgArchetypeId2 = rpgArchetypeId; num = allAffinity.Value; rpgArchetypeId = allAffinity.Key; } else if (allAffinity.Value > num2) { num2 = allAffinity.Value; rpgArchetypeId2 = allAffinity.Key; } } archetypeClassificationResult.HighAffinityCount = num3; archetypeClassificationResult.IsMultidisciplinaryMaster = archetypeClassificationResult.Tier == ArchetypeSpecializationTier.Master && num3 >= 3; archetypeClassificationResult.ProvenanceSummary = string.Format(CultureInfo.InvariantCulture, "Capacidades efectivas evaluadas: Total={0:F2}, Pico={1:F2}. Permanente={2:F2}, Equipamiento={3:F2}.", totalMagnitude, peakCapabilityValue, perm.GetTotalMagnitude(), equip.GetTotalMagnitude()); float num4 = totalMagnitude / 9f; float num5 = 0f; num5 += Mathf.Pow(eff.Vitality - num4, 2f); num5 += Mathf.Pow(eff.PhysicalPower - num4, 2f); num5 += Mathf.Pow(eff.Defense - num4, 2f); num5 += Mathf.Pow(eff.Mobility - num4, 2f); num5 += Mathf.Pow(eff.StaminaMastery - num4, 2f); num5 += Mathf.Pow(eff.Precision - num4, 2f); num5 += Mathf.Pow(eff.Sorcery - num4, 2f); num5 += Mathf.Pow(eff.WeaponMastery - num4, 2f); num5 += Mathf.Pow(eff.CompanionAffinity - num4, 2f); archetypeClassificationResult.SpecializationIndex = Mathf.Clamp01(Mathf.Sqrt(num5 / 9f) * 3.5f); if (num < 0.18f && archetypeClassificationResult.EffectivePowerLevel < 0.2f) { archetypeClassificationResult.PrimaryArchetype = RpgArchetypeId.Neutral; archetypeClassificationResult.SecondaryArchetype = RpgArchetypeId.Neutral; archetypeClassificationResult.HybridIdentity = RpgHybridIdentityId.None; archetypeClassificationResult.HybridTitle = string.Empty; archetypeClassificationResult.HybridDescription = string.Empty; archetypeClassificationResult.HasSecondaryAffinity = false; archetypeClassificationResult.Confidence = 0f; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Neutral] = 1f; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Hybrid] = 0f; archetypeClassificationResult.DiagnosticExplanation = string.Format(CultureInfo.InvariantCulture, "Estado [Neutral]: Especialización insuficiente (Afinidad pico: {0:F2} < {1:F2}). Perfil balanceado o novicio.", num, 0.18f); return archetypeClassificationResult; } bool flag = num >= 0.3f && num2 >= 0.3f && Mathf.Abs(num - num2) <= 0.15f && rpgArchetypeId != rpgArchetypeId2 && rpgArchetypeId != RpgArchetypeId.Neutral && rpgArchetypeId2 != RpgArchetypeId.Neutral; float num6 = 0f; if (flag) { float num7 = 1f - Mathf.Abs(num - num2) / 0.15f; num6 = Mathf.Clamp01((num + num2) * 0.5f * (0.85f + 0.15f * num7)); } archetypeClassificationResult.AllAffinities[RpgArchetypeId.Hybrid] = num6; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Neutral] = 0f; if (flag) { archetypeClassificationResult.PrimaryArchetype = RpgArchetypeId.Hybrid; archetypeClassificationResult.SecondaryArchetype = ((num >= num2) ? rpgArchetypeId : rpgArchetypeId2); archetypeClassificationResult.HybridIdentity = RpgHybridRegistry.ResolveIdentity(rpgArchetypeId, rpgArchetypeId2); RpgHybridSpecializationDefinition definition = RpgHybridRegistry.GetDefinition(archetypeClassificationResult.HybridIdentity); archetypeClassificationResult.HybridTitle = definition.DisplayTitleEs; archetypeClassificationResult.HybridDescription = definition.DescriptionEs; archetypeClassificationResult.HasSecondaryAffinity = true; archetypeClassificationResult.Confidence = Mathf.Clamp01(num6 * (1f - Mathf.Abs(num - num2) / 0.3f)); if (archetypeClassificationResult.IsMultidisciplinaryMaster) { archetypeClassificationResult.DiagnosticExplanation = string.Format(CultureInfo.InvariantCulture, "Reconocido como [Híbrido: {0}] (Maestro Multidisciplinar, {1} disciplinas dominadas). Co-dominancia líder entre {2} ({3:F2}) y {4} ({5:F2}). Margen: {6:F2}.", archetypeClassificationResult.HybridTitle, archetypeClassificationResult.HighAffinityCount, GetArchetypeDisplayName(rpgArchetypeId), num, GetArchetypeDisplayName(rpgArchetypeId2), num2, Mathf.Abs(num - num2)); } else { archetypeClassificationResult.DiagnosticExplanation = string.Format(CultureInfo.InvariantCulture, "Reconocido como [Híbrido: {0}]: Co-dominancia verificada entre {1} ({2:F2}) y {3} ({4:F2}). Margen: {5:F2}.", archetypeClassificationResult.HybridTitle, GetArchetypeDisplayName(rpgArchetypeId), num, GetArchetypeDisplayName(rpgArchetypeId2), num2, Mathf.Abs(num - num2)); } return archetypeClassificationResult; } archetypeClassificationResult.PrimaryArchetype = rpgArchetypeId; archetypeClassificationResult.SecondaryArchetype = rpgArchetypeId2; archetypeClassificationResult.HybridIdentity = RpgHybridIdentityId.None; archetypeClassificationResult.HybridTitle = string.Empty; archetypeClassificationResult.HybridDescription = string.Empty; archetypeClassificationResult.HasSecondaryAffinity = num2 >= 0.2f && rpgArchetypeId2 != RpgArchetypeId.Neutral; float num8 = num - Mathf.Max(0f, num2); archetypeClassificationResult.Confidence = Mathf.Clamp01(num8 / 0.25f * (0.5f + num * 0.5f)); if (archetypeClassificationResult.HasSecondaryAffinity) { archetypeClassificationResult.DiagnosticExplanation = string.Format(CultureInfo.InvariantCulture, "Reconocido como [{0}] con Afinidad Secundaria a [{1}] (Confianza: {2:P0}, Rango: {3}). Afinidad: {4:F2}, Segundo: {5:F2} (Margen: +{6:F2}).", GetArchetypeDisplayName(rpgArchetypeId), GetArchetypeDisplayName(archetypeClassificationResult.SecondaryArchetype), archetypeClassificationResult.Confidence, GetTierDisplayName(archetypeClassificationResult.Tier), num, num2, num8); } else { archetypeClassificationResult.DiagnosticExplanation = string.Format(CultureInfo.InvariantCulture, "Reconocido como [{0}] (Confianza: {1:P0}, Rango: {2}). Afinidad: {3:F2}, Segundo: {4} ({5:F2}, Margen: +{6:F2}).", GetArchetypeDisplayName(rpgArchetypeId), archetypeClassificationResult.Confidence, GetTierDisplayName(archetypeClassificationResult.Tier), num, GetArchetypeDisplayName(rpgArchetypeId2), num2, num8); } return archetypeClassificationResult; } public static string GetArchetypeDisplayName(RpgArchetypeId id) { return id switch { RpgArchetypeId.Tank => "Tanque Baluarte", RpgArchetypeId.Warrior => "Guerrero Marcial", RpgArchetypeId.Berserker => "Berserker Furioso", RpgArchetypeId.Assassin => "Asesino Sombrío", RpgArchetypeId.Lancer => "Lancero Ágil", RpgArchetypeId.Archer => "Arquero Cazador", RpgArchetypeId.Mage => "Mago Elemental", RpgArchetypeId.Tamer => "Domador de Manadas", RpgArchetypeId.Hybrid => "Híbrido Multidisciplinar", RpgArchetypeId.Neutral => "Neutral", _ => id.ToString(), }; } public static string GetTierDisplayName(ArchetypeSpecializationTier tier) { return tier switch { ArchetypeSpecializationTier.Novice => "Novato", ArchetypeSpecializationTier.Developing => "En Desarrollo", ArchetypeSpecializationTier.Specialized => "Especializado", ArchetypeSpecializationTier.Master => "Maestro", _ => tier.ToString(), }; } private static float CalculateTankAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector equip, string shieldType) { float num = eff.Defense * 0.45f + eff.Vitality * 0.35f + eff.StaminaMastery * 0.15f + eff.PhysicalPower * 0.05f; float num2 = 0f; if (!string.IsNullOrEmpty(shieldType) && !shieldType.Equals("None", StringComparison.OrdinalIgnoreCase)) { num2 += 0.2f; } else { num *= 0.7f; } float num3 = 1f; if (eff.Sorcery > 0.4f) { num3 = Mathf.Max(0.7f, 1f - (eff.Sorcery - 0.4f) * 0.5f); } return Mathf.Clamp01((num + num2) * num3); } private static float CalculateWarriorAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector perm, UniversalCapabilityVector equip) { float num = eff.PhysicalPower * 0.35f + eff.Defense * 0.3f + eff.StaminaMastery * 0.2f + eff.Vitality * 0.15f; float num2 = Mathf.Abs(eff.PhysicalPower - eff.Defense); float num3 = Mathf.Clamp01(1f - num2 * 0.5f); float weaponAffinity = eff.GetWeaponAffinity(RpgWeaponCategory.Swords); float weaponAffinity2 = eff.GetWeaponAffinity(RpgWeaponCategory.Clubs); float weaponAffinity3 = eff.GetWeaponAffinity(RpgWeaponCategory.Axes); float num4 = Mathf.Max(weaponAffinity, Mathf.Max(weaponAffinity2, weaponAffinity3)); float num5 = num4 * 0.25f; if (num4 < 0.1f) { num *= 0.7f; } return Mathf.Clamp01(num * num3 + num5); } private static float CalculateBerserkerAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector equip) { float num = eff.PhysicalPower * 0.6f + eff.Vitality * 0.2f + eff.StaminaMastery * 0.2f; float num2 = 0f; if (eff.PhysicalPower > eff.Defense + 0.15f) { num2 = Mathf.Clamp01((eff.PhysicalPower - (eff.Defense + 0.15f)) * 0.35f); } float weaponAffinity = eff.GetWeaponAffinity(RpgWeaponCategory.Axes); float weaponAffinity2 = eff.GetWeaponAffinity(RpgWeaponCategory.Clubs); float num3 = Mathf.Max(weaponAffinity, weaponAffinity2); float num4 = num3 * 0.2f; if (num3 < 0.1f) { num *= 0.65f; } float num5 = 1f; if (eff.Defense > 0.35f) { num5 = Mathf.Max(0.5f, 1f - (eff.Defense - 0.35f) * 1.2f); } return Mathf.Clamp01((num + num2 + num4) * num5); } private static float CalculateAssassinAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector perm, UniversalCapabilityVector equip) { float num = eff.Precision * 0.35f + eff.Mobility * 0.3f + eff.PhysicalPower * 0.2f + eff.StaminaMastery * 0.15f; float weaponAffinity = eff.GetWeaponAffinity(RpgWeaponCategory.Knives); float num2 = weaponAffinity * 0.25f; if (weaponAffinity < 0.1f) { num *= 0.6f; } float num3 = 1f; if (eff.Defense > 0.5f) { num3 = Mathf.Max(0.7f, 1f - (eff.Defense - 0.5f) * 0.6f); } return Mathf.Clamp01((num + num2) * num3); } private static float CalculateLancerAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector perm, UniversalCapabilityVector equip) { float weaponAffinity = eff.GetWeaponAffinity(RpgWeaponCategory.Spears); float weaponAffinity2 = eff.GetWeaponAffinity(RpgWeaponCategory.Polearms); float num = Mathf.Max(weaponAffinity, weaponAffinity2); float num2 = eff.StaminaMastery * 0.3f + eff.PhysicalPower * 0.25f + eff.Mobility * 0.25f + eff.Defense * 0.2f; float num3 = num * 0.4f; float num4 = num2 * 0.6f + num3; if (num < 0.1f) { num4 *= 0.5f; } return Mathf.Clamp01(num4); } private static float CalculateArcherAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector perm, UniversalCapabilityVector equip) { float weaponAffinity = eff.GetWeaponAffinity(RpgWeaponCategory.Bows); float weaponAffinity2 = eff.GetWeaponAffinity(RpgWeaponCategory.Crossbows); float num = Mathf.Max(weaponAffinity, weaponAffinity2); float num2 = eff.Precision * 0.35f + eff.Mobility * 0.25f + eff.StaminaMastery * 0.2f + eff.PhysicalPower * 0.2f; float num3 = num * 0.45f; float num4 = num2 * 0.55f + num3; if (num < 0.1f && eff.Precision < 0.2f) { num4 *= 0.4f; } return Mathf.Clamp01(num4); } private static float CalculateMageAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector perm, UniversalCapabilityVector equip) { float weaponAffinity = eff.GetWeaponAffinity(RpgWeaponCategory.MagicElemental); float weaponAffinity2 = eff.GetWeaponAffinity(RpgWeaponCategory.MagicBlood); float num = Mathf.Max(weaponAffinity, weaponAffinity2); float num2 = eff.Sorcery * 0.6f + eff.Precision * 0.15f + eff.StaminaMastery * 0.15f + eff.Vitality * 0.1f; float num3 = num * 0.25f; float num4 = num2 + num3; if (eff.Sorcery < 0.05f && num < 0.05f) { num4 = 0f; } return Mathf.Clamp01(num4); } private static float CalculateTamerAffinity(UniversalCapabilityVector eff, UniversalCapabilityVector perm) { float num = eff.CompanionAffinity * 0.65f + eff.Vitality * 0.2f + eff.StaminaMastery * 0.15f; if (eff.CompanionAffinity < 0.05f) { num *= 0.3f; } return Mathf.Clamp01(num); } private static ArchetypeClassificationResult CreateNeutralResult(string explanation) { ArchetypeClassificationResult archetypeClassificationResult = new ArchetypeClassificationResult(); archetypeClassificationResult.PrimaryArchetype = RpgArchetypeId.Neutral; archetypeClassificationResult.SecondaryArchetype = RpgArchetypeId.Neutral; archetypeClassificationResult.Confidence = 0f; archetypeClassificationResult.SpecializationIndex = 0f; archetypeClassificationResult.EffectivePowerLevel = 0f; archetypeClassificationResult.Tier = ArchetypeSpecializationTier.Novice; archetypeClassificationResult.DiagnosticExplanation = explanation; archetypeClassificationResult.AllAffinities[RpgArchetypeId.Neutral] = 1f; return archetypeClassificationResult; } } public sealed class RpgPlayerArchetypeTracker { public float HysteresisWindowSeconds = 5f; public float DominanceMarginThreshold = 0.08f; public RpgArchetypeId ActiveArchetype { get; private set; } public RpgArchetypeId CandidateArchetype { get; private set; } public RpgHybridIdentityId ActiveHybridIdentity { get; private set; } public RpgHybridIdentityId CandidateHybridIdentity { get; private set; } public RpgArchetypeId ActiveSecondaryArchetype { get; private set; } public float CandidateElapsedSeconds { get; private set; } public ArchetypeClassificationResult LastClassification { get; private set; } public bool IsLockedToUtilityTool { get; private set; } public string TrackedPlayerName { get; private set; } public RpgPlayerArchetypeTracker(float hysteresisSeconds = 5f) { HysteresisWindowSeconds = Mathf.Max(1f, hysteresisSeconds); Reset(null); } public void Reset(string newPlayerName = null) { TrackedPlayerName = newPlayerName; ActiveArchetype = RpgArchetypeId.Neutral; CandidateArchetype = RpgArchetypeId.Neutral; ActiveHybridIdentity = RpgHybridIdentityId.None; CandidateHybridIdentity = RpgHybridIdentityId.None; ActiveSecondaryArchetype = RpgArchetypeId.Neutral; CandidateElapsedSeconds = 0f; LastClassification = new ArchetypeClassificationResult(); IsLockedToUtilityTool = false; } public RpgArchetypeId Evaluate(RpgPlayerCapabilitySnapshot snapshot, float deltaTime) { if (snapshot == null) { return ActiveArchetype; } if (!string.IsNullOrEmpty(snapshot.PlayerName) && snapshot.PlayerName != TrackedPlayerName) { Reset(snapshot.PlayerName); } if (snapshot.ActiveWeaponCategory == RpgWeaponCategory.UtilityTool) { IsLockedToUtilityTool = true; CandidateElapsedSeconds = 0f; return ActiveArchetype; } IsLockedToUtilityTool = false; ArchetypeClassificationResult archetypeClassificationResult = (LastClassification = RpgArchetypeEngine.Classify(snapshot)); RpgArchetypeId primaryArchetype = archetypeClassificationResult.PrimaryArchetype; RpgHybridIdentityId hybridIdentity = archetypeClassificationResult.HybridIdentity; if (ActiveArchetype == RpgArchetypeId.Neutral) { if (primaryArchetype != RpgArchetypeId.Neutral) { ActiveArchetype = primaryArchetype; CandidateArchetype = primaryArchetype; ActiveHybridIdentity = hybridIdentity; CandidateHybridIdentity = hybridIdentity; ActiveSecondaryArchetype = archetypeClassificationResult.SecondaryArchetype; CandidateElapsedSeconds = 0f; } return ActiveArchetype; } if (primaryArchetype == ActiveArchetype && hybridIdentity == ActiveHybridIdentity) { CandidateArchetype = ActiveArchetype; CandidateHybridIdentity = ActiveHybridIdentity; ActiveSecondaryArchetype = archetypeClassificationResult.SecondaryArchetype; CandidateElapsedSeconds = 0f; return ActiveArchetype; } float affinity = archetypeClassificationResult.GetAffinity(ActiveArchetype); float affinity2 = archetypeClassificationResult.GetAffinity(primaryArchetype); if (affinity2 > affinity + DominanceMarginThreshold || primaryArchetype == RpgArchetypeId.Hybrid || hybridIdentity != ActiveHybridIdentity) { if (primaryArchetype == CandidateArchetype && hybridIdentity == CandidateHybridIdentity) { CandidateElapsedSeconds += deltaTime; if (CandidateElapsedSeconds >= HysteresisWindowSeconds) { ActiveArchetype = CandidateArchetype; ActiveHybridIdentity = CandidateHybridIdentity; ActiveSecondaryArchetype = archetypeClassificationResult.SecondaryArchetype; CandidateElapsedSeconds = 0f; } } else { CandidateArchetype = primaryArchetype; CandidateHybridIdentity = hybridIdentity; CandidateElapsedSeconds = deltaTime; } } else { CandidateElapsedSeconds = Mathf.Max(0f, CandidateElapsedSeconds - deltaTime * 0.5f); } return ActiveArchetype; } public void ForceSetArchetype(RpgArchetypeId archetype, RpgHybridIdentityId hybrid = RpgHybridIdentityId.None) { ActiveArchetype = archetype; CandidateArchetype = archetype; ActiveHybridIdentity = hybrid; CandidateHybridIdentity = hybrid; CandidateElapsedSeconds = 0f; } public void Reset() { ActiveArchetype = RpgArchetypeId.Neutral; CandidateArchetype = RpgArchetypeId.Neutral; ActiveHybridIdentity = RpgHybridIdentityId.None; CandidateHybridIdentity = RpgHybridIdentityId.None; ActiveSecondaryArchetype = RpgArchetypeId.Neutral; CandidateElapsedSeconds = 0f; IsLockedToUtilityTool = false; } } public enum RpgCapabilityType { Vitality, PhysicalPower, Defense, Mobility, StaminaMastery, Precision, Sorcery, WeaponMastery, CompanionAffinity, RangedPower, ElementalPower } public enum RpgWeaponCategory { None, Swords, Clubs, Axes, Polearms, Spears, Knives, Bows, Crossbows, MagicElemental, MagicBlood, Fists, UtilityTool } public enum CapabilityStatus { Valid, Zero, Unsupported, Unknown, NotAvailable, ReadError } public enum InformationLayer { PermanentProgression, ActiveEquipment, EffectiveStats, TemporaryBuffs } public struct RpgCapabilityMeasurement { public RpgCapabilityType CapabilityType; public InformationLayer Layer; public float RawValue; public float NormalizedValue; public string Unit; public CapabilityStatus Status; public string ProviderId; public string SourceDetail; public string ErrorMessage; public static RpgCapabilityMeasurement CreateValid(RpgCapabilityType type, InformationLayer layer, float raw, float normalized, string unit, string providerId, string detail = null) { return new RpgCapabilityMeasurement { CapabilityType = type, Layer = layer, RawValue = raw, NormalizedValue = Mathf.Clamp01(normalized), Unit = (unit ?? string.Empty), Status = ((raw == 0f) ? CapabilityStatus.Zero : CapabilityStatus.Valid), ProviderId = (providerId ?? "Unknown"), SourceDetail = (detail ?? string.Empty), ErrorMessage = string.Empty }; } public static RpgCapabilityMeasurement CreateZero(RpgCapabilityType type, InformationLayer layer, string providerId) { return new RpgCapabilityMeasurement { CapabilityType = type, Layer = layer, RawValue = 0f, NormalizedValue = 0f, Unit = string.Empty, Status = CapabilityStatus.Zero, ProviderId = (providerId ?? "Unknown"), SourceDetail = string.Empty, ErrorMessage = string.Empty }; } public static RpgCapabilityMeasurement CreateUnsupported(RpgCapabilityType type, InformationLayer layer, string providerId) { return new RpgCapabilityMeasurement { CapabilityType = type, Layer = layer, RawValue = 0f, NormalizedValue = 0f, Unit = string.Empty, Status = CapabilityStatus.Unsupported, ProviderId = (providerId ?? "Unknown"), SourceDetail = string.Empty, ErrorMessage = string.Empty }; } public static RpgCapabilityMeasurement CreateUnavailable(RpgCapabilityType type, InformationLayer layer, string providerId, CapabilityStatus status = CapabilityStatus.NotAvailable, string message = "") { return new RpgCapabilityMeasurement { CapabilityType = type, Layer = layer, RawValue = 0f, NormalizedValue = 0f, Unit = string.Empty, Status = status, ProviderId = (providerId ?? "Unknown"), SourceDetail = string.Empty, ErrorMessage = (message ?? string.Empty) }; } } public sealed class UniversalCapabilityVector { public float Vitality; public float PhysicalPower; public float Defense; public float Mobility; public float StaminaMastery; public float Precision; public float Sorcery; public float WeaponMastery; public float CompanionAffinity; public readonly Dictionary WeaponBreakdown = new Dictionary(); public readonly List Measurements = new List(); public float this[RpgCapabilityType type] { get { switch (type) { case RpgCapabilityType.Vitality: return Vitality; case RpgCapabilityType.PhysicalPower: return PhysicalPower; case RpgCapabilityType.Defense: return Defense; case RpgCapabilityType.Mobility: return Mobility; case RpgCapabilityType.StaminaMastery: return StaminaMastery; case RpgCapabilityType.Precision: return Precision; case RpgCapabilityType.Sorcery: case RpgCapabilityType.ElementalPower: return Sorcery; case RpgCapabilityType.WeaponMastery: case RpgCapabilityType.RangedPower: return WeaponMastery; case RpgCapabilityType.CompanionAffinity: return CompanionAffinity; default: return 0f; } } set { float num = Mathf.Clamp01(value); switch (type) { case RpgCapabilityType.Vitality: Vitality = num; break; case RpgCapabilityType.PhysicalPower: PhysicalPower = num; break; case RpgCapabilityType.Defense: Defense = num; break; case RpgCapabilityType.Mobility: Mobility = num; break; case RpgCapabilityType.StaminaMastery: StaminaMastery = num; break; case RpgCapabilityType.Precision: Precision = num; break; case RpgCapabilityType.Sorcery: case RpgCapabilityType.ElementalPower: Sorcery = num; break; case RpgCapabilityType.WeaponMastery: case RpgCapabilityType.RangedPower: WeaponMastery = num; break; case RpgCapabilityType.CompanionAffinity: CompanionAffinity = num; break; } } } public void SetWeaponBreakdown(RpgWeaponCategory category, float value) { WeaponBreakdown[category] = Mathf.Clamp01(value); } public float GetWeaponAffinity(RpgWeaponCategory category) { if (WeaponBreakdown.TryGetValue(category, out var value)) { return value; } return 0f; } public RpgWeaponCategory GetDominantWeaponCategory() { RpgWeaponCategory result = RpgWeaponCategory.None; float num = -1f; foreach (KeyValuePair item in WeaponBreakdown) { if (item.Key != RpgWeaponCategory.UtilityTool && item.Key != RpgWeaponCategory.None && item.Value > num) { num = item.Value; result = item.Key; } } return result; } public float GetPeakCapabilityValue() { return Mathf.Max(Vitality, Mathf.Max(PhysicalPower, Mathf.Max(Defense, Mathf.Max(Mobility, Mathf.Max(StaminaMastery, Mathf.Max(Precision, Mathf.Max(Sorcery, Mathf.Max(WeaponMastery, CompanionAffinity)))))))); } public RpgCapabilityType GetDominantCapability() { RpgCapabilityType result = RpgCapabilityType.Vitality; float num = Vitality; if (PhysicalPower > num) { num = PhysicalPower; result = RpgCapabilityType.PhysicalPower; } if (Defense > num) { num = Defense; result = RpgCapabilityType.Defense; } if (Mobility > num) { num = Mobility; result = RpgCapabilityType.Mobility; } if (StaminaMastery > num) { num = StaminaMastery; result = RpgCapabilityType.StaminaMastery; } if (Precision > num) { num = Precision; result = RpgCapabilityType.Precision; } if (Sorcery > num) { num = Sorcery; result = RpgCapabilityType.Sorcery; } if (WeaponMastery > num) { num = WeaponMastery; result = RpgCapabilityType.WeaponMastery; } if (CompanionAffinity > num) { num = CompanionAffinity; result = RpgCapabilityType.CompanionAffinity; } return result; } public void ClampAll() { Vitality = Mathf.Clamp01(Vitality); PhysicalPower = Mathf.Clamp01(PhysicalPower); Defense = Mathf.Clamp01(Defense); Mobility = Mathf.Clamp01(Mobility); StaminaMastery = Mathf.Clamp01(StaminaMastery); Precision = Mathf.Clamp01(Precision); Sorcery = Mathf.Clamp01(Sorcery); WeaponMastery = Mathf.Clamp01(WeaponMastery); CompanionAffinity = Mathf.Clamp01(CompanionAffinity); } public float GetTotalMagnitude() { return Vitality + PhysicalPower + Defense + Mobility + StaminaMastery + Precision + Sorcery + WeaponMastery + CompanionAffinity; } public bool IsSufficientlySpecialized(float threshold = 0.2f) { if (!(Vitality >= threshold) && !(PhysicalPower >= threshold) && !(Defense >= threshold) && !(Mobility >= threshold) && !(StaminaMastery >= threshold) && !(Precision >= threshold) && !(Sorcery >= threshold) && !(WeaponMastery >= threshold)) { return CompanionAffinity >= threshold; } return true; } public UniversalCapabilityVector Clone() { UniversalCapabilityVector universalCapabilityVector = new UniversalCapabilityVector(); universalCapabilityVector.Vitality = Vitality; universalCapabilityVector.PhysicalPower = PhysicalPower; universalCapabilityVector.Defense = Defense; universalCapabilityVector.Mobility = Mobility; universalCapabilityVector.StaminaMastery = StaminaMastery; universalCapabilityVector.Precision = Precision; universalCapabilityVector.Sorcery = Sorcery; universalCapabilityVector.WeaponMastery = WeaponMastery; universalCapabilityVector.CompanionAffinity = CompanionAffinity; UniversalCapabilityVector universalCapabilityVector2 = universalCapabilityVector; foreach (KeyValuePair item in WeaponBreakdown) { universalCapabilityVector2.WeaponBreakdown[item.Key] = item.Value; } universalCapabilityVector2.Measurements.AddRange(Measurements); return universalCapabilityVector2; } } public sealed class RpgPlayerCapabilitySnapshot { public string PlayerName = string.Empty; public DateTime TimestampUtc = DateTime.UtcNow; public UniversalCapabilityVector PermanentProgression = new UniversalCapabilityVector(); public UniversalCapabilityVector ActiveEquipment = new UniversalCapabilityVector(); public UniversalCapabilityVector EffectiveProfile = new UniversalCapabilityVector(); public readonly List TemporaryBuffs = new List(); public RpgWeaponCategory ActiveWeaponCategory; public string ActiveShieldType = "None"; public string ActiveArmorTier = "None"; public bool HasActiveCompanion; } public interface IRpgCapabilityProvider { string ProviderId { get; } string DisplayName { get; } string Version { get; } bool IsAvailable { get; } ExternalProviderCapabilities Capabilities { get; } void CollectPermanentCapabilities(object playerRef, List destination); void CollectEquipmentCapabilities(object playerRef, List destination); void CollectTemporaryCapabilities(object playerRef, List destination); } public static class RpgCapabilityProviderExtensions { public static void CollectPermanentCapabilities(this IRpgCapabilityProvider provider, Player player, List destination) { provider?.CollectPermanentCapabilities(player, destination); } public static void CollectEquipmentCapabilities(this IRpgCapabilityProvider provider, Player player, List destination) { provider?.CollectEquipmentCapabilities(player, destination); } public static void CollectTemporaryCapabilities(this IRpgCapabilityProvider provider, Player player, List destination) { provider?.CollectTemporaryCapabilities(player, destination); } } public sealed class VanillaRpgCapabilityProvider : IRpgCapabilityProvider { public const string ProviderGuid = "valheim.vanilla"; public string ProviderId => "valheim.vanilla"; public string DisplayName => "Valheim Vanilla Core"; public string Version => "0.221.x"; public bool IsAvailable => true; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.WorldDifficulty; public void CollectPermanentCapabilities(object playerRef, List destination) { if (destination != null) { if (playerRef == null) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.WeaponMastery, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Player is null")); } else { CollectPermanentCapabilitiesInternal(playerRef, destination); } } } [MethodImpl(MethodImplOptions.NoInlining)] private void CollectPermanentCapabilitiesInternal(object playerRef, List destination) { Player val = (Player)((playerRef is Player) ? playerRef : null); if ((Object)(object)val == (Object)null) { return; } try { float skillLevel = ((Character)val).GetSkillLevel((SkillType)1); float skillLevel2 = ((Character)val).GetSkillLevel((SkillType)3); float skillLevel3 = ((Character)val).GetSkillLevel((SkillType)7); float skillLevel4 = ((Character)val).GetSkillLevel((SkillType)4); float skillLevel5 = ((Character)val).GetSkillLevel((SkillType)5); float skillLevel6 = ((Character)val).GetSkillLevel((SkillType)2); float skillLevel7 = ((Character)val).GetSkillLevel((SkillType)8); float skillLevel8 = ((Character)val).GetSkillLevel((SkillType)14); float skillLevel9 = ((Character)val).GetSkillLevel((SkillType)6); float skillLevel10 = ((Character)val).GetSkillLevel((SkillType)102); float skillLevel11 = ((Character)val).GetSkillLevel((SkillType)100); float skillLevel12 = ((Character)val).GetSkillLevel((SkillType)101); float skillLevel13 = ((Character)val).GetSkillLevel((SkillType)9); float skillLevel14 = ((Character)val).GetSkillLevel((SkillType)10); float num = Mathf.Max(skillLevel, Mathf.Max(skillLevel2, Mathf.Max(skillLevel3, Mathf.Max(skillLevel4, Mathf.Max(skillLevel5, skillLevel6))))); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.PhysicalPower, InformationLayer.PermanentProgression, num, num / 100f, "SkillLevel", ProviderId, "Highest Melee Skill")); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Defense, InformationLayer.PermanentProgression, skillLevel9, skillLevel9 / 100f, "SkillLevel", ProviderId, "Blocking Skill")); float num2 = (skillLevel10 + skillLevel11) * 0.5f; destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Mobility, InformationLayer.PermanentProgression, num2, num2 / 100f, "SkillLevel", ProviderId, "Run/Jump Average")); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Precision, InformationLayer.PermanentProgression, skillLevel12, skillLevel12 / 100f, "SkillLevel", ProviderId, "Sneak Skill")); float num3 = Mathf.Max(skillLevel7, skillLevel8); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.RangedPower, InformationLayer.PermanentProgression, num3, num3 / 100f, "SkillLevel", ProviderId, "Bow/Crossbow Skill")); float num4 = Mathf.Max(skillLevel13, skillLevel14); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Sorcery, InformationLayer.PermanentProgression, num4, num4 / 100f, "SkillLevel", ProviderId, "Magic Skill")); } catch (Exception ex) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.WeaponMastery, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.ReadError, ex.Message)); } } public void CollectEquipmentCapabilities(object playerRef, List destination) { if (destination != null && playerRef != null) { CollectEquipmentCapabilitiesInternal(playerRef, destination); } } [MethodImpl(MethodImplOptions.NoInlining)] private void CollectEquipmentCapabilitiesInternal(object playerRef, List destination) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) Player val = (Player)((playerRef is Player) ? playerRef : null); if ((Object)(object)val == (Object)null) { return; } try { float bodyArmor = ((Character)val).GetBodyArmor(); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, bodyArmor, bodyArmor / 150f, "Armor", ProviderId, "Total Body Armor")); ItemData currentWeapon = ((Humanoid)val).GetCurrentWeapon(); if (currentWeapon != null && currentWeapon.m_shared != null) { DamageTypes damage = currentWeapon.GetDamage(); float totalDamage = ((DamageTypes)(ref damage)).GetTotalDamage(); RpgWeaponCategory rpgWeaponCategory = ResolveWeaponCategory(currentWeapon); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.PhysicalPower, InformationLayer.ActiveEquipment, totalDamage, totalDamage / 150f, "Damage", ProviderId, rpgWeaponCategory.ToString())); } ItemData val2 = ((Humanoid)val).LeftItem ?? ((Humanoid)val).GetCurrentWeapon(); if (val2 != null && val2.m_shared != null) { float blockPower = val2.GetBlockPower(((Character)val).GetSkillFactor((SkillType)6)); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, blockPower, blockPower / 250f, "BlockPower", ProviderId, val2.m_shared.m_name)); } } catch (Exception ex) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, ProviderId, CapabilityStatus.ReadError, ex.Message)); } } public void CollectTemporaryCapabilities(object playerRef, List destination) { if (destination != null && playerRef != null) { CollectTemporaryCapabilitiesInternal(playerRef, destination); } } [MethodImpl(MethodImplOptions.NoInlining)] private void CollectTemporaryCapabilitiesInternal(object playerRef, List destination) { Player val = (Player)((playerRef is Player) ? playerRef : null); if ((Object)(object)val == (Object)null) { return; } try { List foods = val.GetFoods(); if (foods == null) { return; } float num = 0f; float num2 = 0f; float num3 = 0f; foreach (Food item in foods) { num += item.m_health; num2 += item.m_stamina; num3 += item.m_eitr; } destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Vitality, InformationLayer.TemporaryBuffs, num, num / 300f, "HP", ProviderId, "Active Food")); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.StaminaMastery, InformationLayer.TemporaryBuffs, num2, num2 / 300f, "Stamina", ProviderId, "Active Food")); if (num3 > 0f) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Sorcery, InformationLayer.TemporaryBuffs, num3, num3 / 200f, "Eitr", ProviderId, "Active Food")); } } catch (Exception ex) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Vitality, InformationLayer.TemporaryBuffs, ProviderId, CapabilityStatus.ReadError, ex.Message)); } } public static RpgWeaponCategory ResolveWeaponCategory(ItemData item) { if (item == null || item.m_shared == null) { return RpgWeaponCategory.None; } return ResolveWeaponCategoryInternal(item); } [MethodImpl(MethodImplOptions.NoInlining)] private static RpgWeaponCategory ResolveWeaponCategoryInternal(ItemData item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected I4, but got Unknown SkillType skillType = item.m_shared.m_skillType; SkillType val = skillType; return (val - 1) switch { 0 => RpgWeaponCategory.Swords, 2 => RpgWeaponCategory.Clubs, 6 => RpgWeaponCategory.Axes, 3 => RpgWeaponCategory.Polearms, 4 => RpgWeaponCategory.Spears, 1 => RpgWeaponCategory.Knives, 7 => RpgWeaponCategory.Bows, 13 => RpgWeaponCategory.Crossbows, 8 => RpgWeaponCategory.MagicElemental, 9 => RpgWeaponCategory.MagicBlood, 10 => RpgWeaponCategory.Fists, 11 => RpgWeaponCategory.UtilityTool, _ => RpgWeaponCategory.None, }; } public static bool IsUtilityToolName(string name) { if (string.IsNullOrEmpty(name)) { return false; } string text = name.ToLowerInvariant(); if (!text.Contains("pickaxe") && !text.Contains("hammer") && !text.Contains("hoe") && !text.Contains("cultivator")) { return text.Contains("fishingrod"); } return true; } } public sealed class EpicMmoCapabilityProvider : IRpgCapabilityProvider { public string ProviderId => "WackyMole.EpicMMOSystem"; public string DisplayName => "EpicMMOSystem"; public string Version => "1.x"; public bool IsAvailable => EpicMMOAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.ProgressionAttributes; public void CollectPermanentCapabilities(object playerRef, List destination) { if (destination == null) { return; } if (!IsAvailable) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.PhysicalPower, InformationLayer.PermanentProgression, ProviderId)); return; } try { int value; bool flag = EpicMMOAdapter.TryQueryLocalPlayerAttribute("Strength", out value); int value2; bool flag2 = EpicMMOAdapter.TryQueryLocalPlayerAttribute("Dexterity", out value2); int value3; bool flag3 = EpicMMOAdapter.TryQueryLocalPlayerAttribute("Intelligence", out value3); int value4; bool flag4 = EpicMMOAdapter.TryQueryLocalPlayerAttribute("Endurance", out value4); int value5; bool flag5 = EpicMMOAdapter.TryQueryLocalPlayerAttribute("Vigour", out value5); int value6; bool flag6 = EpicMMOAdapter.TryQueryLocalPlayerAttribute("Specializing", out value6); if (flag) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.PhysicalPower, InformationLayer.PermanentProgression, value, (float)value / 200f, "Points", ProviderId, "Strength")); } else { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.PhysicalPower, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); } if (flag2) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Mobility, InformationLayer.PermanentProgression, value2, (float)value2 / 200f, "Points", ProviderId, "Dexterity")); } else { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Mobility, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); } if (flag3) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Sorcery, InformationLayer.PermanentProgression, value3, (float)value3 / 200f, "Points", ProviderId, "Intelligence")); } else { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Sorcery, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); } if (flag4) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Defense, InformationLayer.PermanentProgression, value4, (float)value4 / 200f, "Points", ProviderId, "Endurance (Armor)")); destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.StaminaMastery, InformationLayer.PermanentProgression, value4, (float)value4 / 200f, "Points", ProviderId, "Endurance (Stamina)")); } else { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Defense, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.StaminaMastery, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); } if (flag5) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Vitality, InformationLayer.PermanentProgression, value5, (float)value5 / 200f, "Points", ProviderId, "Vigour")); } else { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Vitality, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); } if (flag6) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Precision, InformationLayer.PermanentProgression, value6, (float)value6 / 200f, "Points", ProviderId, "Specializing")); } else { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Precision, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.Unknown, "Attribute not initialized")); } } catch (Exception ex) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.PhysicalPower, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.ReadError, ex.Message)); } } public void CollectEquipmentCapabilities(object playerRef, List destination) { destination?.Add(RpgCapabilityMeasurement.CreateUnsupported(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, ProviderId)); } public void CollectTemporaryCapabilities(object playerRef, List destination) { destination?.Add(RpgCapabilityMeasurement.CreateUnsupported(RpgCapabilityType.Vitality, InformationLayer.TemporaryBuffs, ProviderId)); } } public sealed class EpicLootCapabilityProvider : IRpgCapabilityProvider { public string ProviderId => "randyknapp.mods.epicloot"; public string DisplayName => "EpicLoot"; public string Version => "1.x"; public bool IsAvailable => EpicLootAdapter.IsAvailable; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.MagicAffixes | ExternalProviderCapabilities.LootScaling; public void CollectPermanentCapabilities(object playerRef, List destination) { destination?.Add(RpgCapabilityMeasurement.CreateUnsupported(RpgCapabilityType.Vitality, InformationLayer.PermanentProgression, ProviderId)); } public void CollectEquipmentCapabilities(object playerRef, List destination) { if (destination != null) { if (!IsAvailable) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, ProviderId)); } else if (playerRef == null) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, ProviderId, CapabilityStatus.Unknown, "Player is null")); } else { CollectEquipmentCapabilitiesInternal(playerRef, destination); } } } [MethodImpl(MethodImplOptions.NoInlining)] private void CollectEquipmentCapabilitiesInternal(object playerRef, List destination) { try { int num = 0; int num2 = 0; MethodInfo methodInfo = playerRef?.GetType().GetMethod("GetInventory", BindingFlags.Instance | BindingFlags.Public); object obj = ((methodInfo != null) ? methodInfo.Invoke(playerRef, null) : null); if (obj != null) { MethodInfo method = obj.GetType().GetMethod("GetEquippedItems", BindingFlags.Instance | BindingFlags.Public); IEnumerable enumerable = ((method != null) ? (method.Invoke(obj, null) as IEnumerable) : null); Type type = Type.GetType("EpicLoot.ItemDataExtensions, EpicLoot", throwOnError: false); MethodInfo methodInfo2 = ((type != null) ? AccessTools.Method(type, "IsMagic", (Type[])null, (Type[])null) : null); MethodInfo methodInfo3 = ((type != null) ? AccessTools.Method(type, "GetMagicEffects", (Type[])null, (Type[])null) : null); if (enumerable != null) { foreach (object item in enumerable) { if (item == null) { continue; } bool flag = false; if (methodInfo2 != null) { object obj2 = methodInfo2.Invoke(null, new object[1] { item }); if (obj2 is bool) { flag = (bool)obj2; } } else { FieldInfo field = item.GetType().GetField("m_customData"); Dictionary dictionary = ((field != null) ? (field.GetValue(item) as Dictionary) : null); if (dictionary != null && dictionary.ContainsKey("MagicItemComponent")) { flag = true; } } if (!flag) { continue; } num++; if (methodInfo3 != null) { if (methodInfo3.Invoke(null, new object[1] { item }) is IList list) { num2 += list.Count; } } else { num2++; } } } } if (num > 0) { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, num, Mathf.Clamp01((float)num / 6f), "Items", ProviderId, $"Equipamiento Mágico: {num} piezas ({num2} afijos)")); } else { destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, 0f, 0f, "Items", ProviderId, "Sin equipamiento mágico activo")); } } catch (Exception ex) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, ProviderId, CapabilityStatus.ReadError, ex.Message)); } } public void CollectTemporaryCapabilities(object playerRef, List destination) { destination?.Add(RpgCapabilityMeasurement.CreateUnsupported(RpgCapabilityType.Vitality, InformationLayer.TemporaryBuffs, ProviderId)); } } public sealed class TameMateMasteriesCapabilityProvider : IRpgCapabilityProvider { public const string ProviderGuid = "tamemate.masteries"; public string ProviderId => "tamemate.masteries"; public string DisplayName => "TameMate Masteries & Lineages"; public string Version => "0.8.0"; public bool IsAvailable => true; public ExternalProviderCapabilities Capabilities => ExternalProviderCapabilities.CreatureScaling; public void CollectPermanentCapabilities(object playerRef, List destination) { if (destination == null) { return; } try { float num = 0f; if (playerRef != null) { num = ExtractTamerRank(playerRef); } destination.Add(RpgCapabilityMeasurement.CreateValid(RpgCapabilityType.CompanionAffinity, InformationLayer.PermanentProgression, num, num / 5f, "MasteryRank", ProviderId, "Tamer Rank")); } catch (Exception ex) { destination.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.CompanionAffinity, InformationLayer.PermanentProgression, ProviderId, CapabilityStatus.ReadError, ex.Message)); } } [MethodImpl(MethodImplOptions.NoInlining)] private float ExtractTamerRank(object playerRef) { Player val = (Player)((playerRef is Player) ? playerRef : null); if ((Object)(object)val != (Object)null && val.m_customData != null) { int result2; if (val.m_customData.TryGetValue("TM_Rank_MasterTamer", out var value)) { if (int.TryParse(value, out var result)) { return result; } } else if (val.m_customData.TryGetValue("TM_Rank_BeastKing", out value) && int.TryParse(value, out result2)) { return result2; } } return 0f; } public void CollectEquipmentCapabilities(object playerRef, List destination) { destination?.Add(RpgCapabilityMeasurement.CreateUnsupported(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, ProviderId)); } public void CollectTemporaryCapabilities(object playerRef, List destination) { destination?.Add(RpgCapabilityMeasurement.CreateUnsupported(RpgCapabilityType.Vitality, InformationLayer.TemporaryBuffs, ProviderId)); } } public static class RpgCapabilityRegistry { private static readonly object s_registryLock; private static readonly Dictionary s_providers; static RpgCapabilityRegistry() { s_registryLock = new object(); s_providers = new Dictionary(StringComparer.OrdinalIgnoreCase); RegisterDefaultProviders(); } public static void Initialize() { RegisterDefaultProviders(); } public static void RegisterDefaultProviders() { lock (s_registryLock) { s_providers.Clear(); RegisterProviderInternal(new VanillaRpgCapabilityProvider()); RegisterProviderInternal(new EpicMmoCapabilityProvider()); RegisterProviderInternal(new EpicLootCapabilityProvider()); RegisterProviderInternal(new TameMateMasteriesCapabilityProvider()); } } public static void RegisterProvider(IRpgCapabilityProvider provider) { if (provider == null || string.IsNullOrEmpty(provider.ProviderId)) { return; } lock (s_registryLock) { RegisterProviderInternal(provider); } } private static void RegisterProviderInternal(IRpgCapabilityProvider provider) { s_providers[provider.ProviderId] = provider; } public static bool UnregisterProvider(string providerId) { if (string.IsNullOrEmpty(providerId)) { return false; } lock (s_registryLock) { return s_providers.Remove(providerId); } } public static IRpgCapabilityProvider GetProvider(string providerIdOrAlias) { if (string.IsNullOrEmpty(providerIdOrAlias)) { return null; } lock (s_registryLock) { if (s_providers.TryGetValue(providerIdOrAlias, out var value)) { return value; } foreach (KeyValuePair s_provider in s_providers) { if (string.Equals(s_provider.Key, providerIdOrAlias, StringComparison.OrdinalIgnoreCase) || string.Equals(s_provider.Value.DisplayName, providerIdOrAlias, StringComparison.OrdinalIgnoreCase) || s_provider.Value.GetType().Name.StartsWith(providerIdOrAlias, StringComparison.OrdinalIgnoreCase) || s_provider.Key.IndexOf(providerIdOrAlias, StringComparison.OrdinalIgnoreCase) >= 0) { return s_provider.Value; } } return null; } } public static List GetAllProviders() { lock (s_registryLock) { return new List(s_providers.Values); } } public static RpgPlayerCapabilitySnapshot CapturePlayerSnapshot(object playerRef = null) { return CaptureSnapshot(playerRef); } public static RpgPlayerCapabilitySnapshot CaptureSnapshot(object playerRef = null) { RpgPlayerCapabilitySnapshot rpgPlayerCapabilitySnapshot = new RpgPlayerCapabilitySnapshot(); if (playerRef != null) { PopulatePlayerVisuals(rpgPlayerCapabilitySnapshot, playerRef); } List list = new List(); List list2 = new List(); List list3 = new List(); List allProviders = GetAllProviders(); for (int i = 0; i < allProviders.Count; i++) { IRpgCapabilityProvider rpgCapabilityProvider = allProviders[i]; if (rpgCapabilityProvider != null) { try { rpgCapabilityProvider.CollectPermanentCapabilities(playerRef, list); } catch (Exception ex) { list.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.PhysicalPower, InformationLayer.PermanentProgression, rpgCapabilityProvider.ProviderId, CapabilityStatus.ReadError, ex.Message)); } try { rpgCapabilityProvider.CollectEquipmentCapabilities(playerRef, list2); } catch (Exception ex2) { list2.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Defense, InformationLayer.ActiveEquipment, rpgCapabilityProvider.ProviderId, CapabilityStatus.ReadError, ex2.Message)); } try { rpgCapabilityProvider.CollectTemporaryCapabilities(playerRef, list3); } catch (Exception ex3) { list3.Add(RpgCapabilityMeasurement.CreateUnavailable(RpgCapabilityType.Vitality, InformationLayer.TemporaryBuffs, rpgCapabilityProvider.ProviderId, CapabilityStatus.ReadError, ex3.Message)); } } } AggregateVector(rpgPlayerCapabilitySnapshot.PermanentProgression, list); AggregateVector(rpgPlayerCapabilitySnapshot.ActiveEquipment, list2); SynthesizeEffectiveProfile(rpgPlayerCapabilitySnapshot); rpgPlayerCapabilitySnapshot.TemporaryBuffs.AddRange(list3); return rpgPlayerCapabilitySnapshot; } [MethodImpl(MethodImplOptions.NoInlining)] private static void PopulatePlayerVisuals(RpgPlayerCapabilitySnapshot snap, object playerRef) { Player val = (Player)((playerRef is Player) ? playerRef : null); if (!((Object)(object)val == (Object)null)) { snap.PlayerName = val.GetPlayerName() ?? "Unknown"; ItemData currentWeapon = ((Humanoid)val).GetCurrentWeapon(); if (currentWeapon != null) { snap.ActiveWeaponCategory = VanillaRpgCapabilityProvider.ResolveWeaponCategory(currentWeapon); } ItemData val2 = ((Humanoid)val).LeftItem ?? ((Humanoid)val).GetCurrentWeapon(); if (val2 != null && val2.m_shared != null) { snap.ActiveShieldType = val2.m_shared.m_name; } } } private static void AggregateVector(UniversalCapabilityVector target, List measurements) { if (target == null || measurements == null) { return; } target.Measurements.AddRange(measurements); float num = 0f; float num2 = 0f; float num3 = 0f; float num4 = 0f; float num5 = 0f; float num6 = 0f; float num7 = 0f; float num8 = 0f; float num9 = 0f; float num10 = 0f; float num11 = 0f; float num12 = 0f; float num13 = 0f; float num14 = 0f; float num15 = 0f; float num16 = 0f; float num17 = 0f; float num18 = 0f; for (int i = 0; i < measurements.Count; i++) { RpgCapabilityMeasurement rpgCapabilityMeasurement = measurements[i]; if (rpgCapabilityMeasurement.Status == CapabilityStatus.Valid || rpgCapabilityMeasurement.Status == CapabilityStatus.Zero) { switch (rpgCapabilityMeasurement.CapabilityType) { case RpgCapabilityType.Vitality: num += rpgCapabilityMeasurement.NormalizedValue; num2 += 1f; break; case RpgCapabilityType.PhysicalPower: num3 += rpgCapabilityMeasurement.NormalizedValue; num4 += 1f; break; case RpgCapabilityType.Defense: num5 += rpgCapabilityMeasurement.NormalizedValue; num6 += 1f; break; case RpgCapabilityType.Mobility: num7 += rpgCapabilityMeasurement.NormalizedValue; num8 += 1f; break; case RpgCapabilityType.StaminaMastery: num9 += rpgCapabilityMeasurement.NormalizedValue; num10 += 1f; break; case RpgCapabilityType.Precision: num11 += rpgCapabilityMeasurement.NormalizedValue; num12 += 1f; break; case RpgCapabilityType.Sorcery: case RpgCapabilityType.ElementalPower: num13 += rpgCapabilityMeasurement.NormalizedValue; num14 += 1f; break; case RpgCapabilityType.WeaponMastery: num15 += rpgCapabilityMeasurement.NormalizedValue; num16 += 1f; break; case RpgCapabilityType.CompanionAffinity: num17 += rpgCapabilityMeasurement.NormalizedValue; num18 += 1f; break; } } } if (num2 > 0f) { target.Vitality = num / num2; } if (num4 > 0f) { target.PhysicalPower = num3 / num4; } if (num6 > 0f) { target.Defense = num5 / num6; } if (num8 > 0f) { target.Mobility = num7 / num8; } if (num10 > 0f) { target.StaminaMastery = num9 / num10; } if (num12 > 0f) { target.Precision = num11 / num12; } if (num14 > 0f) { target.Sorcery = num13 / num14; } if (num16 > 0f) { target.WeaponMastery = num15 / num16; } if (num18 > 0f) { target.CompanionAffinity = num17 / num18; } target.ClampAll(); } public static UniversalCapabilityVector CalculateEffectiveVector(UniversalCapabilityVector permanent, UniversalCapabilityVector equipment) { UniversalCapabilityVector universalCapabilityVector = permanent ?? new UniversalCapabilityVector(); UniversalCapabilityVector universalCapabilityVector2 = equipment ?? new UniversalCapabilityVector(); UniversalCapabilityVector universalCapabilityVector3 = new UniversalCapabilityVector(); universalCapabilityVector3.Vitality = Mathf.Clamp01(universalCapabilityVector.Vitality * 0.7f + universalCapabilityVector2.Vitality * 0.3f); universalCapabilityVector3.PhysicalPower = Mathf.Clamp01(universalCapabilityVector.PhysicalPower * 0.5f + universalCapabilityVector2.PhysicalPower * 0.5f); universalCapabilityVector3.Defense = Mathf.Clamp01(universalCapabilityVector.Defense * 0.4f + universalCapabilityVector2.Defense * 0.6f); universalCapabilityVector3.Mobility = Mathf.Clamp01(universalCapabilityVector.Mobility * 0.7f + universalCapabilityVector2.Mobility * 0.3f); universalCapabilityVector3.StaminaMastery = Mathf.Clamp01(universalCapabilityVector.StaminaMastery * 0.7f + universalCapabilityVector2.StaminaMastery * 0.3f); universalCapabilityVector3.Precision = Mathf.Clamp01(universalCapabilityVector.Precision * 0.6f + universalCapabilityVector2.Precision * 0.4f); universalCapabilityVector3.Sorcery = Mathf.Clamp01(universalCapabilityVector.Sorcery * 0.6f + universalCapabilityVector2.Sorcery * 0.4f); universalCapabilityVector3.WeaponMastery = Mathf.Clamp01(universalCapabilityVector.WeaponMastery * 0.6f + universalCapabilityVector2.WeaponMastery * 0.4f); universalCapabilityVector3.CompanionAffinity = Mathf.Clamp01(universalCapabilityVector.CompanionAffinity); foreach (KeyValuePair item in universalCapabilityVector.WeaponBreakdown) { universalCapabilityVector3.WeaponBreakdown[item.Key] = item.Value; } foreach (KeyValuePair item2 in universalCapabilityVector2.WeaponBreakdown) { float weaponAffinity = universalCapabilityVector3.GetWeaponAffinity(item2.Key); universalCapabilityVector3.WeaponBreakdown[item2.Key] = Mathf.Max(weaponAffinity, item2.Value); } universalCapabilityVector3.ClampAll(); return universalCapabilityVector3; } private static void SynthesizeEffectiveProfile(RpgPlayerCapabilitySnapshot snap) { snap.EffectiveProfile = CalculateEffectiveVector(snap.PermanentProgression, snap.ActiveEquipment); } } public enum RpgCodexCategory { Identity, Attributes, Affinities, Masteries, Providers } public struct LiveCombatStats { public float CurrentHealth; public float MaxHealth; public float CurrentStamina; public float MaxStamina; public float CurrentEitr; public float MaxEitr; public float BodyArmor; public float BlockPower; public string EquippedWeaponName; public string EquippedShieldName; public static LiveCombatStats Capture(object playerRef) { LiveCombatStats stats = default(LiveCombatStats); if (playerRef == null) { return stats; } CaptureInternal(playerRef, ref stats); return stats; } [MethodImpl(MethodImplOptions.NoInlining)] private static void CaptureInternal(object playerRef, ref LiveCombatStats stats) { Player val = (Player)((playerRef is Player) ? playerRef : null); if ((Object)(object)val == (Object)null) { return; } try { stats.CurrentHealth = ((Character)val).GetHealth(); stats.MaxHealth = ((Character)val).GetMaxHealth(); } catch { } try { stats.CurrentStamina = val.GetStamina(); stats.MaxStamina = ((Character)val).GetMaxStamina(); } catch { } try { stats.CurrentEitr = val.GetEitr(); stats.MaxEitr = ((Character)val).GetMaxEitr(); } catch { } try { stats.BodyArmor = ((Character)val).GetBodyArmor(); } catch { } try { ItemData currentWeapon = ((Humanoid)val).GetCurrentWeapon(); if (currentWeapon != null && currentWeapon.m_shared != null) { stats.EquippedWeaponName = ((Localization.instance != null) ? Localization.instance.Localize(currentWeapon.m_shared.m_name) : currentWeapon.m_shared.m_name); } } catch { } try { ItemData leftItem = ((Humanoid)val).LeftItem; if (leftItem != null && leftItem.m_shared != null) { stats.EquippedShieldName = ((Localization.instance != null) ? Localization.instance.Localize(leftItem.m_shared.m_name) : leftItem.m_shared.m_name); float num = (((Object)(object)((Character)val).GetSkills() != (Object)null) ? ((Character)val).GetSkills().GetSkillFactor((SkillType)6) : 0f); stats.BlockPower = leftItem.GetBlockPower(num); } } catch { } } } public struct LiveMasteryInfo { public MasteryId Id; public string Name; public string Category; public string Summary; public MasteryRank CurrentRank; public int CurrentProgress; public int RequiredProgress; public string RankTitle; public string RankPerks; public string NextQuest; public static List CaptureAll(object playerRef) { List list = new List(); try { if (MasteriesSystem.Catalog == null) { return list; } foreach (KeyValuePair item2 in MasteriesSystem.Catalog) { MasteryDefinition value = item2.Value; if (value != null) { LiveMasteryInfo item = new LiveMasteryInfo { Id = value.Id, Name = value.GetName(), Category = value.GetCategory(), Summary = value.GetSummary() }; if (playerRef != null) { CapturePlayerMasteryRank(value, playerRef, out item.CurrentRank, out item.CurrentProgress); } else { item.CurrentRank = MasteryRank.Locked; item.CurrentProgress = 0; } if (value.Ranks.TryGetValue(item.CurrentRank, out var value2) && value2 != null) { item.RankTitle = value2.GetTitle(); item.RankPerks = value2.GetPerks(); item.RequiredProgress = value2.RequiredAmount; item.NextQuest = value2.GetQuestDesc(); } else { item.RankTitle = item.CurrentRank.ToString(); item.RankPerks = string.Empty; item.RequiredProgress = 0; item.NextQuest = string.Empty; } list.Add(item); } } } catch { } if (list.Count == 0) { PopulateFallbackMasteryList(list); } return list; } private static void PopulateFallbackMasteryList(List list) { Tuple[] array = new Tuple[8] { Tuple.Create(MasteryId.BeastKing, "Rey de las Bestias", "Criaturas", "Liderazgo sobre fieras salvajes."), Tuple.Create(MasteryId.FeralBastion, "Baluarte Feral", "Criaturas", "Resistencia y mitigación para compañeros."), Tuple.Create(MasteryId.AlphaBloodline, "Linaje Alfa", "Criaturas", "Mejora genética en crianza."), Tuple.Create(MasteryId.StormBeasts, "Bestias de Tormenta", "Criaturas", "Poder elemental en bestias."), Tuple.Create(MasteryId.MasterTamer, "Maestro Domador", "Jugador", "Velocidad y eficacia en doma."), Tuple.Create(MasteryId.GrandCavalier, "Gran Jinete", "Jugador", "Dominio absoluto de monturas."), Tuple.Create(MasteryId.ApexTracker, "Rastreador Ápice", "Jugador", "Detección y velocidad en exploración."), Tuple.Create(MasteryId.BeastShaman, "Chamán Bestial", "Jugador", "Vínculo místico con manadas.") }; foreach (Tuple tuple in array) { list.Add(new LiveMasteryInfo { Id = tuple.Item1, Name = tuple.Item2, Category = tuple.Item3, Summary = tuple.Item4, CurrentRank = MasteryRank.Locked, RankTitle = "Bloqueado", RankPerks = string.Empty, CurrentProgress = 0, RequiredProgress = 100, NextQuest = "Desbloquear rango Iniciado" }); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void CapturePlayerMasteryRank(MasteryDefinition def, object playerRef, out MasteryRank rank, out int progress) { Player val = (Player)((playerRef is Player) ? playerRef : null); if ((Object)(object)val != (Object)null && def != null) { rank = def.GetRank(val); progress = def.GetProgress(val); } else { rank = MasteryRank.Locked; progress = 0; } } } public struct LiveProviderInfo { public string ProviderId; public string DisplayName; public bool IsActive; public ExternalProviderCapabilities Capabilities; public ProviderResponsibility Responsibility; public string ActiveMetrics; public static List CaptureAll() { List list = new List(); try { List allProviders = ExternalStatCatalog.GetAllProviders(); CombatCalculationContext context = CombatCalculationContext.CreateDefault(); for (int i = 0; i < allProviders.Count; i++) { IExternalStatProvider externalStatProvider = allProviders[i]; if (externalStatProvider == null) { continue; } LiveProviderInfo item = new LiveProviderInfo { ProviderId = externalStatProvider.ProviderId, DisplayName = externalStatProvider.DisplayName, IsActive = externalStatProvider.IsActive, Capabilities = externalStatProvider.Capabilities, Responsibility = externalStatProvider.Responsibility }; if (externalStatProvider.IsActive) { try { externalStatProvider.CollectModifiers(ref context); } catch { } item.ActiveMetrics = FormatActiveMetrics(externalStatProvider, context); } else { item.ActiveMetrics = (RpgCodexLocalization.IsSpanish ? "No detectado en el perfil activo (capacidades aisladas)" : "Not detected in active profile (capabilities isolated)"); } list.Add(item); } } catch { } return list; } private static string FormatActiveMetrics(IExternalStatProvider provider, CombatCalculationContext ctx) { if (provider is VanillaWorldStatProvider) { return $"PlayerDmg: {ctx.PlayerDamageRate:F2}x | EnemyDmg: {ctx.EnemyDamageRate:F2}x"; } if (provider is SlsStatProvider) { return $"HP/★: +{ctx.HealthMultiplierPerStar:P0} | Dmg/★: +{ctx.DamageMultiplierPerStar:P0}"; } if (provider is EpicMmoStatProvider) { return $"PhysDmg/Pto: +{ctx.PhysicalDamagePerPoint:F2} | Armor/Pto: +{ctx.ArmorPerPoint:F2} | HP/Pto: +{ctx.HealthPerPoint:F1}"; } if (provider is EpicLootStatProvider) { return "Afijos Mágicos y Botín Progresivo Activos"; } if (provider is BossAddStatProvider) { return $"Boss HP Mult: {ctx.BossHealthMultiplier:F2}x | Speed: {ctx.BossAttackSpeedMultiplier:F2}x"; } if (provider is MonsterDbStatProvider) { return "Prefabs Personalizados y Variantes MonsterDB"; } return "Coexistencia pasiva verificada sin conflictos"; } } public static class RpgCodexLocalization { public static bool IsSpanish { get { try { return Localization.instance == null || Localization.instance.GetSelectedLanguage() == "Spanish"; } catch { return true; } } } public static string GetWindowTitle() { if (!IsSpanish) { return "Character Codex | Adaptive RPG Archetypes (v0.8.0)"; } return "Códice del Personaje | Adaptive RPG Archetypes (v0.8.0)"; } public static string GetWindowSubtitle() { if (!IsSpanish) { return "Dynamic Profile, Specializations and Dimensional Capability Analysis"; } return "Perfil Dinámico, Especializaciones y Análisis Dimensional de Capacidades"; } public static string GetCategoryTitle(RpgCodexCategory cat) { switch (cat) { case RpgCodexCategory.Identity: if (!IsSpanish) { return "Identity"; } return "Identidad"; case RpgCodexCategory.Attributes: if (!IsSpanish) { return "Attributes"; } return "Atributos"; case RpgCodexCategory.Affinities: if (!IsSpanish) { return "Affinities"; } return "Afinidades"; case RpgCodexCategory.Masteries: if (!IsSpanish) { return "Masteries"; } return "Maestrías"; case RpgCodexCategory.Providers: if (!IsSpanish) { return "Providers"; } return "Proveedores"; default: return cat.ToString(); } } public static string GetCapabilityDisplayName(RpgCapabilityType type) { return GetCapabilityDisplayName(type.ToString()); } public static string GetCapabilityDisplayName(string capName) { if (string.IsNullOrEmpty(capName)) { return string.Empty; } if (!IsSpanish) { return capName; } return capName.Trim().ToLowerInvariant() switch { "vitality" => "Vitalidad (Salud Máxima)", "physicalpower" => "Poder Físico", "defense" => "Defensa", "mobility" => "Movilidad", "staminamastery" => "Maestría de Aguante", "precision" => "Precisión", "sorcery" => "Hechicería", "companionaffinity" => "Afinidad de Compañeros", "weaponmastery" => "Maestría de Armas", "blockpower" => "Poder de Bloqueo", "damagemitigation" => "Mitigación de Daño", "eitrefficiency" => "Eficiencia de Eitr", _ => capName, }; } public static string GetResponsibilityTitle(ProviderResponsibility resp) { if (!IsSpanish) { return resp.ToString(); } return resp switch { ProviderResponsibility.ConfigurableByTameMate => "Gobernanza de TameMate", ProviderResponsibility.ReadOnlyDataProvider => "Proveedor Solo Lectura", ProviderResponsibility.PassiveCoexistence => "Coexistencia Pasiva", ProviderResponsibility.Exclusive => "Autoridad Exclusiva", ProviderResponsibility.Cumulative => "Multiplicador Acumulativo", ProviderResponsibility.ConflictDetected => "Conflicto Detectado", _ => resp.ToString(), }; } public static string GetCapabilitiesSummary(ExternalProviderCapabilities caps) { if (!IsSpanish) { return caps.ToString(); } List list = new List(); if ((caps & ExternalProviderCapabilities.WorldDifficulty) != ExternalProviderCapabilities.None) { list.Add("Dificultad de Mundo"); } if ((caps & ExternalProviderCapabilities.CreatureScaling) != ExternalProviderCapabilities.None) { list.Add("Escalado de Criaturas"); } if ((caps & ExternalProviderCapabilities.ProgressionAttributes) != ExternalProviderCapabilities.None) { list.Add("Atributos de Progresión"); } if ((caps & ExternalProviderCapabilities.MagicAffixes) != ExternalProviderCapabilities.None) { list.Add("Afijos Mágicos"); } if ((caps & ExternalProviderCapabilities.LootScaling) != ExternalProviderCapabilities.None) { list.Add("Escalado de Botín"); } if ((caps & ExternalProviderCapabilities.CustomPrefabs) != ExternalProviderCapabilities.None) { list.Add("Prefabs Personalizados"); } if ((caps & ExternalProviderCapabilities.BossMechanics) != ExternalProviderCapabilities.None) { list.Add("Mecánicas de Jefes"); } if ((caps & ExternalProviderCapabilities.EnginePerformance) != ExternalProviderCapabilities.None) { list.Add("Rendimiento del Motor"); } if (list.Count <= 0) { return "Ninguna"; } return string.Join(", ", list.ToArray()); } public static string GetTierName(ArchetypeSpecializationTier tier) { switch (tier) { case ArchetypeSpecializationTier.Novice: if (!IsSpanish) { return "Novice"; } return "Novato"; case ArchetypeSpecializationTier.Developing: if (!IsSpanish) { return "Developing"; } return "En Desarrollo"; case ArchetypeSpecializationTier.Specialized: if (!IsSpanish) { return "Specialized"; } return "Especializado"; case ArchetypeSpecializationTier.Master: if (!IsSpanish) { return "Master"; } return "Maestro"; default: return tier.ToString(); } } public static string GetArchetypeName(RpgArchetypeId id) { switch (id) { case RpgArchetypeId.Tank: if (!IsSpanish) { return "Bulwark Tank"; } return "Tanque Baluarte"; case RpgArchetypeId.Warrior: if (!IsSpanish) { return "Disciplined Warrior"; } return "Guerrero Disciplinado"; case RpgArchetypeId.Berserker: if (!IsSpanish) { return "Frenzied Berserker"; } return "Berserker Feroz"; case RpgArchetypeId.Assassin: if (!IsSpanish) { return "Surgical Assassin"; } return "Asesino Quirúrgico"; case RpgArchetypeId.Lancer: if (!IsSpanish) { return "Vanguard Lancer"; } return "Lancero de Choque"; case RpgArchetypeId.Archer: if (!IsSpanish) { return "Skirmish Archer"; } return "Arquero Hostigador"; case RpgArchetypeId.Mage: if (!IsSpanish) { return "Arcane Mage"; } return "Mago Arcano"; case RpgArchetypeId.Tamer: if (!IsSpanish) { return "Pack Tamer"; } return "Domador de Manadas"; case RpgArchetypeId.Hybrid: if (!IsSpanish) { return "Hybrid Specialization"; } return "Especialización Híbrida"; default: if (!IsSpanish) { return "Neutral (Unspecialized)"; } return "Neutral (Sin Especialización)"; } } public static string GetStateTitle(RpgCodexCharacterProfile profile) { if (profile == null) { if (!IsSpanish) { return "No Data"; } return "Sin Datos"; } if (profile.IsMultidisciplinaryMaster) { if (!IsSpanish) { return $"Multidisciplinary Master ({profile.HighAffinityCount} disciplines)"; } return $"Maestro Multidisciplinar ({profile.HighAffinityCount} disciplinas)"; } if (profile.IsHybrid) { if (!IsSpanish) { return $"Hybrid Specialization: {profile.HybridTitle}"; } return $"Especialización Híbrida: {profile.HybridTitle}"; } if ((profile.Tier == ArchetypeSpecializationTier.Novice || profile.Tier == ArchetypeSpecializationTier.Developing) && profile.PrimaryAffinity < 0.3f) { float num = Mathf.Abs(profile.PrimaryAffinity - profile.SecondaryAffinity); if (profile.HasSecondaryAffinity && num <= 0.05f) { if (!IsSpanish) { return $"{GetTierName(profile.Tier)}: Mixed Affinity ({GetArchetypeName(profile.PrimaryArchetype)} / {GetArchetypeName(profile.SecondaryArchetype)})"; } return $"{GetTierName(profile.Tier)}: Afinidad Mixta ({GetArchetypeName(profile.PrimaryArchetype)} / {GetArchetypeName(profile.SecondaryArchetype)})"; } if (profile.PrimaryArchetype != RpgArchetypeId.Neutral) { if (!IsSpanish) { return $"{GetTierName(profile.Tier)}: Orientation toward {GetArchetypeName(profile.PrimaryArchetype)}"; } return $"{GetTierName(profile.Tier)}: Orientación a {GetArchetypeName(profile.PrimaryArchetype)}"; } if (!IsSpanish) { return "Neutral (Unspecialized)"; } return "Neutral (Sin Especialización)"; } if (profile.HasSecondaryAffinity) { if (!IsSpanish) { return $"Specialist in {GetArchetypeName(profile.PrimaryArchetype)} (Affinity: {GetArchetypeName(profile.SecondaryArchetype)})"; } return $"Especialista en {GetArchetypeName(profile.PrimaryArchetype)} (Afinidad: {GetArchetypeName(profile.SecondaryArchetype)})"; } if (profile.PrimaryArchetype != RpgArchetypeId.Neutral) { if (!IsSpanish) { return $"Pure Specialist in {GetArchetypeName(profile.PrimaryArchetype)}"; } return $"Especialista Puro en {GetArchetypeName(profile.PrimaryArchetype)}"; } if (!IsSpanish) { return "Neutral (No Defined Specialization)"; } return "Neutral (Sin Especialización Definida)"; } } public static class RpgCharacterCodexGui { private static GameObject s_hostObject; private static RpgCharacterCodexComponent s_component; private static ManualLogSource s_logger; private static Assembly s_coreAssembly; private static bool s_stylesInitialized; private static GUIStyle s_windowStyle; private static GUIStyle s_titleStyle; private static GUIStyle s_subtitleStyle; private static GUIStyle s_sectionHeaderStyle; private static GUIStyle s_cardStyle; private static GUIStyle s_labelStyle; private static GUIStyle s_valueStyle; private static GUIStyle s_buttonStyle; private static GUIStyle s_tabStyle; private static GUIStyle s_activeTabStyle; private static GUIStyle s_barLabelStyle; private static GUIStyle s_barValueStyle; private static GUIStyle s_badgeStyle; private static Vector2 s_scrollPosition; public static bool IsOpen { get; private set; } public static ConfigEntry HotkeyConfig { get; set; } public static KeyCode EffectiveHotkey { get { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (HotkeyConfig == null) { return (KeyCode)291; } return HotkeyConfig.Value; } } public static RpgCodexCategory CurrentCategory { get; set; } public static RpgCodexCharacterProfile CachedProfile { get; private set; } public static RpgPlayerCapabilitySnapshot CachedSnapshot { get; private set; } public static LiveCombatStats CachedCombatStats { get; private set; } public static List CachedMasteries { get; private set; } public static List CachedProviders { get; private set; } public static RpgPlayerArchetypeTracker Tracker { get; private set; } public static float LastRefreshTime { get; private set; } public static string ConflictNotice { get; private set; } public static ManualLogSource Log => s_logger; static RpgCharacterCodexGui() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) s_stylesInitialized = false; s_scrollPosition = Vector2.zero; Tracker = new RpgPlayerArchetypeTracker(); CurrentCategory = RpgCodexCategory.Identity; CachedMasteries = new List(); CachedProviders = new List(); } public static void Init(Assembly coreAssembly, ManualLogSource logger) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown s_coreAssembly = coreAssembly; s_logger = logger; try { if ((Object)(object)s_hostObject == (Object)null) { s_hostObject = new GameObject("_TameMate_RpgCharacterCodexUI"); Object.DontDestroyOnLoad((Object)(object)s_hostObject); s_component = s_hostObject.AddComponent(); if (logger != null) { logger.LogInfo((object)"[RpgCharacterCodexGui] UI host initialized successfully."); } } } catch (Exception ex) { if (logger != null) { logger.LogError((object)("[RpgCharacterCodexGui] UI host initialization failed: " + ex.Message)); } } } public static void Open() { IsOpen = true; RefreshSnapshot(force: true); } public static void Close() { IsOpen = false; } public static void Toggle() { if (IsOpen) { Close(); } else { Open(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static float GetUnityTimeInternal() { return Time.time; } public static float SafeGetTime() { try { return GetUnityTimeInternal(); } catch { return (float)(DateTime.UtcNow - new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; } } public static bool IsPlayerDeadSafe(object playerRef) { if (playerRef == null) { return false; } try { MethodInfo method = playerRef.GetType().GetMethod("IsDead", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); if (method != null) { object obj = method.Invoke(playerRef, null); if (obj is bool) { return (bool)obj; } } } catch { } return false; } public static void SetDebugProfile(RpgCodexCharacterProfile profile, LiveCombatStats stats = default(LiveCombatStats)) { CachedProfile = profile; CachedCombatStats = stats; LastRefreshTime = SafeGetTime(); } public static void SetDebugSnapshot(RpgPlayerCapabilitySnapshot snapshot) { CachedSnapshot = snapshot; if (snapshot != null) { Tracker.Evaluate(snapshot, 5f); CachedProfile = Tracker.LastClassification.ToCodexProfile(snapshot); } LastRefreshTime = SafeGetTime(); } private static object GetLocalPlayerSafe() { try { Type type = AccessTools.TypeByName("Player") ?? AccessTools.TypeByName("Player, assembly_valheim"); if (type == null) { return null; } FieldInfo fieldInfo = AccessTools.Field(type, "m_localPlayer"); return (fieldInfo != null) ? fieldInfo.GetValue(null) : null; } catch { return null; } } public static void RefreshSnapshot(bool force = false) { try { object localPlayerSafe = GetLocalPlayerSafe(); CachedCombatStats = LiveCombatStats.Capture(localPlayerSafe); CachedMasteries = LiveMasteryInfo.CaptureAll(localPlayerSafe); CachedProviders = LiveProviderInfo.CaptureAll(); if (CombatCalculationContext.CreateDefault().DetectMultiplierConflict(out var conflictDescription)) { ConflictNotice = conflictDescription; } else { ConflictNotice = string.Empty; } if (localPlayerSafe != null) { CachedSnapshot = RpgCapabilityRegistry.CapturePlayerSnapshot(localPlayerSafe); float deltaTime = (force ? 5f : Mathf.Max(0.1f, SafeGetTime() - LastRefreshTime)); Tracker.Evaluate(CachedSnapshot, deltaTime); CachedProfile = Tracker.LastClassification.ToCodexProfile(CachedSnapshot); } else if (CachedProfile == null) { RpgPlayerCapabilitySnapshot snapshot = new RpgPlayerCapabilitySnapshot(); ArchetypeClassificationResult archetypeClassificationResult = RpgArchetypeEngine.Classify(snapshot); CachedProfile = archetypeClassificationResult.ToCodexProfile(snapshot); } LastRefreshTime = SafeGetTime(); } catch (Exception ex) { if (s_logger != null) { s_logger.LogWarning((object)("[RpgCharacterCodexGui] RefreshSnapshot exception: " + ex.Message)); } } } public static void Draw() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0113: 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_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //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_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) InitStyles(); float screenWidth = GetScreenWidth(); float screenHeight = GetScreenHeight(); Color color = GUI.color; GUI.color = new Color(0f, 0f, 0f, 0.75f); GUI.DrawTexture(new Rect(0f, 0f, screenWidth, screenHeight), (Texture)(object)Texture2D.whiteTexture); GUI.color = color; float num = Mathf.Clamp(screenWidth * 0.88f, 860f, 1140f); float num2 = Mathf.Clamp(screenHeight * 0.88f, 620f, 780f); if (num > screenWidth - 20f) { num = screenWidth - 20f; } if (num2 > screenHeight - 20f) { num2 = screenHeight - 20f; } float num3 = (screenWidth - num) * 0.5f; float num4 = (screenHeight - num2) * 0.5f; Rect val = default(Rect); ((Rect)(ref val))..ctor(num3, num4, num, num2); GUI.backgroundColor = new Color(0.1f, 0.1f, 0.11f, 0.98f); GUI.Box(val, GUIContent.none, s_windowStyle); GUI.color = new Color(0.85f, 0.72f, 0.35f, 0.85f); GUI.DrawTexture(new Rect(num3, num4, num, 2f), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(num3, num4 + num2 - 2f, num, 2f), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(num3, num4, 2f, num2), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(num3 + num - 2f, num4, 2f, num2), (Texture)(object)Texture2D.whiteTexture); GUI.color = Color.white; GUILayout.BeginArea(new Rect(num3 + 16f, num4 + 14f, num - 32f, num2 - 28f)); DrawHeader(); GUILayout.Space(8f); DrawTabs(); GUILayout.Space(10f); s_scrollPosition = GUILayout.BeginScrollView(s_scrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true) }); RpgCodexCharacterProfile cachedProfile = CachedProfile; switch (CurrentCategory) { case RpgCodexCategory.Identity: DrawIdentityTab(cachedProfile); break; case RpgCodexCategory.Attributes: DrawAttributesTab(cachedProfile); break; case RpgCodexCategory.Affinities: DrawAffinitiesTab(cachedProfile); break; case RpgCodexCategory.Masteries: DrawMasteriesTab(); break; case RpgCodexCategory.Providers: DrawProvidersTab(); break; } GUILayout.EndScrollView(); GUILayout.Space(6f); DrawFooter(); GUILayout.EndArea(); } private static void DrawHeader() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(RpgCodexLocalization.GetWindowTitle(), s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(RpgCodexLocalization.GetWindowSubtitle(), s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUI.backgroundColor = new Color(0.25f, 0.3f, 0.38f); if (GUILayout.Button(RpgCodexLocalization.IsSpanish ? "Actualizar" : "Refresh", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(110f), GUILayout.Height(26f) })) { RefreshSnapshot(force: true); } GUILayout.Space(8f); GUI.backgroundColor = new Color(0.65f, 0.2f, 0.2f); if (GUILayout.Button(RpgCodexLocalization.IsSpanish ? "Cerrar (Esc)" : "Close (Esc)", s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(115f), GUILayout.Height(26f) })) { Close(); } GUI.backgroundColor = Color.white; GUILayout.EndHorizontal(); } private static void DrawTabs() { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); for (int i = 0; i < 5; i++) { RpgCodexCategory rpgCodexCategory = (RpgCodexCategory)i; bool flag = CurrentCategory == rpgCodexCategory; GUI.backgroundColor = (flag ? new Color(0.85f, 0.7f, 0.25f) : new Color(0.18f, 0.2f, 0.24f)); GUIStyle val = (flag ? s_activeTabStyle : s_tabStyle); if (GUILayout.Button(RpgCodexLocalization.GetCategoryTitle(rpgCodexCategory), val, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(30f) })) { CurrentCategory = rpgCodexCategory; } } GUI.backgroundColor = Color.white; GUILayout.EndHorizontal(); } private static void DrawIdentityTab(RpgCodexCharacterProfile profile) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: 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_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Unknown result type (might be due to invalid IL or missing references) //IL_03a1: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) //IL_04e1: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Perfil de Identidad y Rango de Especialización" : "Identity Profile and Specialization Tier") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); GUI.backgroundColor = new Color(0.14f, 0.16f, 0.18f, 0.95f); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); string text = ((profile != null && !string.IsNullOrEmpty(profile.CharacterName)) ? profile.CharacterName : (RpgCodexLocalization.IsSpanish ? "Héroe Desconocido" : "Unknown Hero")); GUILayout.Label("" + text + "", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.FlexibleSpace(); ArchetypeSpecializationTier tier = profile?.Tier ?? ArchetypeSpecializationTier.Novice; Color tierColor = GetTierColor(tier); DrawBadge(RpgCodexLocalization.GetTierName(tier), tierColor, Color.black); GUILayout.Space(6f); string stateTitle = RpgCodexLocalization.GetStateTitle(profile); DrawBadge(stateTitle, new Color(0.85f, 0.7f, 0.25f), Color.black); GUILayout.EndHorizontal(); GUILayout.Space(6f); DrawSeparator(); GUILayout.Space(6f); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(GetWindowContentWidth() * 0.48f) }); GUILayout.Label(RpgCodexLocalization.IsSpanish ? "Arquetipo Primario (Líder):" : "Primary Archetype (Lead):", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); RpgArchetypeId id = profile?.PrimaryArchetype ?? RpgArchetypeId.Neutral; float num = profile?.PrimaryAffinity ?? 0f; DrawProgressBar(RpgCodexLocalization.GetArchetypeName(id), num, new Color(0.85f, 0.7f, 0.25f), $"{num:P0}", 22f); GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(GetWindowContentWidth() * 0.48f) }); GUILayout.Label(RpgCodexLocalization.IsSpanish ? "Arquetipo Secundario:" : "Secondary Archetype:", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); RpgArchetypeId rpgArchetypeId = profile?.SecondaryArchetype ?? RpgArchetypeId.Neutral; float num2 = profile?.SecondaryAffinity ?? 0f; Color barColor = ((rpgArchetypeId != RpgArchetypeId.Neutral) ? new Color(0.4f, 0.7f, 0.95f) : new Color(0.45f, 0.45f, 0.45f)); DrawProgressBar(RpgCodexLocalization.GetArchetypeName(rpgArchetypeId), num2, barColor, (rpgArchetypeId != RpgArchetypeId.Neutral) ? $"{num2:P0}" : "N/A", 22f); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(10f); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); float fraction = profile?.EffectivePowerLevel ?? 0f; float fraction2 = profile?.SpecializationIndex ?? 0f; float fraction3 = profile?.Confidence ?? 0f; DrawMetricBox(RpgCodexLocalization.IsSpanish ? "Poder Efectivo" : "Effective Power", fraction, new Color(0.35f, 0.85f, 0.45f)); GUILayout.Space(8f); DrawMetricBox(RpgCodexLocalization.IsSpanish ? "Índice Especialización" : "Specialization Index", fraction2, new Color(0.95f, 0.65f, 0.25f)); GUILayout.Space(8f); DrawMetricBox(RpgCodexLocalization.IsSpanish ? "Confianza Clasificación" : "Classification Confidence", fraction3, new Color(0.45f, 0.75f, 1f)); GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.Space(12f); GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Descripción Táctica y Semántica" : "Tactical and Semantic Narrative") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); GUI.backgroundColor = new Color(0.12f, 0.13f, 0.15f, 0.95f); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); if (profile != null && profile.IsHybrid && !string.IsNullOrEmpty(profile.HybridTitle)) { GUI.color = new Color(0.95f, 0.8f, 0.3f); string text2 = $"{RpgCodexLocalization.GetArchetypeName((profile.PrimaryArchetype == RpgArchetypeId.Hybrid) ? profile.SecondaryArchetype : profile.PrimaryArchetype)} + {RpgCodexLocalization.GetArchetypeName(profile.SecondaryArchetype)}"; GUILayout.Label("[+] " + profile.HybridTitle + " (" + text2 + ")", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.Space(4f); string text3 = ((!string.IsNullOrEmpty(profile.HybridDescription)) ? profile.HybridDescription : "Especialización táctica combinada."); GUILayout.Label(text3, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); DrawSeparator(); GUILayout.Space(6f); } string text4 = ((profile != null && !string.IsNullOrEmpty(profile.DiagnosticExplanation)) ? profile.DiagnosticExplanation : (RpgCodexLocalization.IsSpanish ? "Sin diagnóstico activo." : "No active diagnostic.")); GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Diagnóstico del Motor:" : "Engine Diagnostic:") + " " + text4, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); string text5 = ((profile != null && !string.IsNullOrEmpty(profile.ProvenanceSummary)) ? profile.ProvenanceSummary : string.Empty); if (!string.IsNullOrEmpty(text5)) { GUILayout.Space(4f); GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Procedencia de Atributos:" : "Attribute Provenance:") + " " + text5, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.EndVertical(); } private static void DrawAttributesTab(RpgCodexCharacterProfile profile) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_0510: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_053d: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_04a9: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Estadísticas Vivas de Combate" : "Live Combat Statistics") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); LiveCombatStats cachedCombatStats = CachedCombatStats; GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); DrawStatCard(RpgCodexLocalization.IsSpanish ? "Salud Vital" : "Vital Health", $"{cachedCombatStats.CurrentHealth:F0} / {cachedCombatStats.MaxHealth:F0}", new Color(0.35f, 0.85f, 0.45f), (cachedCombatStats.MaxHealth > 0f) ? $"{cachedCombatStats.CurrentHealth / cachedCombatStats.MaxHealth:P0}" : "100%"); GUILayout.Space(6f); DrawStatCard(RpgCodexLocalization.IsSpanish ? "Aguante / Estamina" : "Stamina Reserve", $"{cachedCombatStats.CurrentStamina:F0} / {cachedCombatStats.MaxStamina:F0}", new Color(0.95f, 0.8f, 0.25f), (cachedCombatStats.MaxStamina > 0f) ? $"{cachedCombatStats.CurrentStamina / cachedCombatStats.MaxStamina:P0}" : "100%"); GUILayout.Space(6f); DrawStatCard(RpgCodexLocalization.IsSpanish ? "Esencia Eitr" : "Eitr Essence", $"{cachedCombatStats.CurrentEitr:F0} / {cachedCombatStats.MaxEitr:F0}", new Color(0.7f, 0.45f, 1f), (cachedCombatStats.MaxEitr > 0f) ? $"{cachedCombatStats.CurrentEitr / cachedCombatStats.MaxEitr:P0}" : "0%"); GUILayout.Space(6f); DrawStatCard(RpgCodexLocalization.IsSpanish ? "Armadura Total" : "Total Armor", $"{cachedCombatStats.BodyArmor:F1}", new Color(0.4f, 0.75f, 0.95f), RpgCodexLocalization.IsSpanish ? "Mitigación base" : "Base mitigation"); GUILayout.Space(6f); DrawStatCard(RpgCodexLocalization.IsSpanish ? "Bloqueo / Escudo" : "Block Power", $"{cachedCombatStats.BlockPower:F1}", new Color(0.95f, 0.55f, 0.3f), (!string.IsNullOrEmpty(cachedCombatStats.EquippedShieldName)) ? cachedCombatStats.EquippedShieldName : (RpgCodexLocalization.IsSpanish ? "Sin escudo" : "No shield")); GUILayout.EndHorizontal(); GUILayout.Space(14f); GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Desglose Universal de Capacidades y Procedencia (12 Dimensiones)" : "Universal Capability Breakdown and Provenance (12 Dimensions)") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); IList list = profile?.GetCapabilities(); if (list != null && list.Count > 0) { for (int i = 0; i < list.Count; i++) { RpgArchetypeCapabilityBreakdown rpgArchetypeCapabilityBreakdown = list[i]; GUI.backgroundColor = ((i % 2 == 0) ? new Color(0.13f, 0.14f, 0.16f, 0.95f) : new Color(0.1f, 0.11f, 0.13f, 0.95f)); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("" + RpgCodexLocalization.GetCapabilityDisplayName(rpgArchetypeCapabilityBreakdown.CapabilityName) + "", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); DrawProgressBar(string.Empty, rpgArchetypeCapabilityBreakdown.EffectiveValue, GetCapabilityColor(rpgArchetypeCapabilityBreakdown.CapabilityName), $"{rpgArchetypeCapabilityBreakdown.EffectiveValue:P0}", 16f); GUILayout.Space(12f); string text = $"Perm: {rpgArchetypeCapabilityBreakdown.PermanentPercent:P0} | Equip: {rpgArchetypeCapabilityBreakdown.EquipmentPercent:P0}"; GUILayout.Label(text, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(rpgArchetypeCapabilityBreakdown.ProvenanceSummary)) { GUILayout.Space(2f); GUI.color = new Color(0.85f, 0.88f, 0.92f); GUILayout.Label(" ↳ " + rpgArchetypeCapabilityBreakdown.ProvenanceSummary, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } GUILayout.EndVertical(); GUILayout.Space(2f); } } else { GUILayout.Label(RpgCodexLocalization.IsSpanish ? "No se registraron capacidades activas en el snapshot actual." : "No active capabilities recorded in current snapshot.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.Space(8f); GUI.color = new Color(0.75f, 0.75f, 0.75f); GUILayout.Label(RpgCodexLocalization.IsSpanish ? "Nota: Los índices [0..100%] representan la magnitud relativa del vector universal de capacidades y no deben confundirse con estadísticas directas ni probabilidades." : "Note: Indices [0..100%] represent the relative magnitude of the universal capability vector and must not be confused with direct combat stats or roll probabilities.", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } private static void DrawAffinitiesTab(RpgCodexCharacterProfile profile) { //IL_0336: Unknown result type (might be due to invalid IL or missing references) //IL_0363: 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_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_0286: 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_0293: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Matriz Dimensional de Afinidades de Combate (8 Arquetipos Primarios)" : "Dimensional Combat Affinity Matrix (8 Primary Archetypes)") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); RpgArchetypeId[] array = new RpgArchetypeId[8] { RpgArchetypeId.Tank, RpgArchetypeId.Warrior, RpgArchetypeId.Berserker, RpgArchetypeId.Assassin, RpgArchetypeId.Lancer, RpgArchetypeId.Archer, RpgArchetypeId.Mage, RpgArchetypeId.Tamer }; foreach (RpgArchetypeId rpgArchetypeId in array) { float num = profile?.GetAffinity(rpgArchetypeId) ?? 0f; bool flag = profile != null && profile.PrimaryArchetype == rpgArchetypeId; bool flag2 = profile != null && profile.SecondaryArchetype == rpgArchetypeId; GUI.backgroundColor = (flag ? new Color(0.22f, 0.18f, 0.1f, 0.95f) : (flag2 ? new Color(0.12f, 0.18f, 0.22f, 0.95f) : new Color(0.12f, 0.13f, 0.15f, 0.95f))); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); if (flag) { DrawBadge(RpgCodexLocalization.IsSpanish ? "LÍDER" : "LEAD", new Color(0.95f, 0.75f, 0.2f), Color.black); } else if (flag2) { DrawBadge(RpgCodexLocalization.IsSpanish ? "SECUNDARIO" : "SECONDARY", new Color(0.4f, 0.75f, 0.95f), Color.black); } else if (num >= 0.3f) { DrawBadge(RpgCodexLocalization.IsSpanish ? "COMPLEMENTO" : "COMPATIBLE", new Color(0.5f, 0.8f, 0.5f), Color.black); } else { DrawBadge(RpgCodexLocalization.IsSpanish ? "MENOR" : "MINOR", new Color(0.35f, 0.35f, 0.35f), Color.white); } GUILayout.Space(8f); GUILayout.Label("" + RpgCodexLocalization.GetArchetypeName(rpgArchetypeId) + "", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(190f) }); Color barColor = (flag ? new Color(0.95f, 0.75f, 0.2f) : (flag2 ? new Color(0.4f, 0.75f, 0.95f) : new Color(0.6f, 0.65f, 0.7f))); DrawProgressBar(string.Empty, num, barColor, $"{num:P0}", 20f); GUILayout.EndHorizontal(); GUILayout.Space(2f); GUI.color = new Color(0.85f, 0.88f, 0.92f); GUILayout.Label(" ↳ " + GetAffinityFactorsExplanation(rpgArchetypeId), s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndVertical(); GUILayout.Space(4f); } GUILayout.Space(8f); GUI.color = new Color(0.75f, 0.75f, 0.75f); GUILayout.Label(RpgCodexLocalization.IsSpanish ? "Aviso: Cada afinidad mide de forma independiente la alineación táctica del personaje. No son probabilidades de tirada, no son mutuamente excluyentes ni suman 100%." : "Notice: Each affinity independently measures the character's tactical alignment. They are not roll probabilities, are not mutually exclusive, and do not sum to 100%.", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } private static void DrawMasteriesTab() { //IL_0329: 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_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Códice de Maestrías Nórdicas de TameMate (Solo Lectura)" : "TameMate Nordic Masteries Codex (Read-Only)") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); List cachedMasteries = CachedMasteries; if (cachedMasteries != null && cachedMasteries.Count > 0) { for (int i = 0; i < cachedMasteries.Count; i++) { LiveMasteryInfo liveMasteryInfo = cachedMasteries[i]; GUI.backgroundColor = new Color(0.12f, 0.13f, 0.16f, 0.95f); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label("" + liveMasteryInfo.Name + "", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.Label($"[{liveMasteryInfo.Category}]", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) }); GUILayout.FlexibleSpace(); Color masteryRankColor = GetMasteryRankColor(liveMasteryInfo.CurrentRank); DrawBadge(liveMasteryInfo.RankTitle, masteryRankColor, Color.black); GUILayout.EndHorizontal(); GUILayout.Space(4f); if (!string.IsNullOrEmpty(liveMasteryInfo.Summary)) { GUILayout.Label(liveMasteryInfo.Summary, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(4f); } if (liveMasteryInfo.RequiredProgress > 0) { float num = Mathf.Clamp01((float)liveMasteryInfo.CurrentProgress / (float)liveMasteryInfo.RequiredProgress); string valueText = $"{liveMasteryInfo.CurrentProgress} / {liveMasteryInfo.RequiredProgress} ({num:P0})"; DrawProgressBar(RpgCodexLocalization.IsSpanish ? "Progreso de Rango:" : "Rank Progress:", num, new Color(0.35f, 0.8f, 0.45f), valueText, 16f); GUILayout.Space(4f); } if (!string.IsNullOrEmpty(liveMasteryInfo.RankPerks)) { GUI.color = new Color(0.85f, 0.9f, 0.7f); GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Beneficios Activos:" : "Active Perks:") + " " + liveMasteryInfo.RankPerks, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } if (!string.IsNullOrEmpty(liveMasteryInfo.NextQuest)) { GUI.color = new Color(1f, 0.85f, 0.5f); GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Misión de Desbloqueo:" : "Unlock Quest:") + " " + liveMasteryInfo.NextQuest, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } GUILayout.EndVertical(); GUILayout.Space(4f); } } else { GUILayout.Label(RpgCodexLocalization.IsSpanish ? "No se pudieron consultar las definiciones de Maestrías o el catálogo aún no está cargado." : "Mastery definitions could not be inspected or catalog is not yet loaded.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.Space(8f); GUI.color = new Color(0.75f, 0.75f, 0.75f); GUILayout.Label(RpgCodexLocalization.IsSpanish ? "Consulta de Solo Lectura: Información sincronizada directamente con MasteriesSystem de TameMate. Cero modificaciones a los datos o progresión." : "Read-Only Inspection: Synchronized directly from TameMate's MasteriesSystem. Zero mutations to progression data.", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } private static void DrawProvidersTab() { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_0151: 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_0383: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("" + (RpgCodexLocalization.IsSpanish ? "Ecosistema de Proveedores RPG y Compatibilidad" : "RPG Provider Ecosystem and Compatibility") + "", s_sectionHeaderStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(6f); if (!string.IsNullOrEmpty(ConflictNotice)) { GUI.backgroundColor = new Color(0.5f, 0.15f, 0.15f, 0.95f); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = new Color(1f, 0.6f, 0.6f); GUILayout.Label("[!] " + (RpgCodexLocalization.IsSpanish ? "ADVERTENCIA DE COMPOSICIÓN:" : "COMPOSITION WARNING:") + "", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(ConflictNotice, s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndVertical(); GUILayout.Space(8f); } List cachedProviders = CachedProviders; if (cachedProviders != null && cachedProviders.Count > 0) { for (int i = 0; i < cachedProviders.Count; i++) { LiveProviderInfo liveProviderInfo = cachedProviders[i]; GUI.backgroundColor = (liveProviderInfo.IsActive ? new Color(0.12f, 0.16f, 0.14f, 0.95f) : new Color(0.11f, 0.11f, 0.12f, 0.95f)); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); if (liveProviderInfo.IsActive) { DrawBadge("ACTIVO", new Color(0.3f, 0.85f, 0.4f), Color.black); } else { DrawBadge("NO PRESENTE", new Color(0.4f, 0.4f, 0.4f), Color.white); } GUILayout.Space(8f); GUILayout.Label("" + liveProviderInfo.DisplayName + "", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); GUILayout.FlexibleSpace(); GUILayout.Label($"[{RpgCodexLocalization.GetResponsibilityTitle(liveProviderInfo.Responsibility)}]", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); GUILayout.Space(4f); GUILayout.Label(string.Format("{0}: {1}", RpgCodexLocalization.IsSpanish ? "Capacidades" : "Capabilities", RpgCodexLocalization.GetCapabilitiesSummary(liveProviderInfo.Capabilities)), s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(2f); GUI.color = (liveProviderInfo.IsActive ? new Color(0.8f, 0.95f, 0.8f) : new Color(0.85f, 0.85f, 0.88f)); GUILayout.Label(string.Format("{0}: {1}", RpgCodexLocalization.IsSpanish ? "Estado en Juego" : "In-Game State", liveProviderInfo.ActiveMetrics), s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.EndVertical(); GUILayout.Space(4f); } } else { GUILayout.Label(RpgCodexLocalization.IsSpanish ? "No hay proveedores registrados en el catálogo de estadísticas." : "No providers registered in stat catalog.", s_labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.Space(8f); GUI.color = new Color(0.75f, 0.75f, 0.75f); GUILayout.Label(RpgCodexLocalization.IsSpanish ? "Gobernanza Modular: TameMate introspecciona proveedores sin dependencias duras. Los mods ausentes no generan lecturas ficticias." : "Modular Governance: TameMate introspects providers without hard dependencies. Absent mods generate zero mock readings.", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } private static void DrawFooter() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = new Color(0.85f, 0.7f, 0.25f); GUILayout.Label("TameMate 0.8.0 — Adaptive RPG Archetypes", s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; GUILayout.FlexibleSpace(); string text = string.Format(RpgCodexLocalization.IsSpanish ? "Acceso: [{0}] | Cerrar: [Esc]" : "Access: [{0}] | Close: [Esc]", EffectiveHotkey); GUILayout.Label(text, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.EndHorizontal(); } private static void DrawProgressBar(string label, float fraction, Color barColor, string valueText, float height = 18f) { //IL_0031: 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) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_014c: 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_018a: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) fraction = Mathf.Clamp01(fraction); Rect rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.ExpandWidth(true), GUILayout.Height(height) }); Color color = GUI.color; GUI.color = new Color(0.12f, 0.13f, 0.15f, 0.95f); GUI.DrawTexture(rect, (Texture)(object)Texture2D.whiteTexture); if (fraction > 0.001f) { Rect val = default(Rect); ((Rect)(ref val))..ctor(((Rect)(ref rect)).x + 1f, ((Rect)(ref rect)).y + 1f, (((Rect)(ref rect)).width - 2f) * fraction, ((Rect)(ref rect)).height - 2f); GUI.color = barColor; GUI.DrawTexture(val, (Texture)(object)Texture2D.whiteTexture); } GUI.color = new Color(0.35f, 0.32f, 0.25f, 0.85f); GUI.DrawTexture(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width, 1f), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).yMax - 1f, ((Rect)(ref rect)).width, 1f), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, 1f, ((Rect)(ref rect)).height), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(((Rect)(ref rect)).xMax - 1f, ((Rect)(ref rect)).y, 1f, ((Rect)(ref rect)).height), (Texture)(object)Texture2D.whiteTexture); GUI.color = Color.white; if (!string.IsNullOrEmpty(label)) { Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref rect)).x + 6f, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * 0.55f, ((Rect)(ref rect)).height); GUI.Label(val2, label, s_barLabelStyle); } if (!string.IsNullOrEmpty(valueText)) { Rect val3 = default(Rect); ((Rect)(ref val3))..ctor(((Rect)(ref rect)).x + ((Rect)(ref rect)).width * 0.5f, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * 0.5f - 6f, ((Rect)(ref rect)).height); GUI.Label(val3, valueText, s_barValueStyle); } GUI.color = color; } private static void DrawStatCard(string title, string value, Color accentColor, string subtext = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0055: 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_0096: 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_00d2: Unknown result type (might be due to invalid IL or missing references) GUI.backgroundColor = new Color(0.14f, 0.15f, 0.18f, 0.95f); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.ExpandWidth(true), GUILayout.Height(62f) }); GUI.color = new Color(0.8f, 0.85f, 0.9f); GUILayout.Label(title, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = accentColor; GUILayout.Label("" + value + "", s_titleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; if (!string.IsNullOrEmpty(subtext)) { GUI.color = new Color(0.85f, 0.88f, 0.92f); GUILayout.Label(subtext, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; } GUILayout.EndVertical(); } private static void DrawMetricBox(string label, float fraction, Color barColor) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) GUI.backgroundColor = new Color(0.13f, 0.14f, 0.16f, 0.95f); GUILayout.BeginVertical(s_cardStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); GUILayout.Label(label, s_subtitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Space(2f); DrawProgressBar(string.Empty, fraction, barColor, $"{fraction:P0}", 16f); GUILayout.EndVertical(); } private static void DrawBadge(string text, Color bgColor, Color textColor) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) Color backgroundColor = GUI.backgroundColor; Color color = GUI.color; GUI.backgroundColor = bgColor; float num = bgColor.r * 0.299f + bgColor.g * 0.587f + bgColor.b * 0.114f; Color val = ((num < 0.55f) ? new Color(0.96f, 0.95f, 0.92f) : new Color(0.12f, 0.12f, 0.14f)); if (s_badgeStyle != null) { s_badgeStyle.normal.textColor = val; } GUI.color = val; GUILayout.Box(" " + text + " ", s_badgeStyle ?? s_buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(20f) }); GUI.backgroundColor = backgroundColor; GUI.color = color; } private static void DrawSeparator(float space = 4f) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) Color color = GUI.color; GUI.color = new Color(0.35f, 0.35f, 0.38f, 0.5f); Rect rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.ExpandWidth(true), GUILayout.Height(1f) }); GUI.DrawTexture(rect, (Texture)(object)Texture2D.whiteTexture); GUI.color = color; } private static Color GetTierColor(ArchetypeSpecializationTier tier) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) return (Color)(tier switch { ArchetypeSpecializationTier.Novice => new Color(0.7f, 0.7f, 0.7f), ArchetypeSpecializationTier.Developing => new Color(0.4f, 0.7f, 1f), ArchetypeSpecializationTier.Specialized => new Color(0.95f, 0.75f, 0.2f), ArchetypeSpecializationTier.Master => new Color(0.85f, 0.45f, 1f), _ => Color.white, }); } private static Color GetMasteryRankColor(MasteryRank rank) { //IL_0031: 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_005b: 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_0085: 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_00a0: Unknown result type (might be due to invalid IL or missing references) return (Color)(rank switch { MasteryRank.Locked => new Color(0.4f, 0.4f, 0.4f), MasteryRank.Iniciado => new Color(0.4f, 0.8f, 0.5f), MasteryRank.Veterano => new Color(0.35f, 0.7f, 1f), MasteryRank.Experto => new Color(0.95f, 0.75f, 0.2f), MasteryRank.Maestro => new Color(0.9f, 0.4f, 0.9f), MasteryRank.GranMaestro => new Color(1f, 0.35f, 0.35f), _ => Color.white, }); } private static Color GetCapabilityColor(string capName) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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) //IL_0138: 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_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(capName)) { return new Color(0.85f, 0.7f, 0.25f); } string text = capName.ToLowerInvariant(); if (text.Contains("vital") || text.Contains("salud")) { return new Color(0.35f, 0.85f, 0.45f); } if (text.Contains("poder") || text.Contains("físic")) { return new Color(0.95f, 0.45f, 0.35f); } if (text.Contains("defens") || text.Contains("armadur")) { return new Color(0.4f, 0.75f, 0.95f); } if (text.Contains("estamina") || text.Contains("aguant")) { return new Color(0.95f, 0.8f, 0.25f); } if (text.Contains("movil") || text.Contains("carrer")) { return new Color(0.35f, 0.9f, 0.8f); } if (text.Contains("precis") || text.Contains("arquer")) { return new Color(0.85f, 0.65f, 0.95f); } if (text.Contains("hechic") || text.Contains("eitr")) { return new Color(0.7f, 0.45f, 1f); } if (text.Contains("bestia") || text.Contains("domad")) { return new Color(0.85f, 0.6f, 0.35f); } return new Color(0.85f, 0.7f, 0.25f); } private static string GetAffinityFactorsExplanation(RpgArchetypeId arch) { switch (arch) { case RpgArchetypeId.Tank: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Equipped shield, Heavy armor, Vitality, and Damage mitigation."; } return "Impulsado por: Escudo equipado, Armadura pesada, Vitalidad y Mitigación."; case RpgArchetypeId.Warrior: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Swords, Clubs, Martial axes, and Balanced offense/defense."; } return "Impulsado por: Espadas, Mazas, Hachas marciales y Equilibrio ofensivo/defensivo."; case RpgArchetypeId.Berserker: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Battle axes, Asymmetric physical power, and Light/medium armor."; } return "Impulsado por: Hachas de combate, Poder físico asimétrico y Armadura ligera/media."; case RpgArchetypeId.Assassin: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Knives, Surgical precision, High mobility, and Backstab potency."; } return "Impulsado por: Cuchillos, Precisión quirúrgica, Movilidad y Ataques por la espalda."; case RpgArchetypeId.Lancer: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Spears, Polearms, Distance control, and Stamina on the move."; } return "Impulsado por: Lanzas, Armas de asta, Control de distancias y Aguante en movimiento."; case RpgArchetypeId.Archer: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Bows, Crossbows, Ranged precision, and Tactical kiting."; } return "Impulsado por: Arcos, Ballestas, Precisión a distancia y Hostigamiento táctico."; case RpgArchetypeId.Mage: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Elemental staffs, Blood magic, Sorcery, and Eitr reserves."; } return "Impulsado por: Báculos elementales, Sangre, Hechicería y Reserva de Eitr."; case RpgArchetypeId.Tamer: if (!RpgCodexLocalization.IsSpanish) { return "Driven by: Beast mastery, Active packs, and Companion coordination."; } return "Impulsado por: Dominio de bestias, Manadas activas y Sinergia con compañeros."; default: return string.Empty; } } private static float GetScreenWidth() { try { return (Screen.width > 0) ? ((float)Screen.width) : 1920f; } catch { return 1920f; } } private static float GetScreenHeight() { try { return (Screen.height > 0) ? ((float)Screen.height) : 1080f; } catch { return 1080f; } } private static float GetWindowContentWidth() { float screenWidth = GetScreenWidth(); float num = Mathf.Clamp(screenWidth * 0.88f, 860f, 1140f); return num - 32f; } private static void InitStyles() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown //IL_0114: 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_0142: Expected O, but got Unknown //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Expected O, but got Unknown //IL_01b9: 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_01e8: Expected O, but got Unknown //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Expected O, but got Unknown //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Expected O, but got Unknown //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Expected O, but got Unknown //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Expected O, but got Unknown //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_039a: Unknown result type (might be due to invalid IL or missing references) //IL_03a4: Expected O, but got Unknown //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ed: Expected O, but got Unknown if (!s_stylesInitialized || s_windowStyle == null) { Font safeFont = GetSafeFont(); s_windowStyle = new GUIStyle(GUI.skin.box); s_windowStyle.normal.background = Texture2D.whiteTexture; s_cardStyle = new GUIStyle(GUI.skin.box); s_cardStyle.normal.background = Texture2D.whiteTexture; s_cardStyle.padding = new RectOffset(10, 10, 8, 8); GUIStyle val = new GUIStyle(GUI.skin.label); val.fontSize = 15; val.fontStyle = (FontStyle)1; s_titleStyle = val; s_titleStyle.normal.textColor = new Color(0.95f, 0.8f, 0.3f); if ((Object)(object)safeFont != (Object)null) { s_titleStyle.font = safeFont; } GUIStyle val2 = new GUIStyle(GUI.skin.label); val2.fontSize = 11; val2.fontStyle = (FontStyle)0; s_subtitleStyle = val2; s_subtitleStyle.normal.textColor = new Color(0.88f, 0.9f, 0.94f); if ((Object)(object)safeFont != (Object)null) { s_subtitleStyle.font = safeFont; } GUIStyle val3 = new GUIStyle(GUI.skin.label); val3.fontSize = 13; val3.fontStyle = (FontStyle)1; s_sectionHeaderStyle = val3; s_sectionHeaderStyle.normal.textColor = new Color(0.9f, 0.75f, 0.35f); if ((Object)(object)safeFont != (Object)null) { s_sectionHeaderStyle.font = safeFont; } GUIStyle val4 = new GUIStyle(GUI.skin.label); val4.fontSize = 12; s_labelStyle = val4; s_labelStyle.normal.textColor = Color.white; if ((Object)(object)safeFont != (Object)null) { s_labelStyle.font = safeFont; } GUIStyle val5 = new GUIStyle(GUI.skin.label); val5.fontSize = 12; val5.fontStyle = (FontStyle)1; val5.alignment = (TextAnchor)5; s_valueStyle = val5; s_valueStyle.normal.textColor = new Color(0.95f, 0.8f, 0.3f); if ((Object)(object)safeFont != (Object)null) { s_valueStyle.font = safeFont; } GUIStyle val6 = new GUIStyle(GUI.skin.button); val6.fontSize = 11; s_buttonStyle = val6; if ((Object)(object)safeFont != (Object)null) { s_buttonStyle.font = safeFont; } GUIStyle val7 = new GUIStyle(GUI.skin.button); val7.fontSize = 12; s_tabStyle = val7; if ((Object)(object)safeFont != (Object)null) { s_tabStyle.font = safeFont; } GUIStyle val8 = new GUIStyle(GUI.skin.button); val8.fontSize = 12; val8.fontStyle = (FontStyle)1; s_activeTabStyle = val8; if ((Object)(object)safeFont != (Object)null) { s_activeTabStyle.font = safeFont; } GUIStyle val9 = new GUIStyle(GUI.skin.label); val9.fontSize = 10; val9.alignment = (TextAnchor)3; s_barLabelStyle = val9; s_barLabelStyle.normal.textColor = Color.white; if ((Object)(object)safeFont != (Object)null) { s_barLabelStyle.font = safeFont; } GUIStyle val10 = new GUIStyle(GUI.skin.label); val10.fontSize = 10; val10.fontStyle = (FontStyle)1; val10.alignment = (TextAnchor)5; s_barValueStyle = val10; s_barValueStyle.normal.textColor = Color.white; if ((Object)(object)safeFont != (Object)null) { s_barValueStyle.font = safeFont; } s_badgeStyle = new GUIStyle(GUI.skin.box); s_badgeStyle.normal.background = Texture2D.whiteTexture; s_badgeStyle.fontSize = 11; s_badgeStyle.fontStyle = (FontStyle)1; s_badgeStyle.alignment = (TextAnchor)4; s_badgeStyle.padding = new RectOffset(8, 8, 2, 2); if ((Object)(object)safeFont != (Object)null) { s_badgeStyle.font = safeFont; } s_stylesInitialized = true; } } private static Font GetSafeFont() { try { Font builtinResource = Resources.GetBuiltinResource("Arial.ttf"); if ((Object)(object)builtinResource != (Object)null) { return builtinResource; } } catch { } try { if ((Object)(object)GUI.skin != (Object)null && (Object)(object)GUI.skin.font != (Object)null) { return GUI.skin.font; } } catch { } return null; } } public class RpgCharacterCodexComponent : MonoBehaviour { private void Update() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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) try { KeyCode effectiveHotkey = RpgCharacterCodexGui.EffectiveHotkey; if (Input.GetKeyDown(effectiveHotkey)) { RpgCharacterCodexGui.Toggle(); } if (RpgCharacterCodexGui.IsOpen) { Character.SetTakeInputDelay(0.25f); Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; try { ZCursor.LockState = (CursorLockMode)0; ZCursor.Show(); } catch { } if (Input.GetKeyDown((KeyCode)27)) { RpgCharacterCodexGui.Close(); } if (RpgCharacterCodexGui.SafeGetTime() - RpgCharacterCodexGui.LastRefreshTime > 0.5f) { RpgCharacterCodexGui.RefreshSnapshot(); } } } catch { } } private void OnGUI() { if (RpgCharacterCodexGui.IsOpen) { RpgCharacterCodexGui.Draw(); } } } public static class RpgCharacterCodexPatches { private static bool s_installed; public static bool IsInstalled => s_installed; public static void Install(Harmony harmony) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Expected O, but got Unknown //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Expected O, but got Unknown if (s_installed || harmony == null) { return; } try { MethodInfo methodInfo = AccessTools.Method(typeof(Player), "TakeInput", new Type[1] { typeof(bool) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(RpgCharacterCodexPatches), "PlayerTakeInputPrefix", (Type[])null, (Type[])null); if (methodInfo != null && methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo3 = AccessTools.Method(typeof(PlayerController), "TakeInput", new Type[1] { typeof(bool) }, (Type[])null); MethodInfo methodInfo4 = AccessTools.Method(typeof(RpgCharacterCodexPatches), "PlayerControllerTakeInputPrefix", (Type[])null, (Type[])null); if (methodInfo3 != null && methodInfo4 != null) { harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo5 = AccessTools.Method(typeof(PlayerController), "InInventoryEtc", (Type[])null, (Type[])null); MethodInfo methodInfo6 = AccessTools.Method(typeof(RpgCharacterCodexPatches), "PlayerControllerInInventoryEtcPostfix", (Type[])null, (Type[])null); if (methodInfo5 != null && methodInfo6 != null) { harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo7 = AccessTools.Method(typeof(ZInput), "GetMouseScrollWheel", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(RpgCharacterCodexPatches), "ZInputGetMouseScrollWheelPrefix", (Type[])null, (Type[])null); if (methodInfo7 != null && methodInfo8 != null) { harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo9 = AccessTools.Method(typeof(GameCamera), "UpdateMouseCapture", (Type[])null, (Type[])null); MethodInfo methodInfo10 = AccessTools.Method(typeof(RpgCharacterCodexPatches), "GameCameraUpdateMouseCapturePostfix", (Type[])null, (Type[])null); if (methodInfo9 != null && methodInfo10 != null) { harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo10), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } s_installed = true; } catch (Exception ex) { if (RpgCharacterCodexGui.Log != null) { RpgCharacterCodexGui.Log.LogWarning((object)("[RpgCharacterCodexPatches] Error installing input patches: " + ex.Message)); } } } public static void Uninstall() { s_installed = false; } public static bool PlayerTakeInputPrefix(ref bool __result) { if (RpgCharacterCodexGui.IsOpen) { __result = false; return false; } return true; } public static bool PlayerControllerTakeInputPrefix(ref bool __result) { if (RpgCharacterCodexGui.IsOpen) { __result = false; return false; } return true; } public static void PlayerControllerInInventoryEtcPostfix(ref bool __result) { if (RpgCharacterCodexGui.IsOpen) { __result = true; } } public static bool ZInputGetMouseScrollWheelPrefix(ref float __result) { if (RpgCharacterCodexGui.IsOpen) { __result = 0f; return false; } return true; } public static void GameCameraUpdateMouseCapturePostfix() { if (RpgCharacterCodexGui.IsOpen) { Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; } } } internal sealed class SaddlebagCustodyDestination { internal readonly SaddlebagCustodyEntity Entity; internal readonly long Owner; internal readonly ushort OwnerRevision; private readonly byte[] before; private readonly byte[] expected; internal byte[] Before => Copy(before); internal byte[] Expected => Copy(expected); internal SaddlebagCustodyDestination(SaddlebagCustodyEntity entity, long owner, ushort revision, byte[] preimage, byte[] result) { if (entity == null || owner == 0 || result == null || result.Length == 0) { throw new ArgumentException("A real destination and expected snapshot are required."); } Entity = entity; Owner = owner; OwnerRevision = revision; before = Copy(preimage); expected = Copy(result); } private static byte[] Copy(byte[] bytes) { if (bytes == null) { return null; } if (bytes.Length > 262144) { throw new ArgumentException("Destination snapshot limit exceeded."); } return (byte[])bytes.Clone(); } internal bool Same(SaddlebagCustodyDestination other) { if (other != null && Entity.Same(other.Entity) && Owner == other.Owner && OwnerRevision == other.OwnerRevision && SaddlebagCustodyHash.Bytes(before) == SaddlebagCustodyHash.Bytes(other.before)) { return SaddlebagCustodyHash.Bytes(expected) == SaddlebagCustodyHash.Bytes(other.expected); } return false; } } internal sealed class SaddlebagCustodyBinding { internal const string FileName = "destination.sbcb"; internal readonly SaddlebagCustodyRecord Parent; internal readonly string PreparedHash; internal readonly string ParentHash; internal readonly SaddlebagCustodyDestination Destination; internal readonly SaddlebagCustodyAuthority Authority; internal string Hash => SaddlebagCustodyHash.Bytes(SaddlebagCustodyBindingCodec.Encode(this)); internal SaddlebagCustodyBinding(SaddlebagCustodyRecord parent, string preparedHash, string parentHash, SaddlebagCustodyDestination destination, SaddlebagCustodyAuthority authority) { if (parent == null || parent.Binding != null || parent.Intent.Destination != null || destination == null || authority == null || (parent.State != SaddlebagCustodyState.PREPARED && parent.State != SaddlebagCustodyState.PENDING) || !SaddlebagCustodyHash.IsHash(preparedHash) || !SaddlebagCustodyHash.IsHash(parentHash) || parentHash != SaddlebagCustodyHash.Bytes(SaddlebagCustodyCodec.Encode(parent))) { throw new ArgumentException("Invalid binding anchor."); } if ((parent.Intent.Source.UserId == destination.Entity.UserId && parent.Intent.Source.ObjectId == destination.Entity.ObjectId) || authority.ServerPeer != authority.SenderPeer || authority.ServerPeer != parent.Authority.ServerPeer || !authority.SourcePresent || !authority.DestinationPresent || !parent.Authority.SourcePresent || authority.SourceOwner != parent.Authority.SourceOwner || authority.SourceRevision != parent.Authority.SourceRevision || authority.DestinationOwner != destination.Owner || authority.DestinationRevision != destination.OwnerRevision) { throw new ArgumentException("Binding identity/authority contradiction."); } Parent = parent; PreparedHash = preparedHash; ParentHash = parentHash; Destination = destination; Authority = authority; } internal bool IsFor(SaddlebagCustodyIntent intent) { if (intent != null) { return Parent.Intent.Same(intent); } return false; } internal void ValidateAnchor(SaddlebagCustodyRecord parent, SaddlebagCustodyRecord prepared, string parentHash, string preparedHash) { if (!IsFor(parent.Intent) || !IsFor(prepared.Intent) || parent.Revision != Parent.Revision || parentHash != ParentHash || preparedHash != PreparedHash || SaddlebagCustodyHash.Bytes(SaddlebagCustodyCodec.Encode(parent)) != ParentHash || authorityChanged(prepared.Authority, Authority)) { throw new InvalidDataException("Binding contradicts original operation/authority or parent revision."); } } private static bool authorityChanged(SaddlebagCustodyAuthority original, SaddlebagCustodyAuthority current) { if (original.ServerPeer == current.ServerPeer && original.SourcePresent && original.SourceOwner == current.SourceOwner) { return original.SourceRevision != current.SourceRevision; } return true; } } internal static class SaddlebagCustodyBindingCodec { private const int Magic = 1396851522; private const int Version = 1; internal static byte[] Encode(SaddlebagCustodyBinding binding) { byte[] array2; using (MemoryStream memoryStream = new MemoryStream()) { using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); byte[] array = SaddlebagCustodyCodec.Encode(binding.Parent); binaryWriter.Write(array.Length); binaryWriter.Write(array); SaddlebagCustodyCodec.Text(binaryWriter, binding.PreparedHash); SaddlebagCustodyCodec.Text(binaryWriter, binding.ParentHash); SaddlebagCustodyDestination destination = binding.Destination; binaryWriter.Write(destination.Entity.UserId); binaryWriter.Write(destination.Entity.ObjectId); binaryWriter.Write(destination.Entity.Prefab); binaryWriter.Write(destination.Owner); binaryWriter.Write(destination.OwnerRevision); SaddlebagCustodyCodec.Blob(binaryWriter, destination.Before); SaddlebagCustodyCodec.Blob(binaryWriter, destination.Expected); SaddlebagCustodyAuthority authority = binding.Authority; binaryWriter.Write(authority.ServerPeer); binaryWriter.Write(authority.SenderPeer); binaryWriter.Write(authority.SourceOwner); binaryWriter.Write(authority.SourceRevision); binaryWriter.Write(authority.DestinationOwner); binaryWriter.Write(authority.DestinationRevision); binaryWriter.Write(authority.SourcePresent); binaryWriter.Write(authority.DestinationPresent); binaryWriter.Write(authority.CapturedUtcTicks); binaryWriter.Flush(); array2 = memoryStream.ToArray(); } using MemoryStream memoryStream2 = new MemoryStream(); using BinaryWriter binaryWriter2 = new BinaryWriter(memoryStream2); binaryWriter2.Write(1396851522); binaryWriter2.Write(1); binaryWriter2.Write(array2.Length); binaryWriter2.Write(array2); SaddlebagCustodyCodec.Text(binaryWriter2, SaddlebagCustodyHash.Bytes(array2)); binaryWriter2.Flush(); if (memoryStream2.Length > 1048576) { throw new InvalidDataException("Binding receipt too large."); } return memoryStream2.ToArray(); } internal static SaddlebagCustodyBinding Decode(byte[] bytes) { if (bytes == null || bytes.Length > 1048576) { throw new InvalidDataException("Invalid binding size."); } byte[] array; using (MemoryStream memoryStream = new MemoryStream(bytes, writable: false)) { using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadInt32() != 1396851522 || binaryReader.ReadInt32() != 1) { throw new InvalidDataException("Unsupported binding format."); } array = SaddlebagCustodyCodec.Exact(binaryReader, binaryReader.ReadInt32(), 1048576); if (SaddlebagCustodyCodec.Text(binaryReader) != SaddlebagCustodyHash.Bytes(array) || memoryStream.Position != memoryStream.Length) { throw new InvalidDataException("Binding checksum/trailing data mismatch."); } } using MemoryStream memoryStream2 = new MemoryStream(array, writable: false); using BinaryReader binaryReader2 = new BinaryReader(memoryStream2); SaddlebagCustodyRecord parent = SaddlebagCustodyCodec.Decode(SaddlebagCustodyCodec.Exact(binaryReader2, binaryReader2.ReadInt32(), 1048576)); string preparedHash = SaddlebagCustodyCodec.Text(binaryReader2); string parentHash = SaddlebagCustodyCodec.Text(binaryReader2); SaddlebagCustodyEntity entity = new SaddlebagCustodyEntity(binaryReader2.ReadInt64(), binaryReader2.ReadUInt32(), binaryReader2.ReadInt32()); long owner = binaryReader2.ReadInt64(); ushort revision = binaryReader2.ReadUInt16(); SaddlebagCustodyDestination destination = new SaddlebagCustodyDestination(entity, owner, revision, SaddlebagCustodyCodec.Blob(binaryReader2), SaddlebagCustodyCodec.Blob(binaryReader2)); SaddlebagCustodyAuthority authority = new SaddlebagCustodyAuthority(binaryReader2.ReadInt64(), binaryReader2.ReadInt64(), binaryReader2.ReadInt64(), binaryReader2.ReadUInt16(), binaryReader2.ReadInt64(), binaryReader2.ReadUInt16(), binaryReader2.ReadBoolean(), binaryReader2.ReadBoolean(), binaryReader2.ReadInt64()); SaddlebagCustodyBinding result = new SaddlebagCustodyBinding(parent, preparedHash, parentHash, destination, authority); if (memoryStream2.Position != memoryStream2.Length) { throw new InvalidDataException("Trailing binding body data."); } return result; } } internal static class SaddlebagCustodyCodec { private const int Magic = 1396851505; private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); internal static byte[] Encode(SaddlebagCustodyRecord record) { byte[] array; using (MemoryStream memoryStream = new MemoryStream()) { using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); SaddlebagCustodyIntent intent = record.Intent; binaryWriter.Write(intent.WorldUid); Entity(binaryWriter, intent.Source); Entity(binaryWriter, intent.Destination); Text(binaryWriter, intent.DeathAttempt); binaryWriter.Write(intent.Generation); Blob(binaryWriter, intent.SourcePayload); Blob(binaryWriter, intent.DestinationBefore); Blob(binaryWriter, intent.DestinationExpected); binaryWriter.Write(record.Revision); binaryWriter.Write((int)record.State); Text(binaryWriter, record.PreviousHash); Text(binaryWriter, record.ChangeId); binaryWriter.Write(record.CreatedUtcTicks); SaddlebagCustodyAuthority authority = record.Authority; binaryWriter.Write(authority.ServerPeer); binaryWriter.Write(authority.SenderPeer); binaryWriter.Write(authority.SourceOwner); binaryWriter.Write(authority.SourceRevision); binaryWriter.Write(authority.DestinationOwner); binaryWriter.Write(authority.DestinationRevision); binaryWriter.Write(authority.SourcePresent); binaryWriter.Write(authority.DestinationPresent); binaryWriter.Write(authority.CapturedUtcTicks); Proof(binaryWriter, record.Evidence); binaryWriter.Flush(); array = memoryStream.ToArray(); } using MemoryStream memoryStream2 = new MemoryStream(); using BinaryWriter binaryWriter2 = new BinaryWriter(memoryStream2); binaryWriter2.Write(1396851505); binaryWriter2.Write(1); binaryWriter2.Write(array.Length); binaryWriter2.Write(array); Text(binaryWriter2, SaddlebagCustodyHash.Bytes(array)); binaryWriter2.Flush(); if (memoryStream2.Length > 1048576) { throw new InvalidDataException("Record too large."); } return memoryStream2.ToArray(); } internal static SaddlebagCustodyRecord Decode(byte[] bytes) { if (bytes == null || bytes.Length > 1048576) { throw new InvalidDataException("Invalid record length."); } byte[] array; using (MemoryStream memoryStream = new MemoryStream(bytes, writable: false)) { using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadInt32() != 1396851505 || binaryReader.ReadInt32() != 1) { throw new InvalidDataException("Unsupported custody format."); } int count = binaryReader.ReadInt32(); array = Exact(binaryReader, count, 1048576); if (Text(binaryReader) != SaddlebagCustodyHash.Bytes(array) || memoryStream.Position != memoryStream.Length) { throw new InvalidDataException("Custody integrity mismatch."); } } using MemoryStream memoryStream2 = new MemoryStream(array, writable: false); using BinaryReader binaryReader2 = new BinaryReader(memoryStream2); long world = binaryReader2.ReadInt64(); SaddlebagCustodyEntity saddlebagCustodyEntity = Entity(binaryReader2); SaddlebagCustodyEntity to = Entity(binaryReader2); string deathAttempt = Text(binaryReader2); long generation = binaryReader2.ReadInt64(); SaddlebagCustodyIntent intent = new SaddlebagCustodyIntent(world, saddlebagCustodyEntity, to, deathAttempt, generation, Blob(binaryReader2), Blob(binaryReader2), Blob(binaryReader2)); int revision = binaryReader2.ReadInt32(); SaddlebagCustodyState state = (SaddlebagCustodyState)binaryReader2.ReadInt32(); string previous = Text(binaryReader2); string change = Text(binaryReader2); long ticks = binaryReader2.ReadInt64(); SaddlebagCustodyAuthority authority = new SaddlebagCustodyAuthority(binaryReader2.ReadInt64(), binaryReader2.ReadInt64(), binaryReader2.ReadInt64(), binaryReader2.ReadUInt16(), binaryReader2.ReadInt64(), binaryReader2.ReadUInt16(), binaryReader2.ReadBoolean(), binaryReader2.ReadBoolean(), binaryReader2.ReadInt64()); SaddlebagCustodyRecord result = new SaddlebagCustodyRecord(intent, revision, state, previous, change, ticks, authority, Proof(binaryReader2)); if (memoryStream2.Position != memoryStream2.Length) { throw new InvalidDataException("Trailing custody data."); } return result; } internal static string ChangeId(string operation, int expectedRevision, SaddlebagCustodyState state, SaddlebagCustodyEvidence proof) { using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); Text(binaryWriter, operation); binaryWriter.Write(expectedRevision); binaryWriter.Write((int)state); Proof(binaryWriter, proof); binaryWriter.Flush(); return SaddlebagCustodyHash.Bytes(memoryStream.ToArray()); } private static void Proof(BinaryWriter w, SaddlebagCustodyEvidence e) { w.Write(e.ApplicationObserved); w.Write(e.WorldPersistenceObserved); w.Write(e.ReconciliationObserved); Text(w, e.DestinationHash); Text(w, e.WorldSaveIdentity); Text(w, e.Description); } private static SaddlebagCustodyEvidence Proof(BinaryReader r) { return new SaddlebagCustodyEvidence(r.ReadBoolean(), r.ReadBoolean(), r.ReadBoolean(), Text(r), Text(r), Text(r)); } private static void Entity(BinaryWriter w, SaddlebagCustodyEntity e) { w.Write(e != null); if (e != null) { w.Write(e.UserId); w.Write(e.ObjectId); w.Write(e.Prefab); } } private static SaddlebagCustodyEntity Entity(BinaryReader r) { if (!r.ReadBoolean()) { return null; } return new SaddlebagCustodyEntity(r.ReadInt64(), r.ReadUInt32(), r.ReadInt32()); } internal static void Text(BinaryWriter w, string text) { SaddlebagCustodyHash.CheckText(text); byte[] bytes = Utf8.GetBytes(text); w.Write(bytes.Length); w.Write(bytes); } internal static string Text(BinaryReader r) { return Utf8.GetString(Exact(r, r.ReadInt32(), 1024)); } internal static void Blob(BinaryWriter w, byte[] bytes) { w.Write((bytes == null) ? (-1) : bytes.Length); if (bytes != null) { w.Write(bytes); } } internal static byte[] Blob(BinaryReader r) { int num = r.ReadInt32(); if (num != -1) { return Exact(r, num, 262144); } return null; } internal static byte[] Exact(BinaryReader r, int count, int maximum) { if (count < 0 || count > maximum || count > r.BaseStream.Length - r.BaseStream.Position) { throw new InvalidDataException("Invalid bounded field length."); } byte[] array = r.ReadBytes(count); if (array.Length != count) { throw new EndOfStreamException(); } return array; } } internal sealed class SaddlebagCustodyAuthorityExpectation { internal readonly long SourceOwner; internal readonly long DestinationOwner; internal readonly ushort SourceRevision; internal readonly ushort DestinationRevision; internal SaddlebagCustodyAuthorityExpectation(long sourceOwner, ushort sourceRevision, long targetOwner, ushort targetRevision) { SourceOwner = sourceOwner; SourceRevision = sourceRevision; DestinationOwner = targetOwner; DestinationRevision = targetRevision; } } internal interface ISaddlebagCustodyServerVerifier { bool TryObserve(SaddlebagCustodyRecord operation, SaddlebagCustodyState next, out SaddlebagCustodyEvidence evidence, out string failure); } internal sealed class SaddlebagCustodyCoordinator { private readonly int mainThread; private readonly long world; private readonly ZNet network; private readonly SaddlebagCustodyStore store; private readonly ISaddlebagCustodyServerVerifier verifier; private SaddlebagCustodyCoordinator(SaddlebagCustodyPathRequest paths, ZNet net, long worldUid, int thread, ISaddlebagCustodyServerVerifier serverVerifier) { network = net; world = worldUid; mainThread = thread; verifier = serverVerifier; store = new SaddlebagCustodyStore(paths, world, mainThread); } internal static SaddlebagCustodyCoordinator CreateForCurrentServer(ISaddlebagCustodyServerVerifier verifier = null, SaddlebagCustodyPathOptions pathOptions = null, ISaddlebagCustodyPathEnvironment pathEnvironment = null) { RequireUnityContext(); ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer() || instance.GetWorldUID() == 0) { throw new InvalidOperationException("Custody coordinator requires the current host/server world."); } string legacy = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Paths.ConfigPath, "TameMate"), "saddlebags-custody"), "v1"), "world_" + instance.GetWorldUID().ToString(CultureInfo.InvariantCulture)); return new SaddlebagCustodyCoordinator(new SaddlebagCustodyPathRequest(legacy, pathOptions, pathEnvironment), instance, instance.GetWorldUID(), Thread.CurrentThread.ManagedThreadId, verifier); } private static void RequireUnityContext() { SynchronizationContext current = SynchronizationContext.Current; if (current == null || current.GetType().FullName != "UnityEngine.UnitySynchronizationContext") { throw new InvalidOperationException("Unity main-thread context required; no Unity API was accessed."); } } private void RequireServer() { if (Thread.CurrentThread.ManagedThreadId != mainThread) { throw new InvalidOperationException("Unity thread required."); } RequireUnityContext(); if ((Object)(object)ZNet.instance != (Object)(object)network || (Object)(object)network == (Object)null || !network.IsServer() || network.GetWorldUID() != world) { throw new InvalidOperationException("Server/world session changed; close the old store."); } } internal Task InitializeAsync() { RequireServer(); return store.Schedule(store.Initialize); } internal Task ReadRecoveryAsync() { RequireServer(); return store.Schedule(store.Recovery); } internal Task PrepareFromTransportAsync(SaddlebagCustodyIntent intent, long actualRpcSender, SaddlebagCustodyAuthorityExpectation expected) { RequireServer(); if (intent == null || expected == null || intent.WorldUid != world || ZDOMan.instance == null) { throw new InvalidOperationException("Invalid world/authority request."); } long sessionID = ZDOMan.GetSessionID(); if (actualRpcSender == 0 || (actualRpcSender != sessionID && (network.GetPeer(actualRpcSender) == null || !network.GetPeer(actualRpcSender).IsReady()))) { throw new InvalidOperationException("Unauthenticated sender."); } ZDO val = Entity(intent.Source); if (val == null || val.GetOwner() != actualRpcSender || val.GetOwner() != expected.SourceOwner || val.OwnerRevision != expected.SourceRevision) { throw new InvalidOperationException("Source owner/revision changed."); } byte[] byteArray = val.GetByteArray(ZDOVars.s_items, (byte[])null); if (byteArray == null || byteArray.Length == 0) { byteArray = val.GetByteArray(StringExtensionMethods.GetStableHashCode("tm_saddlebags"), (byte[])null); } if (byteArray != null && byteArray.Length > 262144) { throw new InvalidOperationException("Source payload exceeds custody limits."); } if (SaddlebagCustodyHash.Bytes(byteArray) != SaddlebagCustodyHash.Bytes(intent.SourcePayload)) { throw new InvalidOperationException("Source payload is not the server-observed serialized inventory."); } ZDO val2 = Entity(intent.Destination); byte[] array = ((val2 == null) ? null : val2.GetByteArray(ZDOVars.s_items, (byte[])null)); if (array != null && array.Length > 262144) { throw new InvalidOperationException("Destination payload exceeds custody limits."); } if (intent.Destination != null && (val2 == null || val2.GetOwner() != expected.DestinationOwner || val2.OwnerRevision != expected.DestinationRevision || SaddlebagCustodyHash.Bytes(array) != SaddlebagCustodyHash.Bytes(intent.DestinationBefore))) { throw new InvalidOperationException("Destination preimage/authority changed."); } SaddlebagCustodyAuthority captured = Capture(sessionID, actualRpcSender, val, val2); return store.Schedule(() => store.Prepare(intent, captured)); } internal Task BindDestinationOnServerAsync(SaddlebagCustodyRecord operation, SaddlebagCustodyDestination destination, SaddlebagCustodyAuthorityExpectation expected) { RequireServer(); if (operation == null || operation.Intent.WorldUid != world || operation.Intent.Destination != null || destination == null || expected == null || ZDOMan.instance == null) { throw new InvalidOperationException("Invalid deferred destination request."); } ZDO val = Entity(operation.Intent.Source); ZDO val2 = Entity(destination.Entity); if (val == null || val2 == null || val.GetOwner() != expected.SourceOwner || val.OwnerRevision != expected.SourceRevision || val.GetOwner() != operation.Authority.SourceOwner || val.OwnerRevision != operation.Authority.SourceRevision || val2.GetOwner() != destination.Owner || val2.OwnerRevision != destination.OwnerRevision || val2.GetOwner() != expected.DestinationOwner || val2.OwnerRevision != expected.DestinationRevision) { throw new InvalidOperationException("Destination/source presence, owner or authority revision changed."); } byte[] byteArray = val.GetByteArray(ZDOVars.s_items, (byte[])null); if (byteArray == null || byteArray.Length == 0) { byteArray = val.GetByteArray(StringExtensionMethods.GetStableHashCode("tm_saddlebags"), (byte[])null); } byte[] byteArray2 = val2.GetByteArray(ZDOVars.s_items, (byte[])null); if ((byteArray != null && byteArray.Length > 262144) || (byteArray2 != null && byteArray2.Length > 262144) || SaddlebagCustodyHash.Bytes(byteArray) != SaddlebagCustodyHash.Bytes(operation.Intent.SourcePayload) || SaddlebagCustodyHash.Bytes(byteArray2) != SaddlebagCustodyHash.Bytes(destination.Before)) { throw new InvalidOperationException("Server-observed inventory bytes contradict the binding request."); } long sessionID = ZDOMan.GetSessionID(); SaddlebagCustodyAuthority captured = Capture(sessionID, sessionID, val, val2); return store.Schedule(() => store.BindDestination(operation, destination, captured)); } internal Task AdvanceOnServerAsync(SaddlebagCustodyRecord expected, SaddlebagCustodyState next) { RequireServer(); if (expected == null || expected.Intent.WorldUid != world || ZDOMan.instance == null) { throw new InvalidOperationException("Invalid operation."); } ZDO val = Entity(expected.Intent.Source); ZDO val2 = Entity(expected.EffectiveDestination); SaddlebagCustodyAuthority saddlebagCustodyAuthority = ((expected.Binding != null && expected.Revision == expected.Binding.Parent.Revision) ? expected.Binding.Authority : expected.Authority); if (next != SaddlebagCustodyState.REQUIRES_MANUAL_REVIEW && (val != null != saddlebagCustodyAuthority.SourcePresent || val2 != null != saddlebagCustodyAuthority.DestinationPresent || (val != null && (val.GetOwner() != saddlebagCustodyAuthority.SourceOwner || val.OwnerRevision != saddlebagCustodyAuthority.SourceRevision)) || (val2 != null && (val2.GetOwner() != saddlebagCustodyAuthority.DestinationOwner || val2.OwnerRevision != saddlebagCustodyAuthority.DestinationRevision)))) { throw new InvalidOperationException("Authority revision changed; retain for review instead of advancing."); } SaddlebagCustodyEvidence proof = SaddlebagCustodyEvidence.None; if (next != SaddlebagCustodyState.PENDING && next != SaddlebagCustodyState.REQUIRES_MANUAL_REVIEW) { string failure = "No server application/persistence verifier is installed in A-01.1."; if (verifier == null || !verifier.TryObserve(expected, next, out proof, out failure) || proof == null) { throw new InvalidOperationException(failure ?? "Server verification denied."); } } long sessionID = ZDOMan.GetSessionID(); SaddlebagCustodyAuthority captured = Capture(sessionID, sessionID, val, val2); return store.Schedule(() => store.Advance(expected, next, captured, proof)); } private static ZDO Entity(SaddlebagCustodyEntity identity) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (identity == null) { return null; } ZDO zDO = ZDOMan.instance.GetZDO(new ZDOID(identity.UserId, identity.ObjectId)); if (zDO != null && zDO.GetPrefab() != identity.Prefab) { throw new InvalidOperationException("Entity prefab identity contradiction."); } return zDO; } private static SaddlebagCustodyAuthority Capture(long server, long sender, ZDO source, ZDO target) { return new SaddlebagCustodyAuthority(server, sender, (source == null) ? 0 : source.GetOwner(), (ushort)((source != null) ? source.OwnerRevision : 0), (target == null) ? 0 : target.GetOwner(), (ushort)((target != null) ? target.OwnerRevision : 0), source != null, target != null, DateTime.UtcNow.Ticks); } internal Task CloseAsync() { if (Thread.CurrentThread.ManagedThreadId != mainThread) { throw new InvalidOperationException("Owning thread required."); } return store.Schedule(store.Close); } } internal enum SaddlebagCustodyState { PREPARED = 1, PENDING, APPLIED, PERSISTENCE_UNCONFIRMED, RECONCILED, REQUIRES_MANUAL_REVIEW } internal static class SaddlebagCustodyLimits { internal const int Format = 1; internal const int PayloadBytes = 262144; internal const int RecordBytes = 1048576; internal const int Operations = 1024; internal const int Revisions = 64; internal const long StoreBytes = 67108864L; internal const int QueuedWork = 8; internal const int TextBytes = 1024; internal const int AuthorityAgeSeconds = 10; } internal sealed class SaddlebagCustodyEntity { internal readonly long UserId; internal readonly uint ObjectId; internal readonly int Prefab; internal string Key { get { string[] array = new string[5]; long userId = UserId; array[0] = userId.ToString(CultureInfo.InvariantCulture); array[1] = ":"; uint objectId = ObjectId; array[2] = objectId.ToString(CultureInfo.InvariantCulture); array[3] = ":"; int prefab = Prefab; array[4] = prefab.ToString(CultureInfo.InvariantCulture); return string.Concat(array); } } internal SaddlebagCustodyEntity(long userId, uint objectId, int prefab) { if (userId == 0 || objectId == 0 || prefab == 0) { throw new ArgumentException("Incomplete entity identity."); } UserId = userId; ObjectId = objectId; Prefab = prefab; } internal bool Same(SaddlebagCustodyEntity other) { if (other != null) { return Key == other.Key; } return false; } } internal sealed class SaddlebagCustodyIntent { internal readonly long WorldUid; internal readonly SaddlebagCustodyEntity Source; internal readonly SaddlebagCustodyEntity Destination; internal readonly string DeathAttempt; internal readonly long Generation; private readonly byte[] source; private readonly byte[] destinationBefore; private readonly byte[] destinationExpected; internal byte[] SourcePayload => Copy(source); internal byte[] DestinationBefore => Copy(destinationBefore); internal byte[] DestinationExpected => Copy(destinationExpected); internal string Slot { get { string[] array = new string[7]; long worldUid = WorldUid; array[0] = worldUid.ToString(CultureInfo.InvariantCulture); array[1] = "|"; long userId = Source.UserId; array[2] = userId.ToString(CultureInfo.InvariantCulture); array[3] = "|"; uint objectId = Source.ObjectId; array[4] = objectId.ToString(CultureInfo.InvariantCulture); array[5] = "|"; long generation = Generation; array[6] = generation.ToString(CultureInfo.InvariantCulture); return SaddlebagCustodyHash.Text(string.Concat(array)); } } internal string OperationId => SaddlebagCustodyHash.Text(Slot + "|" + DeathAttempt); internal string PayloadHash => SaddlebagCustodyHash.Text(SaddlebagCustodyHash.Bytes(source) + "|" + SaddlebagCustodyHash.Bytes(destinationBefore) + "|" + SaddlebagCustodyHash.Bytes(destinationExpected)); internal SaddlebagCustodyIntent(long world, SaddlebagCustodyEntity from, SaddlebagCustodyEntity to, string deathAttempt, long generation, byte[] sourcePayload, byte[] targetBefore, byte[] targetExpected) { if (world == 0 || from == null || generation <= 0 || !Guid.TryParseExact(deathAttempt, "N", out var result) || result == Guid.Empty) { throw new ArgumentException("World, source, death attempt and generation are required."); } if (to != null && to.UserId == from.UserId && to.ObjectId == from.ObjectId) { throw new ArgumentException("Source equals destination."); } if (sourcePayload == null || sourcePayload.Length == 0) { throw new ArgumentException("Missing source custody payload."); } if (to == null && (targetBefore != null || targetExpected != null)) { throw new ArgumentException("Destination payload without identity."); } WorldUid = world; Source = from; Destination = to; DeathAttempt = result.ToString("N"); Generation = generation; source = Copy(sourcePayload); destinationBefore = Copy(targetBefore); destinationExpected = Copy(targetExpected); } private static byte[] Copy(byte[] bytes) { if (bytes == null) { return null; } if (bytes.Length > 262144) { throw new ArgumentException("Custody payload limit exceeded."); } return (byte[])bytes.Clone(); } internal bool Same(SaddlebagCustodyIntent other) { if (other != null && WorldUid == other.WorldUid && Generation == other.Generation && DeathAttempt == other.DeathAttempt && OperationId == other.OperationId && Source.Same(other.Source) && ((Destination == null && other.Destination == null) || (Destination != null && Destination.Same(other.Destination)))) { return PayloadHash == other.PayloadHash; } return false; } } internal sealed class SaddlebagCustodyAuthority { internal readonly long ServerPeer; internal readonly long SenderPeer; internal readonly long SourceOwner; internal readonly long DestinationOwner; internal readonly ushort SourceRevision; internal readonly ushort DestinationRevision; internal readonly bool SourcePresent; internal readonly bool DestinationPresent; internal readonly long CapturedUtcTicks; internal bool Fresh { get { long num = DateTime.UtcNow.Ticks - CapturedUtcTicks; if (num >= 0) { return num <= TimeSpan.FromSeconds(10.0).Ticks; } return false; } } internal SaddlebagCustodyAuthority(long server, long sender, long sourceOwner, ushort sourceRevision, long targetOwner, ushort targetRevision, bool sourcePresent, bool targetPresent, long ticks) { if (server != 0 && sender != 0 && ticks > 0) { DateTime maxValue = DateTime.MaxValue; if (ticks <= maxValue.Ticks && (sourcePresent || (sourceOwner == 0 && sourceRevision == 0)) && (targetPresent || (targetOwner == 0 && targetRevision == 0))) { ServerPeer = server; SenderPeer = sender; SourceOwner = sourceOwner; SourceRevision = sourceRevision; DestinationOwner = targetOwner; DestinationRevision = targetRevision; CapturedUtcTicks = ticks; SourcePresent = sourcePresent; DestinationPresent = targetPresent; return; } } throw new ArgumentException("Invalid authority evidence."); } } internal sealed class SaddlebagCustodyEvidence { internal readonly bool ApplicationObserved; internal readonly bool WorldPersistenceObserved; internal readonly bool ReconciliationObserved; internal readonly string DestinationHash; internal readonly string WorldSaveIdentity; internal readonly string Description; internal static SaddlebagCustodyEvidence None => new SaddlebagCustodyEvidence(applied: false, persisted: false, reconciled: false, "", "", ""); internal SaddlebagCustodyEvidence(bool applied, bool persisted, bool reconciled, string targetHash, string worldSaveIdentity, string description) { ApplicationObserved = applied; WorldPersistenceObserved = persisted; ReconciliationObserved = reconciled; DestinationHash = targetHash ?? ""; WorldSaveIdentity = worldSaveIdentity ?? ""; Description = description ?? ""; if ((persisted && !applied) || (reconciled && !persisted)) { throw new ArgumentException("Inconsistent custody evidence."); } SaddlebagCustodyHash.CheckText(DestinationHash); SaddlebagCustodyHash.CheckText(WorldSaveIdentity); SaddlebagCustodyHash.CheckText(Description); if (applied && !SaddlebagCustodyHash.IsHash(DestinationHash)) { throw new ArgumentException("Missing destination hash."); } if (persisted && string.IsNullOrEmpty(WorldSaveIdentity)) { throw new ArgumentException("Missing world save identity."); } } } internal static class SaddlebagCustodyPolicy { internal static bool Allows(SaddlebagCustodyState from, SaddlebagCustodyState to, SaddlebagCustodyIntent intent, SaddlebagCustodyEvidence proof) { return Allows(from, to, intent, proof, null); } internal static bool Allows(SaddlebagCustodyState from, SaddlebagCustodyState to, SaddlebagCustodyIntent intent, SaddlebagCustodyEvidence proof, SaddlebagCustodyBinding binding) { if (intent == null || !Enum.IsDefined(typeof(SaddlebagCustodyState), from) || !Enum.IsDefined(typeof(SaddlebagCustodyState), to)) { return false; } if (binding != null && !binding.IsFor(intent)) { return false; } SaddlebagCustodyEntity saddlebagCustodyEntity = ((binding == null) ? intent.Destination : binding.Destination.Entity); byte[] array = ((binding == null) ? intent.DestinationExpected : binding.Destination.Expected); if (from == SaddlebagCustodyState.RECONCILED || from == SaddlebagCustodyState.REQUIRES_MANUAL_REVIEW || from == to || proof == null) { return false; } switch (to) { case SaddlebagCustodyState.REQUIRES_MANUAL_REVIEW: return true; case SaddlebagCustodyState.PENDING: if (from == SaddlebagCustodyState.PREPARED) { return !proof.ApplicationObserved; } return false; case SaddlebagCustodyState.APPLIED: if ((from == SaddlebagCustodyState.PREPARED || from == SaddlebagCustodyState.PENDING) && saddlebagCustodyEntity != null && array != null && proof.ApplicationObserved && !proof.WorldPersistenceObserved && !proof.ReconciliationObserved) { return proof.DestinationHash == SaddlebagCustodyHash.Bytes(array); } return false; case SaddlebagCustodyState.PERSISTENCE_UNCONFIRMED: if (from == SaddlebagCustodyState.APPLIED && proof.ApplicationObserved && !proof.WorldPersistenceObserved) { return proof.DestinationHash == SaddlebagCustodyHash.Bytes(array); } return false; case SaddlebagCustodyState.RECONCILED: if (from == SaddlebagCustodyState.PERSISTENCE_UNCONFIRMED && proof.ApplicationObserved && proof.WorldPersistenceObserved && proof.ReconciliationObserved && array != null) { return proof.DestinationHash == SaddlebagCustodyHash.Bytes(array); } return false; default: return false; } } } internal sealed class SaddlebagCustodyRecord { internal readonly SaddlebagCustodyIntent Intent; internal readonly int Revision; internal readonly SaddlebagCustodyState State; internal readonly string PreviousHash; internal readonly string ChangeId; internal readonly long CreatedUtcTicks; internal readonly SaddlebagCustodyAuthority Authority; internal readonly SaddlebagCustodyEvidence Evidence; internal readonly SaddlebagCustodyBinding Binding; internal SaddlebagCustodyEntity EffectiveDestination { get { if (Binding != null) { return Binding.Destination.Entity; } return Intent.Destination; } } internal string BindingHash { get { if (Binding != null) { return Binding.Hash; } return ""; } } internal SaddlebagCustodyRecord WithBinding(SaddlebagCustodyBinding binding) { return new SaddlebagCustodyRecord(Intent, Revision, State, PreviousHash, ChangeId, CreatedUtcTicks, Authority, Evidence, binding); } internal SaddlebagCustodyRecord(SaddlebagCustodyIntent intent, int revision, SaddlebagCustodyState state, string previous, string change, long ticks, SaddlebagCustodyAuthority authority, SaddlebagCustodyEvidence evidence, SaddlebagCustodyBinding binding = null) { if (intent != null && authority != null && evidence != null && revision >= 1 && revision <= 64 && Enum.IsDefined(typeof(SaddlebagCustodyState), state) && ticks > 0) { DateTime maxValue = DateTime.MaxValue; if (ticks <= maxValue.Ticks && SaddlebagCustodyHash.IsHash(change) && !((revision == 1) ? (!string.IsNullOrEmpty(previous)) : (!SaddlebagCustodyHash.IsHash(previous)))) { if (revision == 1 && (state != SaddlebagCustodyState.PREPARED || evidence.ApplicationObserved)) { throw new ArgumentException("Invalid initial state."); } if (binding != null && (!binding.IsFor(intent) || binding.Parent.Revision > revision)) { throw new ArgumentException("Invalid attached binding."); } Intent = intent; Revision = revision; State = state; PreviousHash = previous ?? ""; ChangeId = change; CreatedUtcTicks = ticks; Authority = authority; Evidence = evidence; Binding = binding; return; } } throw new ArgumentException("Invalid custody record."); } } internal static class SaddlebagCustodyHash { internal static string Bytes(byte[] bytes) { if (bytes == null) { return "absent"; } using SHA256 sHA = SHA256.Create(); return BitConverter.ToString(sHA.ComputeHash(bytes)).Replace("-", ""); } internal static string Text(string text) { return Bytes(Encoding.UTF8.GetBytes(text)); } internal static bool IsHash(string value) { if (value == null || value.Length != 64) { return false; } foreach (char c in value) { if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { return false; } } return true; } internal static void CheckText(string value) { if (value == null || Encoding.UTF8.GetByteCount(value) > 1024) { throw new ArgumentException("Custody text limit exceeded."); } } } internal enum SaddlebagCustodyDirectoryLayout { LegacyHex = 1, CompactBase32 } internal sealed class SaddlebagCustodyPathOptions { internal readonly string OverrideRoot; internal readonly string RecoveryWorldRoot; internal readonly SaddlebagCustodyDirectoryLayout RecoveryLayout; private readonly string[] previous; internal string[] PreviousWorldRoots => (string[])previous.Clone(); internal SaddlebagCustodyPathOptions(string overrideRoot = null, string recoveryWorldRoot = null, SaddlebagCustodyDirectoryLayout recoveryLayout = SaddlebagCustodyDirectoryLayout.LegacyHex, string[] previousWorldRoots = null) { if (overrideRoot != null && recoveryWorldRoot != null) { throw new ArgumentException("Choose an active root OR read-only recovery."); } if (!Enum.IsDefined(typeof(SaddlebagCustodyDirectoryLayout), recoveryLayout)) { throw new ArgumentException("Unknown directory layout."); } if (previousWorldRoots != null && previousWorldRoots.Length > 8) { throw new ArgumentException("Too many previous roots."); } OverrideRoot = overrideRoot; RecoveryWorldRoot = recoveryWorldRoot; RecoveryLayout = recoveryLayout; previous = ((previousWorldRoots == null) ? new string[0] : ((string[])previousWorldRoots.Clone())); } } internal interface ISaddlebagCustodyPathEnvironment { string LocalDataDirectory(); string ConfiguredRoot(); long AvailableBytes(string directory); } internal sealed class SaddlebagCustodyNativePathEnvironment : ISaddlebagCustodyPathEnvironment { public string LocalDataDirectory() { return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } public string ConfiguredRoot() { return Environment.GetEnvironmentVariable("TAMEMATE_CUSTODY_ROOT"); } public long AvailableBytes(string directory) { DriveInfo driveInfo = new DriveInfo(Path.GetPathRoot(directory)); if (!driveInfo.IsReady) { throw new IOException("Custody volume unavailable."); } if (driveInfo.DriveType == DriveType.Network || driveInfo.DriveType == DriveType.CDRom || driveInfo.DriveType == DriveType.NoRootDirectory || driveInfo.DriveType == DriveType.Unknown) { throw new IOException("Custody requires an available local writable volume, not a mapped/network/unknown drive."); } return driveInfo.AvailableFreeSpace; } } internal sealed class SaddlebagCustodyPathRequest { internal readonly string LegacyWorldRoot; internal readonly SaddlebagCustodyPathOptions Options; internal readonly ISaddlebagCustodyPathEnvironment Environment; internal SaddlebagCustodyPathRequest(string legacy, SaddlebagCustodyPathOptions options, ISaddlebagCustodyPathEnvironment environment) { LegacyWorldRoot = legacy; Options = options ?? new SaddlebagCustodyPathOptions(); Environment = environment ?? new SaddlebagCustodyNativePathEnvironment(); } } internal static class SaddlebagCustodyPaths { internal const int MaximumFilePath = 259; internal const int MaximumDirectoryPath = 247; private const string Alphabet = "abcdefghijklmnopqrstuvwxyz234567"; internal static StringComparison PathComparison { get { if (Path.DirectorySeparatorChar != '\\') { return StringComparison.Ordinal; } return StringComparison.OrdinalIgnoreCase; } } internal static string WorldName(long uid) { if (uid == 0) { throw new ArgumentException("World UID required."); } return "w" + uid.ToString("x16", CultureInfo.InvariantCulture); } internal static string OperationName(string slot) { if (!SaddlebagCustodyHash.IsHash(slot)) { throw new ArgumentException("Invalid operation slot."); } StringBuilder stringBuilder = new StringBuilder("o"); int num = 0; int num2 = 0; for (int i = 0; i < 32; i++) { num = (num << 8) | Convert.ToByte(slot.Substring(i * 2, 2), 16); num2 += 8; while (num2 >= 5) { num2 -= 5; stringBuilder.Append("abcdefghijklmnopqrstuvwxyz234567"[(num >> num2) & 0x1F]); } num &= (1 << num2) - 1; } if (num2 > 0) { stringBuilder.Append("abcdefghijklmnopqrstuvwxyz234567"[(num << 5 - num2) & 0x1F]); } return stringBuilder.ToString(); } internal static bool IsOperationName(string name) { if (name == null || name.Length != 53 || name[0] != 'o') { return false; } for (int i = 1; i < name.Length; i++) { if ("abcdefghijklmnopqrstuvwxyz234567".IndexOf(name[i]) < 0) { return false; } } return true; } internal static string DirectoryPath(string raw) { if (string.IsNullOrEmpty(raw) || !Path.IsPathRooted(raw) || raw.StartsWith("\\\\", StringComparison.Ordinal) || raw.StartsWith("//", StringComparison.Ordinal)) { throw new ArgumentException("Custody requires an explicit absolute local path; no UNC/device/relative paths."); } for (int i = 0; i < raw.Length; i++) { char c = raw[i]; if (c < ' ' || "<>\"|?*".IndexOf(c) >= 0 || (c == ':' && (Path.DirectorySeparatorChar != '\\' || i != 1 || !char.IsLetter(raw[0])))) { throw new ArgumentException("Invalid custody path character."); } } if (Path.DirectorySeparatorChar == '\\' && (raw.Length < 3 || raw[1] != ':' || (raw[2] != '\\' && raw[2] != '/'))) { throw new ArgumentException("Drive-relative custody paths are not supported."); } string[] array = raw.Split(new char[2] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text in array2) { if (text.EndsWith(":", StringComparison.Ordinal)) { continue; } string text2 = text.Split(new char[1] { '.' })[0].ToUpperInvariant(); if (!(text == ".") && !(text == "..") && !text.EndsWith(".", StringComparison.Ordinal) && !text.EndsWith(" ", StringComparison.Ordinal)) { switch (text2) { default: if (text2.Length != 4 || (!text2.StartsWith("COM", StringComparison.Ordinal) && !text2.StartsWith("LPT", StringComparison.Ordinal)) || text2[3] < '1' || text2[3] > '9') { continue; } break; case "CON": case "PRN": case "AUX": case "NUL": break; } } throw new ArgumentException("Ambiguous/reserved custody path component."); } string text3 = Path.GetFullPath(raw); string pathRoot = Path.GetPathRoot(text3); while (text3.Length > pathRoot.Length && (text3.EndsWith("\\", StringComparison.Ordinal) || text3.EndsWith("/", StringComparison.Ordinal))) { text3 = text3.Substring(0, text3.Length - 1); } if (text3.Length > 247) { throw new PathTooLongException("Custody directory exceeds the portable path budget."); } return text3; } internal static void FilePath(string path) { if (path.Length > 259) { throw new PathTooLongException("Custody file exceeds the portable path budget."); } } internal static void WorldBudget(string root, SaddlebagCustodyDirectoryLayout layout, bool readOnly) { DirectoryPath(root); string path = ((layout == SaddlebagCustodyDirectoryLayout.LegacyHex) ? new string('A', 64) : ("o" + new string('a', 52))); DirectoryPath(Path.Combine(root, path)); FilePath(Path.Combine(Path.Combine(root, path), readOnly ? "00000064.sbcu" : ("incomplete-" + new string('0', 32) + ".tmp"))); FilePath(Path.Combine(root, "coordinator.lock")); } internal static bool Same(string a, string b) { return string.Equals(a, b, PathComparison); } internal static bool Contains(string parent, string child) { if (!Same(parent, child)) { return child.StartsWith(parent.TrimEnd(new char[1] { Path.DirectorySeparatorChar }) + Path.DirectorySeparatorChar, PathComparison); } return true; } internal static bool Exists(string path) { try { FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.ReparsePoint) != FileAttributes.None) { throw new IOException("Reparse point denied in custody path."); } if ((attributes & FileAttributes.Directory) == 0) { throw new IOException("Expected custody directory, found a file."); } return true; } catch (DirectoryNotFoundException) { return false; } catch (FileNotFoundException) { return false; } } internal static void NoLinks(string path) { for (DirectoryInfo directoryInfo = new DirectoryInfo(path); directoryInfo != null; directoryInfo = directoryInfo.Parent) { Exists(directoryInfo.FullName); } } } internal sealed class SaddlebagCustodyPathSession : IDisposable { internal readonly string WorldDirectory; internal readonly SaddlebagCustodyDirectoryLayout Layout; internal readonly bool ReadOnly; private readonly long world; private readonly string marker; private readonly ISaddlebagCustodyPathEnvironment environment; private readonly List guards = new List(); private bool bound; private SaddlebagCustodyPathSession(string directory, SaddlebagCustodyDirectoryLayout layout, bool readOnly, long uid, string markerPath, ISaddlebagCustodyPathEnvironment env) { WorldDirectory = directory; Layout = layout; ReadOnly = readOnly; world = uid; marker = markerPath; environment = env; } internal static SaddlebagCustodyPathSession Open(SaddlebagCustodyPathRequest request, long world, int unityThread) { if (Thread.CurrentThread.ManagedThreadId == unityThread) { throw new InvalidOperationException("Root selection requires the filesystem worker."); } string path = SaddlebagCustodyPaths.DirectoryPath(request.Environment.LocalDataDirectory()); string path2 = Path.Combine(Path.Combine(path, "TameMate"), "sbc"); string text = Path.Combine(Path.Combine(path2, "v2"), SaddlebagCustodyPaths.WorldName(world)); string text2 = request.Options.OverrideRoot; if (text2 == null && request.Options.RecoveryWorldRoot == null) { text2 = request.Environment.ConfiguredRoot(); } bool flag = request.Options.RecoveryWorldRoot != null; string raw = (flag ? SaddlebagCustodyPaths.DirectoryPath(request.Options.RecoveryWorldRoot) : ((text2 == null) ? text : Path.Combine(SaddlebagCustodyPaths.DirectoryPath(text2), SaddlebagCustodyPaths.WorldName(world)))); SaddlebagCustodyDirectoryLayout layout = (flag ? request.Options.RecoveryLayout : SaddlebagCustodyDirectoryLayout.CompactBase32); raw = SaddlebagCustodyPaths.DirectoryPath(raw); SaddlebagCustodyPaths.WorldBudget(raw, layout, flag); string text3 = SaddlebagCustodyPaths.DirectoryPath(Path.Combine(Path.Combine(path2, "roots"), SaddlebagCustodyPaths.WorldName(world))); if (SaddlebagCustodyPaths.Contains(text3, raw) || SaddlebagCustodyPaths.Contains(raw, text3)) { throw new IOException("Custody and routing directories overlap."); } string text4 = Path.Combine(text3, "route.sbcp"); SaddlebagCustodyPaths.FilePath(text4); SaddlebagCustodyPaths.FilePath(Path.Combine(text3, "route-" + new string('0', 32) + ".tmp")); SaddlebagCustodyPathSession saddlebagCustodyPathSession = new SaddlebagCustodyPathSession(raw, layout, flag, world, text4, request.Environment); try { SaddlebagCustodyPaths.NoLinks(text3); Directory.CreateDirectory(text3); string path3 = Path.Combine(text3, "routing.lock"); CheckFile(path3, required: false); saddlebagCustodyPathSession.guards.Add(new FileStream(path3, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); int num = 0; foreach (string item in Directory.EnumerateFileSystemEntries(text3)) { if (++num > 2 || (Path.GetFileName(item) != "routing.lock" && Path.GetFileName(item) != "route.sbcp")) { throw new InvalidDataException("Incomplete/unknown routing receipt retained; review required."); } } if (FileExists(text4)) { string text5 = ReadRoute(text4, world); if (!flag && !SaddlebagCustodyPaths.Same(raw, text5)) { throw new IOException("Custody root is already bound to " + text5 + "; refusing a configuration switch."); } if (!flag && (!SaddlebagCustodyPaths.Exists(raw) || !FileExists(Path.Combine(raw, "coordinator.lock")))) { throw new IOException("Bound custody location is missing/incomplete; refusing to recreate an empty replacement."); } saddlebagCustodyPathSession.bound = true; } if (flag) { if (!SaddlebagCustodyPaths.Exists(raw)) { throw new DirectoryNotFoundException("Read-only recovery location is absent; no fallback."); } SaddlebagCustodyPaths.NoLinks(raw); return saddlebagCustodyPathSession; } List list = new List(); if (request.LegacyWorldRoot != null) { list.Add(request.LegacyWorldRoot); } list.Add(text); list.AddRange(request.Options.PreviousWorldRoots); HashSet hashSet = new HashSet((Path.DirectorySeparatorChar == '\\') ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); foreach (string item2 in list) { string text6 = SaddlebagCustodyPaths.DirectoryPath(item2); if (SaddlebagCustodyPaths.Same(text6, raw) || !hashSet.Add(text6)) { continue; } SaddlebagCustodyPaths.NoLinks(text6); if (!SaddlebagCustodyPaths.Exists(text6)) { continue; } string path4 = Path.Combine(text6, "coordinator.lock"); if (FileExists(path4)) { saddlebagCustodyPathSession.guards.Add(new FileStream(path4, FileMode.Open, FileAccess.Read, FileShare.None)); } foreach (string item3 in Directory.EnumerateFileSystemEntries(text6)) { if (Path.GetFileName(item3) != "coordinator.lock") { throw new IOException("Previous custody data exists at " + text6 + "; use explicit read-only recovery, never an empty replacement."); } } } if (!saddlebagCustodyPathSession.bound && SaddlebagCustodyPaths.Exists(raw)) { foreach (string item4 in Directory.EnumerateFileSystemEntries(raw)) { if (Path.GetFileName(item4) != "coordinator.lock") { throw new IOException("Unbound existing custody data requires explicit read-only recovery; no automatic routing reset."); } } } saddlebagCustodyPathSession.CheckSpace(69206016L); return saddlebagCustodyPathSession; } catch { saddlebagCustodyPathSession.Dispose(); throw; } } internal void CheckSpace(long required) { if (environment.AvailableBytes(WorldDirectory) < required) { throw new IOException("Insufficient available capacity for custody; no fallback location."); } } internal void ConfirmBinding() { if (ReadOnly) { return; } string path = Path.Combine(WorldDirectory, "probe-" + Guid.NewGuid().ToString("N") + ".tmp"); SaddlebagCustodyPaths.FilePath(path); byte[] bytes = Encoding.ASCII.GetBytes("custody-write-probe-v1"); WriteNew(path, bytes); if (SaddlebagCustodyHash.Bytes(File.ReadAllBytes(path)) != SaddlebagCustodyHash.Bytes(bytes)) { throw new IOException("Custody path probe readback failed."); } File.Delete(path); if (!bound) { byte[] bytes2 = RouteBytes(world, WorldDirectory); string text = Path.Combine(Path.GetDirectoryName(marker), "route-" + Guid.NewGuid().ToString("N") + ".tmp"); SaddlebagCustodyPaths.FilePath(text); WriteNew(text, bytes2); if (ReadRoute(text, world) != WorldDirectory) { throw new IOException("Routing receipt readback failed."); } File.Move(text, marker); if (ReadRoute(marker, world) != WorldDirectory) { throw new IOException("Routing receipt final readback failed."); } bound = true; } } private static void WriteNew(string path, byte[] bytes) { CheckFile(path, required: false); using FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough); fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(flushToDisk: true); } private static bool FileExists(string path) { try { CheckFile(path, required: true); return true; } catch (FileNotFoundException) { return false; } catch (DirectoryNotFoundException) { return false; } } private static void CheckFile(string path, bool required) { SaddlebagCustodyPaths.FilePath(path); try { if ((File.GetAttributes(path) & (FileAttributes.Directory | FileAttributes.ReparsePoint)) != FileAttributes.None) { throw new IOException("Invalid custody metadata file."); } } catch (FileNotFoundException) { if (required) { throw; } } catch (DirectoryNotFoundException) { if (required) { throw; } } } private static byte[] RouteBytes(long world, string path) { byte[] array; using (MemoryStream memoryStream = new MemoryStream()) { using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetBytes(path); binaryWriter.Write(world); binaryWriter.Write(2); binaryWriter.Write(bytes.Length); binaryWriter.Write(bytes); binaryWriter.Flush(); array = memoryStream.ToArray(); } using MemoryStream memoryStream2 = new MemoryStream(); using BinaryWriter binaryWriter2 = new BinaryWriter(memoryStream2); binaryWriter2.Write(1396851536); binaryWriter2.Write(1); binaryWriter2.Write(array.Length); binaryWriter2.Write(array); binaryWriter2.Write(Encoding.ASCII.GetBytes(SaddlebagCustodyHash.Bytes(array))); binaryWriter2.Flush(); return memoryStream2.ToArray(); } private static string ReadRoute(string path, long world) { CheckFile(path, required: true); byte[] array; using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (fileStream.Length < 92 || fileStream.Length > 4096) { throw new InvalidDataException("Invalid routing receipt size."); } array = new byte[(int)fileStream.Length]; int num; for (int i = 0; i < array.Length; i += num) { num = fileStream.Read(array, i, array.Length - i); if (num <= 0) { throw new EndOfStreamException(); } } } byte[] array2; using (MemoryStream memoryStream = new MemoryStream(array, writable: false)) { using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadInt32() != 1396851536 || binaryReader.ReadInt32() != 1) { throw new InvalidDataException("Unsupported routing format."); } int num2 = binaryReader.ReadInt32(); if (num2 < 16 || num2 > 4096 || num2 != memoryStream.Length - memoryStream.Position - 64) { throw new InvalidDataException("Invalid routing bounds."); } array2 = binaryReader.ReadBytes(num2); if (Encoding.ASCII.GetString(binaryReader.ReadBytes(64)) != SaddlebagCustodyHash.Bytes(array2)) { throw new InvalidDataException("Routing integrity mismatch."); } } using MemoryStream memoryStream2 = new MemoryStream(array2, writable: false); using BinaryReader binaryReader2 = new BinaryReader(memoryStream2); if (binaryReader2.ReadInt64() != world || binaryReader2.ReadInt32() != 2) { throw new InvalidDataException("Routing world/layout mismatch."); } int num3 = binaryReader2.ReadInt32(); if (num3 <= 0 || num3 != memoryStream2.Length - memoryStream2.Position) { throw new InvalidDataException("Invalid route text."); } string text = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(binaryReader2.ReadBytes(num3)); if (SaddlebagCustodyPaths.DirectoryPath(text) != text) { throw new InvalidDataException("Noncanonical custody route."); } SaddlebagCustodyPaths.WorldBudget(text, SaddlebagCustodyDirectoryLayout.CompactBase32, readOnly: false); return text; } public void Dispose() { for (int num = guards.Count - 1; num >= 0; num--) { guards[num].Dispose(); } guards.Clear(); } } internal sealed class SaddlebagCustodyRecovery { internal readonly SaddlebagCustodyRecord[] Records; internal readonly string[] ManualReview; internal readonly bool WritesBlocked; internal readonly string StoreDirectory; internal readonly SaddlebagCustodyDirectoryLayout Layout; internal readonly bool ReadOnly; internal SaddlebagCustodyRecovery(SaddlebagCustodyRecord[] records, string[] issues, bool blocked, string directory, SaddlebagCustodyDirectoryLayout layout, bool readOnly) { Records = records; ManualReview = issues; WritesBlocked = blocked; StoreDirectory = directory; Layout = layout; ReadOnly = readOnly; } } internal sealed class SaddlebagCustodyStore { private string root; private readonly SaddlebagCustodyPathRequest pathRequest; private SaddlebagCustodyPathSession pathSession; private bool compactNames; private bool readOnly; private readonly long world; private readonly int unityThread; private readonly object serial = new object(); private readonly Dictionary latest = new Dictionary(StringComparer.Ordinal); private readonly List issues = new List(); private FileStream lease; private bool initialized; private bool initializationAttempted; private bool blocked; private bool closed; private long totalBytes; private int queued; internal SaddlebagCustodyStore(string rootDirectory, long worldUid, int mainThread) { root = Path.GetFullPath(rootDirectory); world = worldUid; unityThread = mainThread; } internal SaddlebagCustodyStore(SaddlebagCustodyPathRequest request, long worldUid, int mainThread) { if (request == null) { throw new ArgumentNullException("request"); } pathRequest = request; world = worldUid; unityThread = mainThread; } internal Task Schedule(Func work) { return Schedule(work, CancellationToken.None); } internal Task Schedule(Func work, CancellationToken cancellation) { if (work == null) { throw new ArgumentNullException("work"); } TaskCompletionSource completion = new TaskCompletionSource(); if (cancellation.IsCancellationRequested) { completion.SetCanceled(); return completion.Task; } if (Interlocked.Increment(ref queued) > 8) { Interlocked.Decrement(ref queued); throw new InvalidOperationException("Custody queue is full; no work accepted."); } try { Task.Factory.StartNew(delegate { T result = default(T); Exception ex = null; bool flag = false; try { if (Thread.CurrentThread.ManagedThreadId == unityThread) { throw new InvalidOperationException("Filesystem work on Unity thread denied."); } lock (serial) { if (closed) { throw new ObjectDisposedException("SaddlebagCustodyStore"); } if (cancellation.IsCancellationRequested) { flag = true; } else { result = work(); } } } catch (Exception ex2) { ex = ex2; } finally { Interlocked.Decrement(ref queued); } if (ex != null) { completion.SetException(ex); } else if (flag) { completion.SetCanceled(); } else { completion.SetResult(result); } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return completion.Task; } catch { Interlocked.Decrement(ref queued); throw; } } internal SaddlebagCustodyRecovery Initialize() { RequireWorker(); if (initialized) { return Recovery(); } if (initializationAttempted) { throw new InvalidOperationException("Initialization failed; use a new coordinator for recovery."); } initializationAttempted = true; try { return InitializeCore(); } catch { if (lease != null) { lease.Dispose(); lease = null; } if (pathSession != null) { pathSession.Dispose(); pathSession = null; } throw; } } private SaddlebagCustodyRecovery InitializeCore() { if (pathRequest != null) { pathSession = SaddlebagCustodyPathSession.Open(pathRequest, world, unityThread); root = pathSession.WorldDirectory; compactNames = pathSession.Layout == SaddlebagCustodyDirectoryLayout.CompactBase32; readOnly = pathSession.ReadOnly; } SaddlebagCustodyPaths.WorldBudget(root, (!compactNames) ? SaddlebagCustodyDirectoryLayout.LegacyHex : SaddlebagCustodyDirectoryLayout.CompactBase32, readOnly); for (DirectoryInfo directoryInfo = new DirectoryInfo(root); directoryInfo != null; directoryInfo = directoryInfo.Parent) { if (directoryInfo.Exists) { NoLink(directoryInfo.FullName); } } if (!readOnly) { Directory.CreateDirectory(root); } NoLink(root); string path = Path.Combine(root, "coordinator.lock"); if (File.Exists(path)) { NoLink(path); } SaddlebagCustodyPaths.FilePath(path); lease = new FileStream(path, readOnly ? FileMode.Open : FileMode.OpenOrCreate, readOnly ? FileAccess.Read : FileAccess.ReadWrite, FileShare.None); if (pathSession != null) { pathSession.ConfirmBinding(); } if (readOnly) { Issue("Explicit read-only recovery: receipts retained; no journal writes or deliveries allowed."); } try { int num = 0; foreach (string item in Directory.EnumerateFileSystemEntries(root)) { if (totalBytes > 67108864) { break; } if (Path.GetFileName(item) == "coordinator.lock") { continue; } if (++num > 1024) { Issue("Operation/entry limit exceeded."); break; } try { NoLink(item); string fileName = Path.GetFileName(item); if (!Directory.Exists(item) || !(compactNames ? SaddlebagCustodyPaths.IsOperationName(fileName) : SaddlebagCustodyHash.IsHash(fileName))) { throw new InvalidDataException("Unknown root entry."); } LoadChain(item, fileName); } catch (Exception ex) { Issue(Path.GetFileName(item) + ": " + ex.GetType().Name + " (retained)"); } } ValidateGenerations(); initialized = true; return Recovery(); } catch { lease.Dispose(); lease = null; throw; } } private void LoadChain(string directory, string slot) { List list = new List(); SaddlebagCustodyBinding saddlebagCustodyBinding = null; foreach (string item in Directory.EnumerateFileSystemEntries(directory)) { NoLink(item); if (Path.GetFileName(item) == "destination.sbcb") { byte[] array = ReadBounded(item); totalBytes += array.Length; if (totalBytes > 67108864) { throw new InvalidDataException("World custody byte limit exceeded."); } saddlebagCustodyBinding = SaddlebagCustodyBindingCodec.Decode(array); } else { if (list.Count >= 64) { throw new InvalidDataException("Revision/entry limit exceeded."); } NoLink(item); list.Add(item); } } list.Sort(StringComparer.Ordinal); if (list.Count == 0) { throw new InvalidDataException("Incomplete empty operation directory."); } SaddlebagCustodyRecord saddlebagCustodyRecord = null; SaddlebagCustodyRecord prepared = null; string text = ""; string preparedHash = ""; bool flag = false; for (int i = 0; i < list.Count; i++) { if (Path.GetFileName(list[i]) != RevisionName(i + 1)) { throw new InvalidDataException("Missing revision or incomplete/unknown file."); } byte[] array2 = ReadBounded(list[i]); totalBytes += array2.Length; if (totalBytes > 67108864) { throw new InvalidDataException("World custody byte limit exceeded."); } SaddlebagCustodyRecord saddlebagCustodyRecord2 = SaddlebagCustodyCodec.Decode(array2); if (saddlebagCustodyRecord2.Intent.WorldUid != world || OperationName(saddlebagCustodyRecord2.Intent.Slot) != slot || saddlebagCustodyRecord2.Revision != i + 1 || saddlebagCustodyRecord2.PreviousHash != text) { throw new InvalidDataException("Identity/revision/hash-chain mismatch."); } string text2 = ((saddlebagCustodyRecord == null) ? SaddlebagCustodyHash.Text("PREPARE|" + saddlebagCustodyRecord2.Intent.OperationId + "|" + saddlebagCustodyRecord2.Intent.PayloadHash) : SaddlebagCustodyCodec.ChangeId(saddlebagCustodyRecord2.Intent.OperationId, saddlebagCustodyRecord.Revision, saddlebagCustodyRecord2.State, saddlebagCustodyRecord2.Evidence)); if (saddlebagCustodyRecord2.ChangeId != text2) { throw new InvalidDataException("Inconsistent change identity."); } if (saddlebagCustodyRecord != null && (!saddlebagCustodyRecord.Intent.Same(saddlebagCustodyRecord2.Intent) || !SaddlebagCustodyPolicy.Allows(saddlebagCustodyRecord.State, saddlebagCustodyRecord2.State, saddlebagCustodyRecord2.Intent, saddlebagCustodyRecord2.Evidence, flag ? saddlebagCustodyBinding : null))) { throw new InvalidDataException("Inconsistent history."); } if (i == 0) { prepared = saddlebagCustodyRecord2; preparedHash = SaddlebagCustodyHash.Bytes(array2); } if (saddlebagCustodyBinding != null && saddlebagCustodyRecord2.Revision == saddlebagCustodyBinding.Parent.Revision) { saddlebagCustodyBinding.ValidateAnchor(saddlebagCustodyRecord2, prepared, SaddlebagCustodyHash.Bytes(array2), preparedHash); flag = true; } if (flag) { saddlebagCustodyRecord2 = saddlebagCustodyRecord2.WithBinding(saddlebagCustodyBinding); } saddlebagCustodyRecord = saddlebagCustodyRecord2; text = SaddlebagCustodyHash.Bytes(array2); if (flag && saddlebagCustodyRecord2.Revision == saddlebagCustodyBinding.Parent.Revision) { text = saddlebagCustodyBinding.Hash; } } if (saddlebagCustodyBinding != null && !flag) { throw new InvalidDataException("Orphan destination binding."); } latest.Add(saddlebagCustodyRecord.Intent.Slot, saddlebagCustodyRecord); } private void ValidateGenerations() { Dictionary> dictionary = new Dictionary>(StringComparer.Ordinal); foreach (SaddlebagCustodyRecord value2 in latest.Values) { long userId = value2.Intent.Source.UserId; string text = userId.ToString(CultureInfo.InvariantCulture); uint objectId = value2.Intent.Source.ObjectId; string key = text + ":" + objectId.ToString(CultureInfo.InvariantCulture); if (!dictionary.TryGetValue(key, out var value)) { value = new List(); dictionary.Add(key, value); } value.Add(value2); } foreach (List value3 in dictionary.Values) { value3.Sort(delegate(SaddlebagCustodyRecord a, SaddlebagCustodyRecord b) { long generation = a.Intent.Generation; return generation.CompareTo(b.Intent.Generation); }); HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int num = 0; num < value3.Count; num++) { if (value3[num].Intent.Generation != (long)num + 1L || !hashSet.Add(value3[num].Intent.DeathAttempt) || (num > 0 && value3[num - 1].State != SaddlebagCustodyState.RECONCILED)) { Issue(value3[num].Intent.OperationId + ": conflicting/incomplete source generation history; retained."); } } } } internal SaddlebagCustodyRecovery Recovery() { if (!initialized) { throw new InvalidOperationException("Initialize custody first."); } List list = new List(issues); foreach (SaddlebagCustodyRecord value in latest.Values) { if (value.State != SaddlebagCustodyState.RECONCILED) { list.Add(string.Concat(value.Intent.OperationId, ": ", value.State, "; no automatic delivery; reconciliation required.")); } } SaddlebagCustodyRecord[] array = new SaddlebagCustodyRecord[latest.Count]; latest.Values.CopyTo(array, 0); return new SaddlebagCustodyRecovery(array, list.ToArray(), blocked, root, (!compactNames) ? SaddlebagCustodyDirectoryLayout.LegacyHex : SaddlebagCustodyDirectoryLayout.CompactBase32, readOnly); } internal SaddlebagCustodyRecord Prepare(SaddlebagCustodyIntent intent, SaddlebagCustodyAuthority authority) { Ready(authority); if (intent.WorldUid != world) { throw new InvalidOperationException("Wrong world."); } if (!authority.SourcePresent || authority.SenderPeer != authority.SourceOwner) { throw new InvalidOperationException("Preparation requires an authenticated current source owner."); } if (latest.TryGetValue(intent.Slot, out var value)) { if (!value.Intent.Same(intent)) { throw new InvalidOperationException("Conflicting operation identity/payload; manual review required."); } VerifyCurrent(value); return value; } if (latest.Count >= 1024) { throw new InvalidOperationException("Operation limit reached; receipts retained."); } long num = 0L; foreach (SaddlebagCustodyRecord value2 in latest.Values) { if (value2.Intent.Source.UserId == intent.Source.UserId && value2.Intent.Source.ObjectId == intent.Source.ObjectId) { if (value2.State != SaddlebagCustodyState.RECONCILED || value2.Intent.DeathAttempt == intent.DeathAttempt) { throw new InvalidOperationException("Unresolved custody or reused death attempt; manual review required."); } num = Math.Max(num, value2.Intent.Generation); } } if (num == long.MaxValue || intent.Generation != num + 1) { throw new InvalidOperationException("Obsolete/skipped custody generation."); } string change = SaddlebagCustodyHash.Text("PREPARE|" + intent.OperationId + "|" + intent.PayloadHash); SaddlebagCustodyRecord saddlebagCustodyRecord = new SaddlebagCustodyRecord(intent, 1, SaddlebagCustodyState.PREPARED, "", change, DateTime.UtcNow.Ticks, authority, SaddlebagCustodyEvidence.None); Append(saddlebagCustodyRecord); return saddlebagCustodyRecord; } internal SaddlebagCustodyRecord Advance(SaddlebagCustodyRecord expected, SaddlebagCustodyState next, SaddlebagCustodyAuthority authority, SaddlebagCustodyEvidence proof) { Ready(authority); if (authority.SenderPeer != authority.ServerPeer) { throw new InvalidOperationException("Only the server coordinator can advance custody."); } if (expected == null || !latest.TryGetValue(expected.Intent.Slot, out var value) || !value.Intent.Same(expected.Intent)) { throw new InvalidOperationException("Unknown or conflicting operation."); } VerifyCurrent(value); string text = SaddlebagCustodyCodec.ChangeId(expected.Intent.OperationId, expected.Revision, next, proof); if (value.Revision > expected.Revision) { string path = Path.Combine(OperationDirectory(expected.Intent.Slot), RevisionName(expected.Revision + 1)); SaddlebagCustodyRecord saddlebagCustodyRecord = SaddlebagCustodyCodec.Decode(ReadBounded(path)); if (saddlebagCustodyRecord.Revision == expected.Revision + 1 && saddlebagCustodyRecord.ChangeId == text && saddlebagCustodyRecord.Intent.Same(expected.Intent)) { return value; } throw new InvalidOperationException("Stale/conflicting operation revision."); } if (value.Revision != expected.Revision || value.ChangeId != expected.ChangeId || value.BindingHash != expected.BindingHash || value.Revision >= 64 || !SaddlebagCustodyPolicy.Allows(value.State, next, value.Intent, proof, value.Binding)) { throw new InvalidOperationException("Transition denied."); } string text2 = SaddlebagCustodyHash.Bytes(ReadBounded(Path.Combine(OperationDirectory(value.Intent.Slot), RevisionName(value.Revision)))); if (text2 != SaddlebagCustodyHash.Bytes(SaddlebagCustodyCodec.Encode(value))) { throw new InvalidDataException("Stored record changed externally."); } if (value.Binding != null && value.Revision == value.Binding.Parent.Revision) { text2 = value.Binding.Hash; } SaddlebagCustodyRecord saddlebagCustodyRecord2 = new SaddlebagCustodyRecord(value.Intent, value.Revision + 1, next, text2, text, DateTime.UtcNow.Ticks, authority, proof, value.Binding); Append(saddlebagCustodyRecord2); return saddlebagCustodyRecord2; } internal SaddlebagCustodyRecord BindDestination(SaddlebagCustodyRecord expected, SaddlebagCustodyDestination destination, SaddlebagCustodyAuthority authority) { Ready(authority); if (authority.ServerPeer != authority.SenderPeer || expected == null || destination == null || !latest.TryGetValue(expected.Intent.Slot, out var value) || !value.Intent.Same(expected.Intent)) { throw new InvalidOperationException("Only the server can bind a known operation."); } VerifyCurrent(value); string path = Path.Combine(OperationDirectory(value.Intent.Slot), RevisionName(expected.Revision)); if (expected.Revision > value.Revision || SaddlebagCustodyHash.Bytes(ReadBounded(path)) != SaddlebagCustodyHash.Bytes(SaddlebagCustodyCodec.Encode(expected))) { throw new InvalidOperationException("Stale/contradictory binding anchor."); } if (value.Binding != null) { SaddlebagCustodyBinding binding = value.Binding; if (!binding.Destination.Same(destination) || authority.ServerPeer != binding.Authority.ServerPeer || !authority.SourcePresent || !authority.DestinationPresent || authority.SourceOwner != binding.Authority.SourceOwner || authority.SourceRevision != binding.Authority.SourceRevision || authority.DestinationOwner != binding.Authority.DestinationOwner || authority.DestinationRevision != binding.Authority.DestinationRevision) { throw new InvalidOperationException("Conflicting destination binding; retained unchanged."); } return value; } if (value.Revision != expected.Revision || value.BindingHash != expected.BindingHash) { throw new InvalidOperationException("Capture current operation before first binding."); } byte[] bytes = ReadBounded(Path.Combine(OperationDirectory(value.Intent.Slot), RevisionName(1))); SaddlebagCustodyRecord prepared = SaddlebagCustodyCodec.Decode(bytes); string parentHash = SaddlebagCustodyHash.Bytes(SaddlebagCustodyCodec.Encode(value)); SaddlebagCustodyBinding saddlebagCustodyBinding = new SaddlebagCustodyBinding(value, SaddlebagCustodyHash.Bytes(bytes), parentHash, destination, authority); saddlebagCustodyBinding.ValidateAnchor(value, prepared, parentHash, SaddlebagCustodyHash.Bytes(bytes)); byte[] array = SaddlebagCustodyBindingCodec.Encode(saddlebagCustodyBinding); if (totalBytes + array.Length > 67108864) { throw new InvalidOperationException("World custody byte limit reached."); } string text = OperationDirectory(value.Intent.Slot); string text2 = Path.Combine(text, "destination.sbcb"); string text3 = Path.Combine(text, "incomplete-" + Guid.NewGuid().ToString("N") + ".tmp"); try { NoLink(text); SaddlebagCustodyPaths.FilePath(text2); SaddlebagCustodyPaths.FilePath(text3); if (pathSession != null) { pathSession.CheckSpace(2L * (long)array.Length + 4096); } 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); } if (SaddlebagCustodyHash.Bytes(ReadBounded(text3)) != saddlebagCustodyBinding.Hash) { throw new IOException("Binding readback failed."); } File.Move(text3, text2); byte[] bytes2 = ReadBounded(text2); SaddlebagCustodyBindingCodec.Decode(bytes2); if (SaddlebagCustodyHash.Bytes(bytes2) != saddlebagCustodyBinding.Hash) { throw new IOException("Binding final readback failed."); } value = value.WithBinding(saddlebagCustodyBinding); latest[value.Intent.Slot] = value; totalBytes += array.Length; return value; } catch { Issue("Interrupted/unverified destination binding; retain files for review."); throw; } } private void Ready(SaddlebagCustodyAuthority authority) { RequireWorker(); if (!initialized || lease == null || blocked || readOnly) { throw new InvalidOperationException("Custody unavailable or retained for manual review."); } if (authority == null || !authority.Fresh) { throw new InvalidOperationException("Expired server authority observation; capture again on Unity thread."); } } private void VerifyCurrent(SaddlebagCustodyRecord record) { try { byte[] bytes = ReadBounded(Path.Combine(OperationDirectory(record.Intent.Slot), RevisionName(record.Revision))); SaddlebagCustodyCodec.Decode(bytes); if (SaddlebagCustodyHash.Bytes(bytes) != SaddlebagCustodyHash.Bytes(SaddlebagCustodyCodec.Encode(record))) { throw new InvalidDataException("Stored receipt changed externally."); } string path = Path.Combine(OperationDirectory(record.Intent.Slot), "destination.sbcb"); if (record.Binding == null) { if (File.Exists(path) || Directory.Exists(path)) { throw new InvalidDataException("Unobserved binding appeared externally."); } return; } byte[] bytes2 = ReadBounded(path); SaddlebagCustodyBindingCodec.Decode(bytes2); if (SaddlebagCustodyHash.Bytes(bytes2) != record.Binding.Hash) { throw new InvalidDataException("Binding removed/modified externally."); } } catch { Issue("Custody receipt unavailable/modified; retain for review."); throw; } } private void Append(SaddlebagCustodyRecord record) { byte[] array = SaddlebagCustodyCodec.Encode(record); if (totalBytes + array.Length > 67108864) { throw new InvalidOperationException("World custody byte limit reached."); } string text = OperationDirectory(record.Intent.Slot); string text2 = Path.Combine(text, "incomplete-" + Guid.NewGuid().ToString("N") + ".tmp"); try { SaddlebagCustodyPaths.FilePath(text2); SaddlebagCustodyPaths.FilePath(Path.Combine(text, RevisionName(record.Revision))); if (pathSession != null) { pathSession.CheckSpace(2L * (long)array.Length + 4096); } Directory.CreateDirectory(text); NoLink(text); 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 (SaddlebagCustodyHash.Bytes(ReadBounded(text2)) != SaddlebagCustodyHash.Bytes(array)) { throw new IOException("Custody write readback failed."); } File.Move(text2, Path.Combine(text, RevisionName(record.Revision))); byte[] bytes = ReadBounded(Path.Combine(text, RevisionName(record.Revision))); SaddlebagCustodyCodec.Decode(bytes); if (SaddlebagCustodyHash.Bytes(bytes) != SaddlebagCustodyHash.Bytes(array)) { throw new IOException("Custody final readback failed."); } latest[record.Intent.Slot] = record; totalBytes += array.Length; } catch { Issue("Interrupted/unverified append; retain all files and reopen for review."); throw; } } private void Issue(string message) { blocked = true; if (issues.Count < 1025) { issues.Add(message); } } private string OperationName(string slot) { if (!compactNames) { return slot; } return SaddlebagCustodyPaths.OperationName(slot); } private string OperationDirectory(string slot) { return Path.Combine(root, OperationName(slot)); } private static string RevisionName(int revision) { return revision.ToString("D8", CultureInfo.InvariantCulture) + ".sbcu"; } private static void NoLink(string path) { if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != FileAttributes.None) { throw new IOException("Reparse point denied in custody store."); } } private static byte[] ReadBounded(string path) { SaddlebagCustodyPaths.FilePath(path); NoLink(path); using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length <= 0 || fileStream.Length > 1048576) { throw new InvalidDataException("Invalid custody file size."); } byte[] array = new byte[(int)fileStream.Length]; int num; for (int i = 0; i < array.Length; i += num) { num = fileStream.Read(array, i, array.Length - i); if (num <= 0) { throw new EndOfStreamException(); } } return array; } private void RequireWorker() { if (Thread.CurrentThread.ManagedThreadId == unityThread) { throw new InvalidOperationException("Filesystem work on Unity thread denied."); } } internal bool Close() { RequireWorker(); if (lease != null) { lease.Dispose(); lease = null; } if (pathSession != null) { pathSession.Dispose(); pathSession = null; } closed = true; return true; } } internal static class SaddlebagSemanticInventory { internal const int MaximumBytes = 1048576; internal const int MaximumStacks = 4096; internal static byte[] Save(Inventory inventory) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown if (inventory == null) { throw new InvalidOperationException("Missing inventory."); } ZPackage val = new ZPackage(); inventory.Save(val); byte[] array = val.GetArray(); if (array == null || array.Length > 1048576) { throw new InvalidOperationException("Inventory serialization limit exceeded."); } return array; } internal static bool BytesEqual(byte[] a, byte[] b) { if (a == null || b == null) { return a == b; } if (a.Length != b.Length) { return false; } for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return false; } } return true; } internal static Inventory Empty(int width, int height) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown if (width <= 0 || height <= 0 || (long)width * (long)height > 4096) { throw new InvalidOperationException("Unsupported inventory dimensions."); } return new Inventory("A01M isolated inventory", (Sprite)null, width, height); } internal static Inventory Decode(byte[] bytes, int width, int height) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown Inventory val = Empty(width, height); if (bytes == null) { return val; } if (bytes.Length == 0 || bytes.Length > 1048576) { throw new InvalidOperationException("Invalid inventory packet."); } val.Load(new ZPackage(bytes)); if (!BytesEqual(bytes, Save(val))) { throw new InvalidOperationException("Inventory packet cannot round-trip exactly."); } Manifest(val.GetAllItems()); return val; } private static ItemData Clone(ItemData item) { if (item == null || ((object)item).GetType() != typeof(ItemData) || (Object)(object)item.m_dropPrefab == (Object)null || item.m_shared == null || item.m_stack <= 0 || item.m_stack > item.m_shared.m_maxStackSize || float.IsNaN(item.m_durability) || float.IsInfinity(item.m_durability)) { throw new InvalidOperationException("Unverifiable item identity/type/quantity/properties."); } ItemData val = item.Clone(); if (val == null || object.ReferenceEquals(val, item)) { throw new InvalidOperationException("Unsafe item clone."); } Inventory val2 = Empty(1, 1); Inventory val3 = Empty(1, 1); val2.GetAllItems().Add(item); val3.GetAllItems().Add(val); if ((Object)(object)val.m_dropPrefab == (Object)null || ((Object)val.m_dropPrefab).name != ((Object)item.m_dropPrefab).name || !BytesEqual(Save(val2), Save(val3))) { throw new InvalidOperationException("Clone lost serialized item properties."); } if (item.m_customData == null) { throw new InvalidOperationException("Missing custom-data map."); } val.m_customData = new Dictionary(); List list = new List(item.m_customData.Keys); list.Sort(StringComparer.Ordinal); foreach (string item2 in list) { if (item2 == null || item.m_customData[item2] == null) { throw new InvalidOperationException("Invalid custom-data entry."); } val.m_customData.Add(item2, item.m_customData[item2]); } return val; } internal static List Copy(IEnumerable items) { List list = new List(); foreach (ItemData item in items) { if (list.Count >= 4096) { throw new InvalidOperationException("Inventory stack limit exceeded."); } list.Add(Clone(item)); } return list; } private static string Identity(ItemData item) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) ItemData val = Clone(item); val.m_stack = 1; val.m_gridPos = new Vector2i(0, 0); Inventory val2 = Empty(1, 1); val2.GetAllItems().Add(val); return ((Object)item.m_dropPrefab).name + "|" + Convert.ToBase64String(Save(val2)); } internal static Dictionary Manifest(IEnumerable items) { Dictionary dictionary = new Dictionary(StringComparer.Ordinal); int num = 0; foreach (ItemData item in items) { if (++num > 4096) { throw new InvalidOperationException("Inventory stack limit exceeded."); } string key = Identity(item); dictionary.TryGetValue(key, out var value); dictionary[key] = checked(value + item.m_stack); } return dictionary; } internal static Dictionary Combined(IEnumerable before, IEnumerable source) { List list = Copy(before); list.AddRange(Copy(source)); return Manifest(list); } internal static void Require(Dictionary expected, IEnumerable actual) { Dictionary dictionary = Manifest(actual); if (expected.Count != dictionary.Count) { throw new InvalidOperationException("Item property/identity conservation failed."); } foreach (KeyValuePair item in expected) { if (!dictionary.TryGetValue(item.Key, out var value) || value != item.Value) { throw new InvalidOperationException("Item quantity conservation failed."); } } } internal static Inventory Prepare(Inventory before, IEnumerable source, int width, int height) { List list = Copy(source); Dictionary expected = Combined(before.GetAllItems(), list); Inventory val = Decode(Save(before), width, height); foreach (ItemData item in list) { if (!val.AddItem(item)) { throw new InvalidOperationException("Destination lacks safe capacity; no live inventory changed."); } } Require(expected, val.GetAllItems()); Inventory val2 = Decode(Save(val), width, height); Require(expected, val2.GetAllItems()); return val2; } } internal static class SlsLevelSettingsRepair { private static readonly HashSet KnownBosses = new HashSet(StringComparer.Ordinal) { "Eikthyr", "gd_king", "Bonemass", "Dragon", "GoblinKing", "SeekerQueen", "Fader", "FrozenKing", "Monstrum_FrozenKing", "Lord_DeepNorth" }; internal static bool TryPrepare(string original, out string repaired, out string reason) { repaired = null; reason = null; if (string.IsNullOrEmpty(original)) { return false; } string separator = (original.Contains("\r\n") ? "\r\n" : "\n"); string text = original.Replace("\r\n", "\n"); if (text.IndexOf('\r') >= 0) { return false; } List list = new List(text.Split(new char[1] { '\n' })); int num = -1; int num2 = -1; int num3 = -1; for (int i = 0; i < list.Count; i++) { if (Regex.IsMatch(list[i], "^[A-Za-z_]\\w*:\\s*") && num3 < 0) { num3 = i; } if (Regex.IsMatch(list[i], "^\\s*#\\s+CreatureConfiguration:\\s*$")) { if (num >= 0) { return false; } num = i; } if (Regex.IsMatch(list[i], "^CreatureConfiguration:\\s*(?:#.*)?$")) { if (num2 >= 0) { reason = "Multiple active CreatureConfiguration sections; manual review required."; return false; } num2 = i; } } if (num < 0 || num2 < 0 || num3 <= num || num2 <= num) { return false; } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); Dictionary dictionary2 = new Dictionary(StringComparer.Ordinal); List list2 = new List(); int j; for (j = num + 1; j + 1 < num3; j += 2) { Match match = Regex.Match(list[j], "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$"); if (!match.Success) { break; } string value = match.Groups[1].Value; Match match2 = Regex.Match(list[j + 1], "^ CreatureMaxLevelOverride:\\s*(-?\\d+)\\s*(?:#.*)?$"); if (!KnownBosses.Contains(value) || dictionary.ContainsKey(value) || !match2.Success || !int.TryParse(match2.Groups[1].Value, out var result) || result < -1) { reason = "Unrecognized or duplicate misplaced boss rule; manual review required."; return false; } dictionary.Add(value, result); dictionary2.Add(value, list[j + 1]); list2.Add(value); } if (dictionary.Count == 0) { return false; } if (dictionary.Count != KnownBosses.Count) { reason = "Incomplete misplaced boss-cap block; manual review required."; return false; } for (int k = j; k < num3; k++) { if (list[k].Trim().Length > 0 && !list[k].TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { reason = "Other active content in YAML comment header; manual review required."; return false; } } int l; for (l = num2 + 1; l < list.Count && !Regex.IsMatch(list[l], "^[A-Za-z_]\\w*:"); l++) { } Dictionary dictionary3 = new Dictionary(StringComparer.Ordinal); for (int m = num2 + 1; m < l; m++) { Match match3 = Regex.Match(list[m], "^ ([A-Za-z_]\\w*):"); if (match3.Success) { string value2 = match3.Groups[1].Value; if (dictionary3.ContainsKey(value2)) { reason = "Duplicate creature entry: " + value2; return false; } dictionary3.Add(value2, m); } } SortedDictionary> sortedDictionary = new SortedDictionary>(); foreach (string item in list2) { if (!dictionary3.TryGetValue(item, out var value3)) { if (!sortedDictionary.TryGetValue(l, out var value4)) { sortedDictionary.Add(l, value4 = new List()); } value4.Add(" " + item + ":"); value4.Add(dictionary2[item]); continue; } if (!Regex.IsMatch(list[value3], "^ [A-Za-z_]\\w*:\\s*(?:#.*)?$")) { reason = "Inline creature mapping requires manual review: " + item; return false; } int num4 = l; foreach (int value6 in dictionary3.Values) { if (value6 > value3 && value6 < num4) { num4 = value6; } } bool flag = false; for (int n = value3 + 1; n < num4; n++) { if (Regex.IsMatch(list[n], "^ CreatureMaxLevelOverride:")) { Match match4 = Regex.Match(list[n], "^ CreatureMaxLevelOverride:\\s*(-?\\d+)\\s*(?:#.*)?$"); if (flag || !match4.Success || !int.TryParse(match4.Groups[1].Value, out var result2) || result2 != dictionary[item]) { reason = "Conflicting boss cap; neither value was overwritten: " + item; return false; } flag = true; } } if (!flag) { if (!sortedDictionary.TryGetValue(value3 + 1, out var value5)) { sortedDictionary.Add(value3 + 1, value5 = new List()); } value5.Insert(0, dictionary2[item]); } } for (int num5 = num + 1; num5 < j; num5++) { list[num5] = "# " + list[num5]; } List list3 = new List(sortedDictionary.Keys); list3.Reverse(); foreach (int item2 in list3) { list.InsertRange(item2, sortedDictionary[item2]); } repaired = string.Join(separator, list.ToArray()); return true; } internal static void Run(Assembly sls, string configRoot, Action info, Action warn) { if ((Object)(object)ZNet.instance != (Object)null) { return; } try { Type type = sls.GetType("StarLevelSystem.common.YamlConfigManager", throwOnError: true); object value = AccessTools.Field(type, "LevelSettings").GetValue(null); if (value == null) { return; } Type type2 = value.GetType(); if (!(bool)AccessTools.Property(type2, "LastLoadFailed").GetValue(value, null)) { return; } string path = (string)AccessTools.Property(type2, "Path").GetValue(value, null); string fullPath = Path.GetFullPath(Path.Combine(configRoot, "StarLevelSystem", "LevelSettings.yaml")); if (!string.Equals(Path.GetFullPath(path), fullPath, StringComparison.OrdinalIgnoreCase)) { throw new NotSupportedException("Unexpected SLS level settings path"); } string text = File.ReadAllText(path); if (!TryPrepare(text, out var repaired, out var reason)) { if (reason != null) { warn(reason); } return; } MethodInfo methodInfo = AccessTools.Method(type2, "DryRun", new Type[2] { typeof(string), typeof(string).MakeByRefType() }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(type, "ApplyEdited", new Type[3] { value.GetType().BaseType, typeof(string), typeof(string).MakeByRefType() }, (Type[])null); if (methodInfo == null || methodInfo2 == null) { throw new NotSupportedException("SLS native validation/edit API changed"); } object[] array = new object[2] { text, null }; methodInfo.Invoke(value, array); if (array[1] == null) { return; } object[] array2 = new object[2] { repaired, null }; object obj = methodInfo.Invoke(value, array2); if (array2[1] != null || obj == null || (bool)AccessTools.Property(obj.GetType(), "HasErrors").GetValue(obj, null)) { warn("SLS rejected repaired LevelSettings; original retained. " + array2[1]); return; } if (!string.Equals(File.ReadAllText(path), text, StringComparison.Ordinal)) { warn("LevelSettings changed during validation; migration skipped."); return; } object[] array3 = new object[3] { value, repaired, null }; if (!(bool)methodInfo2.Invoke(null, array3)) { warn("SLS level-settings repair not applied: " + array3[2]); return; } string text2 = File.ReadAllText(path); object[] array4 = new object[2] { text2, null }; object obj2 = methodInfo.Invoke(value, array4); if (array4[1] != null || obj2 == null || (bool)AccessTools.Property(obj2.GetType(), "HasErrors").GetValue(obj2, null) || text2.IndexOf(repaired, StringComparison.Ordinal) < 0) { warn("SLS accepted the repair in memory but it was not fully persisted; check SLS write errors."); } else { info("0.7.50 SLS misplaced boss rules repaired through native validation/backup/edit. Existing caps and biome, distance and boss curves retained. " + array3[2]); } } catch (Exception ex) { warn("SLS settings repair deferred: " + ex.GetBaseException().Message); } } } public sealed class SlsConfigSnapshot { public DateTime CapturedAtUtc { get; set; } public string FilePath { get; set; } public string ContentHashSha256 { get; set; } public Dictionary BiomeStarCaps { get; private set; } public float DefaultStarFrequency { get; set; } public int DefaultMaxLevel { get; set; } public float BaseHealthMultiplier { get; set; } public float StarHealthMultiplier { get; set; } public float StarDamageMultiplier { get; set; } public string RawYamlContent { get; set; } public SlsConfigSnapshot() { CapturedAtUtc = DateTime.UtcNow; FilePath = string.Empty; ContentHashSha256 = string.Empty; BiomeStarCaps = new Dictionary(StringComparer.OrdinalIgnoreCase); DefaultStarFrequency = 0.15f; DefaultMaxLevel = 6; BaseHealthMultiplier = 1f; StarHealthMultiplier = 1f; StarDamageMultiplier = 0.5f; RawYamlContent = string.Empty; } public SlsConfigSnapshot Clone() { SlsConfigSnapshot slsConfigSnapshot = new SlsConfigSnapshot(); slsConfigSnapshot.CapturedAtUtc = CapturedAtUtc; slsConfigSnapshot.FilePath = FilePath; slsConfigSnapshot.ContentHashSha256 = ContentHashSha256; slsConfigSnapshot.DefaultStarFrequency = DefaultStarFrequency; slsConfigSnapshot.DefaultMaxLevel = DefaultMaxLevel; slsConfigSnapshot.BaseHealthMultiplier = BaseHealthMultiplier; slsConfigSnapshot.StarHealthMultiplier = StarHealthMultiplier; slsConfigSnapshot.StarDamageMultiplier = StarDamageMultiplier; slsConfigSnapshot.RawYamlContent = RawYamlContent; SlsConfigSnapshot slsConfigSnapshot2 = slsConfigSnapshot; foreach (KeyValuePair biomeStarCap in BiomeStarCaps) { slsConfigSnapshot2.BiomeStarCaps[biomeStarCap.Key] = biomeStarCap.Value; } return slsConfigSnapshot2; } } public sealed class SlsAdapterResult { public bool Success { get; private set; } public string ErrorMessage { get; private set; } public string Biome { get; private set; } public int RequestedStarCap { get; private set; } public int EffectiveStarCap { get; private set; } public bool RequiresRestart { get; private set; } private SlsAdapterResult() { } public static SlsAdapterResult Ok(string biome, int requested, int effective, bool requiresRestart = false) { SlsAdapterResult slsAdapterResult = new SlsAdapterResult(); slsAdapterResult.Success = true; slsAdapterResult.ErrorMessage = string.Empty; slsAdapterResult.Biome = biome; slsAdapterResult.RequestedStarCap = requested; slsAdapterResult.EffectiveStarCap = effective; slsAdapterResult.RequiresRestart = requiresRestart; return slsAdapterResult; } public static SlsAdapterResult Fail(string biome, int requested, int effective, string reason) { SlsAdapterResult slsAdapterResult = new SlsAdapterResult(); slsAdapterResult.Success = false; slsAdapterResult.ErrorMessage = reason ?? "Unknown failure"; slsAdapterResult.Biome = biome; slsAdapterResult.RequestedStarCap = requested; slsAdapterResult.EffectiveStarCap = effective; slsAdapterResult.RequiresRestart = false; return slsAdapterResult; } } public static class StarLevelSystemAdapter { public sealed class BiomeStarProbabilityReport { public DifficultyPreset Preset { get; set; } public string BiomeName { get; set; } public int GlobalCeilingStars { get; set; } public int BiomeStarCap { get; set; } public int InternalMaxLevel => BiomeStarCap + 1; public float StarCreatureRate { get; set; } public SortedDictionary IndividualStarProbabilities { get; private set; } public SortedDictionary CumulativeAtOrBelowProbabilities { get; private set; } public SortedDictionary CumulativeAtOrAboveProbabilities { get; private set; } public float TotalProbabilitySum { get; set; } public bool IsStrictlyMonotonicDecreasing { get; set; } public BiomeStarProbabilityReport() { IndividualStarProbabilities = new SortedDictionary(); CumulativeAtOrBelowProbabilities = new SortedDictionary(); CumulativeAtOrAboveProbabilities = new SortedDictionary(); } } public const string SlsPluginGuid = "MidnightsFX.StarLevelSystem"; public const string SlsConfigSubFolder = "StarLevelSystem"; public const string SlsLevelSettingsFileName = "LevelSettings.yaml"; private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.StarLevelSystemAdapter"); private static SlsConfigSnapshot s_baselineSnapshot; private static string s_customConfigPath = null; private static readonly object s_fileLock = new object(); public static bool IsSlsInstalled { get { try { if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("MidnightsFX.StarLevelSystem")) { return true; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (string.Equals(assembly.GetName().Name, "StarLevelSystem", StringComparison.OrdinalIgnoreCase)) { return true; } } } catch { } return false; } } public static bool IsConfigFileAvailable { get { string levelSettingsPath = GetLevelSettingsPath(); if (!string.IsNullOrEmpty(levelSettingsPath)) { return File.Exists(levelSettingsPath); } return false; } } private static bool HasRef(object obj) { return !object.ReferenceEquals(obj, null); } public static void SetCustomConfigPathForTesting(string path) { s_customConfigPath = path; s_baselineSnapshot = null; } public static void ResetConfigPath() { s_customConfigPath = null; s_baselineSnapshot = null; } public static string GetLevelSettingsPath() { if (!string.IsNullOrEmpty(s_customConfigPath)) { return s_customConfigPath; } try { if (Paths.ConfigPath != null) { return Path.Combine(Paths.ConfigPath, "StarLevelSystem", "LevelSettings.yaml"); } } catch { } return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BepInEx", "config", "StarLevelSystem", "LevelSettings.yaml"); } public static bool HasAuthority() { if (!HasRef(ZNet.instance)) { return true; } return ZNet.instance.IsServer(); } public static void EnsureBaselineCaptured() { if (s_baselineSnapshot == null && IsConfigFileAvailable) { s_baselineSnapshot = CaptureCurrentState(); if (s_baselineSnapshot != null) { Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[StarLevelSystemAdapter] Captured SLS baseline from '{0}' (SHA256: {1})", s_baselineSnapshot.FilePath, s_baselineSnapshot.ContentHashSha256)); } } } public static SlsConfigSnapshot GetBaseline() { if (s_baselineSnapshot == null) { return null; } return s_baselineSnapshot.Clone(); } public static string ComputeFileSha256(string filePath) { if (!File.Exists(filePath)) { return string.Empty; } using SHA256 sHA = SHA256.Create(); using FileStream inputStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); byte[] array = sHA.ComputeHash(inputStream); StringBuilder stringBuilder = new StringBuilder(array.Length * 2); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("X2")); } return stringBuilder.ToString(); } public static string ComputeContentSha256(string content) { if (content == null) { return string.Empty; } using SHA256 sHA = SHA256.Create(); byte[] bytes = Encoding.UTF8.GetBytes(content); byte[] array = sHA.ComputeHash(bytes); StringBuilder stringBuilder = new StringBuilder(array.Length * 2); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("X2")); } return stringBuilder.ToString(); } public static Dictionary ReadAllBiomeStarCaps() { Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); string levelSettingsPath = GetLevelSettingsPath(); if (!File.Exists(levelSettingsPath)) { return dictionary; } try { string yaml = File.ReadAllText(levelSettingsPath, Encoding.UTF8); ParseBiomeCapsFromYaml(yaml, dictionary); } catch (Exception ex) { Log.LogError((object)("[StarLevelSystemAdapter] Failed to read biome caps: " + ex.Message)); } return dictionary; } public static int ReadBiomeStarCap(string biomeName) { if (string.IsNullOrEmpty(biomeName)) { return -1; } Dictionary dictionary = ReadAllBiomeStarCaps(); if (dictionary.TryGetValue(biomeName, out var value)) { return value; } return -1; } public static SlsConfigSnapshot CaptureCurrentState() { string levelSettingsPath = GetLevelSettingsPath(); if (!File.Exists(levelSettingsPath)) { return null; } try { string text = File.ReadAllText(levelSettingsPath, Encoding.UTF8); SlsConfigSnapshot slsConfigSnapshot = new SlsConfigSnapshot(); slsConfigSnapshot.CapturedAtUtc = DateTime.UtcNow; slsConfigSnapshot.FilePath = levelSettingsPath; slsConfigSnapshot.ContentHashSha256 = ComputeContentSha256(text); slsConfigSnapshot.RawYamlContent = text; SlsConfigSnapshot slsConfigSnapshot2 = slsConfigSnapshot; ParseBiomeCapsFromYaml(text, slsConfigSnapshot2.BiomeStarCaps); ParseDefaultStarFrequencyFromYaml(text, out var frequency, out var maxLevel); slsConfigSnapshot2.DefaultStarFrequency = frequency; slsConfigSnapshot2.DefaultMaxLevel = maxLevel; ParseCreatureScalingFromYaml(text, out var baseHealth, out var starHealth, out var starDamage); slsConfigSnapshot2.BaseHealthMultiplier = baseHealth; slsConfigSnapshot2.StarHealthMultiplier = starHealth; slsConfigSnapshot2.StarDamageMultiplier = starDamage; return slsConfigSnapshot2; } catch (Exception ex) { Log.LogError((object)("[StarLevelSystemAdapter] CaptureCurrentState failed: " + ex.Message)); return null; } } public static SlsAdapterResult SetBiomeMaxLevelOverride(string biomeName, int starCap, string expectedBaseHash = null) { if (string.IsNullOrEmpty(biomeName)) { return SlsAdapterResult.Fail(biomeName, starCap, -1, "Invalid biome name."); } if (!IsConfigFileAvailable) { return SlsAdapterResult.Fail(biomeName, starCap, -1, "LevelSettings.yaml not found."); } if (!HasAuthority()) { return SlsAdapterResult.Fail(biomeName, starCap, ReadBiomeStarCap(biomeName), "Unauthorized: StarLevelSystem configuration is server-authoritative. Remote clients cannot alter server settings."); } int num = Mathf.Clamp(starCap, 0, 16); EnsureBaselineCaptured(); string levelSettingsPath = GetLevelSettingsPath(); SlsConfigSnapshot slsConfigSnapshot = CaptureCurrentState(); if (slsConfigSnapshot == null) { return SlsAdapterResult.Fail(biomeName, num, -1, "Could not capture pre-apply snapshot."); } try { string text = File.ReadAllText(levelSettingsPath, Encoding.UTF8); string a = ComputeContentSha256(text); if (!string.IsNullOrEmpty(expectedBaseHash) && !string.Equals(a, expectedBaseHash, StringComparison.OrdinalIgnoreCase)) { return SlsAdapterResult.Fail(biomeName, num, ReadBiomeStarCap(biomeName), "Concurrent modification detected: LevelSettings.yaml was changed externally. Aborting to protect user edits."); } if (!TryUpdateBiomeCapInYaml(text, biomeName, num, out var modifiedYaml, out var error)) { return SlsAdapterResult.Fail(biomeName, num, ReadBiomeStarCap(biomeName), "YAML update failed: " + error); } string backupPath = CreateBackupFile(levelSettingsPath, text, slsConfigSnapshot.ContentHashSha256); WriteTextPreservingEncoding(levelSettingsPath, text, modifiedYaml); int num2 = ReadBiomeStarCap(biomeName); if (num2 != num) { RestoreFromBackup(levelSettingsPath, backupPath); return SlsAdapterResult.Fail(biomeName, num, num2, "Verification failed: star cap mismatch after write. Rolled back."); } bool flag = TryReloadSlsInMemory(); if (IsSlsInstalled && !flag) { Log.LogWarning((object)"[StarLevelSystemAdapter] File saved but live in-memory reload deferred; server restart will apply changes."); } Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[StarLevelSystemAdapter] Biome '{0}' star cap set to {1}★ (Effective: {2}★)", biomeName, num, num2)); return SlsAdapterResult.Ok(biomeName, num, num2, IsSlsInstalled && !flag); } catch (Exception ex) { Rollback(slsConfigSnapshot); return SlsAdapterResult.Fail(biomeName, num, ReadBiomeStarCap(biomeName), "Exception during SLS update: " + ex.Message); } } public static bool ReadDefaultStarFrequency(out float frequency, out int maxLevel) { frequency = 0.15f; maxLevel = 6; string levelSettingsPath = GetLevelSettingsPath(); if (!File.Exists(levelSettingsPath)) { return false; } try { string yaml = File.ReadAllText(levelSettingsPath, Encoding.UTF8); ParseDefaultStarFrequencyFromYaml(yaml, out frequency, out maxLevel); return true; } catch { return false; } } public static bool ReadCreatureScalingRates(out float baseHealth, out float starHealth, out float starDamage) { baseHealth = 1f; starHealth = 1f; starDamage = 0.5f; string levelSettingsPath = GetLevelSettingsPath(); if (!File.Exists(levelSettingsPath)) { return false; } try { string yaml = File.ReadAllText(levelSettingsPath, Encoding.UTF8); ParseCreatureScalingFromYaml(yaml, out baseHealth, out starHealth, out starDamage); return true; } catch { return false; } } public static SortedDictionary ComputeExponentialCurve(int minLevel, int maxLevel, float initialChance, float epsilon = 0.01f) { SortedDictionary sortedDictionary = new SortedDictionary(); int num = maxLevel - minLevel; if (num <= 0) { sortedDictionary[minLevel] = 0f; return sortedDictionary; } float num2 = Mathf.Clamp(initialChance, 0.01f, 100f); float num3 = Mathf.Pow(epsilon / num2, 1f / (float)num); for (int i = minLevel; i <= maxLevel; i++) { if (i == maxLevel) { sortedDictionary[i] = epsilon; continue; } float num4 = num2 * Mathf.Pow(num3, (float)(i - minLevel)); sortedDictionary[i] = Mathf.Max(num4, epsilon); } return sortedDictionary; } public static SlsAdapterResult SetDefaultStarDistribution(float starFrequency, int maxCeilingStar, string expectedBaseHash = null) { if (!IsConfigFileAvailable) { return SlsAdapterResult.Fail("Global", maxCeilingStar, -1, "LevelSettings.yaml not found."); } if (!HasAuthority()) { return SlsAdapterResult.Fail("Global", maxCeilingStar, -1, "Unauthorized: StarLevelSystem configuration is server-authoritative. Remote clients cannot alter server settings."); } EnsureBaselineCaptured(); string levelSettingsPath = GetLevelSettingsPath(); SlsConfigSnapshot snapshot = CaptureCurrentState(); lock (s_fileLock) { try { string text = File.ReadAllText(levelSettingsPath, Encoding.UTF8); string text2 = ComputeContentSha256(text); if (!string.IsNullOrEmpty(expectedBaseHash) && !string.Equals(text2, expectedBaseHash, StringComparison.OrdinalIgnoreCase)) { return SlsAdapterResult.Fail("Global", maxCeilingStar, -1, $"Concurrent modification conflict: expected hash {expectedBaseHash}, but file hash is {text2}."); } string backupPath = CreateBackupFile(levelSettingsPath, text, text2); if (!TryUpdateDefaultStarDistributionInYaml(text, starFrequency, maxCeilingStar, out var modifiedYaml, out var error)) { return SlsAdapterResult.Fail("Global", maxCeilingStar, -1, "YAML update error: " + error); } try { WriteTextPreservingEncoding(levelSettingsPath, text, modifiedYaml); } catch (Exception ex) { RestoreFromBackup(levelSettingsPath, backupPath); return SlsAdapterResult.Fail("Global", maxCeilingStar, -1, "File write failure: " + ex.Message); } bool flag = TryReloadSlsInMemory(); return SlsAdapterResult.Ok("Global", maxCeilingStar, maxCeilingStar, !flag); } catch (Exception ex2) { Rollback(snapshot); return SlsAdapterResult.Fail("Global", maxCeilingStar, -1, "Exception during SLS distribution update: " + ex2.Message); } } } public static SlsAdapterResult SetCreatureScalingRates(float? baseHealth, float? starHealth, float? starDamage, string expectedBaseHash = null) { if (!IsConfigFileAvailable) { return SlsAdapterResult.Fail("Scaling", -1, -1, "LevelSettings.yaml not found."); } if (!HasAuthority()) { return SlsAdapterResult.Fail("Scaling", -1, -1, "Unauthorized: StarLevelSystem configuration is server-authoritative. Remote clients cannot alter server settings."); } EnsureBaselineCaptured(); string levelSettingsPath = GetLevelSettingsPath(); SlsConfigSnapshot snapshot = CaptureCurrentState(); lock (s_fileLock) { try { string text = File.ReadAllText(levelSettingsPath, Encoding.UTF8); string text2 = ComputeContentSha256(text); if (!string.IsNullOrEmpty(expectedBaseHash) && !string.Equals(text2, expectedBaseHash, StringComparison.OrdinalIgnoreCase)) { return SlsAdapterResult.Fail("Scaling", -1, -1, $"Concurrent modification conflict: expected hash {expectedBaseHash}, but file hash is {text2}."); } string backupPath = CreateBackupFile(levelSettingsPath, text, text2); if (!TryUpdateCreatureScalingInYaml(text, baseHealth, starHealth, starDamage, out var modifiedYaml, out var error)) { return SlsAdapterResult.Fail("Scaling", -1, -1, "YAML update error: " + error); } try { WriteTextPreservingEncoding(levelSettingsPath, text, modifiedYaml); } catch (Exception ex) { RestoreFromBackup(levelSettingsPath, backupPath); return SlsAdapterResult.Fail("Scaling", -1, -1, "File write failure: " + ex.Message); } bool flag = TryReloadSlsInMemory(); return SlsAdapterResult.Ok("Scaling", 1, 1, !flag); } catch (Exception ex2) { Rollback(snapshot); return SlsAdapterResult.Fail("Scaling", -1, -1, "Exception during SLS creature scaling update: " + ex2.Message); } } } public static bool Rollback(SlsConfigSnapshot snapshot) { if (snapshot == null || string.IsNullOrEmpty(snapshot.FilePath) || !HasAuthority()) { return false; } try { if (File.Exists(snapshot.FilePath) && !string.IsNullOrEmpty(snapshot.RawYamlContent)) { File.WriteAllText(snapshot.FilePath, snapshot.RawYamlContent, Encoding.UTF8); TryReloadSlsInMemory(); Log.LogWarning((object)("[StarLevelSystemAdapter] Restored LevelSettings.yaml to snapshot from " + snapshot.CapturedAtUtc.ToString("o"))); return true; } } catch (Exception ex) { Log.LogError((object)("[StarLevelSystemAdapter] Catastrophic failure during rollback: " + ex.Message)); } return false; } public static bool RestoreToBaseline() { if (s_baselineSnapshot == null) { return false; } return Rollback(s_baselineSnapshot); } internal static void ParseBiomeCapsFromYaml(string yaml, Dictionary targetDict) { if (string.IsNullOrEmpty(yaml) || targetDict == null) { return; } string text = yaml.Replace("\r\n", "\n"); string[] array = text.Split(new char[1] { '\n' }); bool flag = false; string text2 = null; foreach (string text3 in array) { string text4 = text3.Trim(); if (text4.StartsWith("#", StringComparison.Ordinal) || text4.Length == 0) { continue; } if (text3.Length > 0 && !char.IsWhiteSpace(text3[0])) { if (Regex.IsMatch(text3, "^BiomeConfiguration:\\s*(?:#.*)?$")) { flag = true; text2 = null; continue; } if (flag) { flag = false; text2 = null; } } if (!flag) { continue; } Match match = Regex.Match(text3, "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$"); if (match.Success) { text2 = match.Groups[1].Value; } else if (text2 != null) { Match match2 = Regex.Match(text3, "^\\s+BiomeMaxLevelOverride:\\s*(\\d+)\\s*(?:#.*)?$"); if (match2.Success && int.TryParse(match2.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { targetDict[text2] = result; } } } } internal static bool TryUpdateBiomeCapInYaml(string originalYaml, string targetBiome, int newCap, out string modifiedYaml, out string error) { modifiedYaml = null; error = null; if (string.IsNullOrEmpty(originalYaml)) { error = "Original YAML content is empty."; return false; } string separator = (originalYaml.Contains("\r\n") ? "\r\n" : "\n"); string text = originalYaml.Replace("\r\n", "\n"); List list = new List(text.Split(new char[1] { '\n' })); int num = -1; int num2 = 0; for (int i = 0; i < list.Count; i++) { if (Regex.IsMatch(list[i], "^BiomeConfiguration:\\s*(?:#.*)?$")) { num = i; num2++; } } if (num2 == 0) { error = "BiomeConfiguration section not found in LevelSettings.yaml."; return false; } if (num2 > 1) { error = "Multiple BiomeConfiguration sections found; file is ambiguous."; return false; } int num3 = list.Count; for (int j = num + 1; j < list.Count; j++) { if (list[j].Length > 0 && !char.IsWhiteSpace(list[j][0]) && !list[j].TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { num3 = j; break; } } int num4 = -1; int num5 = num3; for (int k = num + 1; k < num3; k++) { Match match = Regex.Match(list[k], "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$"); if (match.Success) { if (string.Equals(match.Groups[1].Value, targetBiome, StringComparison.OrdinalIgnoreCase)) { num4 = k; } else if (num4 >= 0 && num5 == num3) { num5 = k; } } } if (num4 >= 0) { int num6 = -1; for (int l = num4 + 1; l < num5; l++) { if (Regex.IsMatch(list[l], "^\\s+BiomeMaxLevelOverride:\\s*\\d+")) { num6 = l; break; } } if (num6 >= 0) { string input = list[num6]; string value = Regex.Replace(input, "(BiomeMaxLevelOverride:\\s*)\\d+", "${1}" + newCap.ToString(CultureInfo.InvariantCulture)); list[num6] = value; } else { list.Insert(num4 + 1, " BiomeMaxLevelOverride: " + newCap.ToString(CultureInfo.InvariantCulture)); } } else { list.Insert(num3, " " + targetBiome + ":"); list.Insert(num3 + 1, " BiomeMaxLevelOverride: " + newCap.ToString(CultureInfo.InvariantCulture)); } modifiedYaml = string.Join(separator, list.ToArray()); return true; } public static BiomeStarProbabilityReport ComputeNormalizedStarProbabilities(DifficultyPreset preset, string biomeName, float starFrequency, int globalCeilingStars, int biomeStarCap) { BiomeStarProbabilityReport biomeStarProbabilityReport = new BiomeStarProbabilityReport(); biomeStarProbabilityReport.Preset = preset; biomeStarProbabilityReport.BiomeName = biomeName ?? "Unknown"; biomeStarProbabilityReport.GlobalCeilingStars = Mathf.Clamp(globalCeilingStars, 1, 16); biomeStarProbabilityReport.BiomeStarCap = Mathf.Clamp(biomeStarCap, 0, 16); biomeStarProbabilityReport.StarCreatureRate = Mathf.Clamp(starFrequency, 0.01f, 0.99f); BiomeStarProbabilityReport biomeStarProbabilityReport2 = biomeStarProbabilityReport; int maxLevel = biomeStarProbabilityReport2.GlobalCeilingStars + 1; int num = biomeStarProbabilityReport2.BiomeStarCap + 1; SortedDictionary sortedDictionary = ComputeExponentialCurve(1, maxLevel, biomeStarProbabilityReport2.StarCreatureRate * 100f); float num2 = 100f; int count = sortedDictionary.Count; int num3 = 0; foreach (KeyValuePair item in sortedDictionary) { num3++; int key = item.Key; float value = item.Value; int key2 = key - 1; if (key >= num || num3 == count) { int key3 = Mathf.Min(key, num) - 1; float num4 = Mathf.Max(0f, num2 / 100f); if (biomeStarProbabilityReport2.IndividualStarProbabilities.TryGetValue(key3, out var value2)) { biomeStarProbabilityReport2.IndividualStarProbabilities[key3] = value2 + num4; } else { biomeStarProbabilityReport2.IndividualStarProbabilities[key3] = num4; } break; } float value3 = Mathf.Max(0f, (num2 - value) / 100f); biomeStarProbabilityReport2.IndividualStarProbabilities[key2] = value3; num2 = value; } float num5 = 0f; float num6 = float.MaxValue; bool isStrictlyMonotonicDecreasing = true; foreach (KeyValuePair individualStarProbability in biomeStarProbabilityReport2.IndividualStarProbabilities) { num5 += individualStarProbability.Value; biomeStarProbabilityReport2.CumulativeAtOrBelowProbabilities[individualStarProbability.Key] = num5; if (individualStarProbability.Value >= num6) { isStrictlyMonotonicDecreasing = false; } num6 = individualStarProbability.Value; } float num7 = 0f; List list = new List(biomeStarProbabilityReport2.IndividualStarProbabilities.Keys); for (int num8 = list.Count - 1; num8 >= 0; num8--) { int key4 = list[num8]; num7 += biomeStarProbabilityReport2.IndividualStarProbabilities[key4]; biomeStarProbabilityReport2.CumulativeAtOrAboveProbabilities[key4] = num7; } biomeStarProbabilityReport2.TotalProbabilitySum = num5; biomeStarProbabilityReport2.IsStrictlyMonotonicDecreasing = isStrictlyMonotonicDecreasing; return biomeStarProbabilityReport2; } public static BiomeStarProbabilityReport ComputeNormalizedBiomeStarProbabilities(DifficultyPreset preset, string biomeName) { PresetDefinition presetDefinition = PresetDefinition.Get(preset); int biomeStarCap = presetDefinition.GlobalCeilingStars; if (!string.IsNullOrEmpty(biomeName) && presetDefinition.DefaultStarCaps != null && presetDefinition.DefaultStarCaps.TryGetValue(biomeName, out var value)) { biomeStarCap = value; } return ComputeNormalizedStarProbabilities(preset, biomeName, presetDefinition.StarCreatureRate, presetDefinition.GlobalCeilingStars, biomeStarCap); } public static void ParseDefaultGeneratorDetailsFromYaml(string yaml, out int minLevel, out int maxLevel, out float levelUpChance, out string calculationStyle, out SortedDictionary chanceTable) { minLevel = 1; maxLevel = 6; levelUpChance = 0.15f; calculationStyle = string.Empty; chanceTable = new SortedDictionary(); if (string.IsNullOrEmpty(yaml)) { return; } string text = yaml.Replace("\r\n", "\n"); string[] array = text.Split(new char[1] { '\n' }); bool flag = false; bool flag2 = false; bool flag3 = false; foreach (string text2 in array) { if (Regex.IsMatch(text2, "^DefaultLevelupGenerators:\\s*(?:#.*)?$")) { flag = true; flag2 = false; } else if (Regex.IsMatch(text2, "^DefaultCreatureLevelUpChance:\\s*(?:#.*)?$")) { flag2 = true; flag = false; } else if (flag) { if (text2.Length > 0 && !char.IsWhiteSpace(text2[0]) && !text2.TrimStart(new char[0]).StartsWith("-", StringComparison.Ordinal) && !text2.TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { flag = false; continue; } Match match = Regex.Match(text2, "^\\s*(?:-\\s*)?MinLevel:\\s*(\\d+)"); if (match.Success && int.TryParse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out minLevel)) { flag3 = true; } Match match2 = Regex.Match(text2, "^\\s*(?:-\\s*)?MaxLevel:\\s*(\\d+)"); if (match2.Success) { int.TryParse(match2.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out maxLevel); } Match match3 = Regex.Match(text2, "^\\s*(?:-\\s*)?LevelUpChance:\\s*([0-9\\.]+)"); if (match3.Success && float.TryParse(match3.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { levelUpChance = result; } Match match4 = Regex.Match(text2, "^\\s*(?:-\\s*)?LevelupCalculationStyle:\\s*([A-Za-z0-9_]+)"); if (match4.Success) { calculationStyle = match4.Groups[1].Value.Trim(); } } else { if (!flag2) { continue; } if (text2.Length > 0 && !char.IsWhiteSpace(text2[0]) && !text2.TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { flag2 = false; continue; } Match match5 = Regex.Match(text2, "^\\s+(\\d+):\\s*([0-9\\.]+)"); if (match5.Success && int.TryParse(match5.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2) && float.TryParse(match5.Groups[2].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result3)) { chanceTable[result2] = result3; } } } if (flag3 || chanceTable.Count <= 0) { return; } using SortedDictionary.Enumerator enumerator = chanceTable.GetEnumerator(); if (enumerator.MoveNext()) { minLevel = enumerator.Current.Key; } } public static bool ReadDefaultGeneratorDetails(out int minLevel, out int maxLevel, out float levelUpChance, out string calculationStyle, out SortedDictionary chanceTable) { minLevel = 1; maxLevel = 6; levelUpChance = 0.15f; calculationStyle = string.Empty; chanceTable = new SortedDictionary(); string levelSettingsPath = GetLevelSettingsPath(); if (!File.Exists(levelSettingsPath)) { return false; } try { string yaml = File.ReadAllText(levelSettingsPath, Encoding.UTF8); ParseDefaultGeneratorDetailsFromYaml(yaml, out minLevel, out maxLevel, out levelUpChance, out calculationStyle, out chanceTable); return true; } catch { return false; } } public static bool HasDemonstratedDistributionInconsistency(out string inconsistencyReason) { inconsistencyReason = null; if (!ReadDefaultGeneratorDetails(out var minLevel, out var _, out var _, out var calculationStyle, out var chanceTable)) { return false; } if (minLevel != 1) { inconsistencyReason = string.Format(CultureInfo.InvariantCulture, "MinLevel is {0} instead of 1 (causes star floor saturation).", minLevel); return true; } if (!string.Equals(calculationStyle, "Exponential", StringComparison.OrdinalIgnoreCase)) { inconsistencyReason = string.Format(CultureInfo.InvariantCulture, "LevelupCalculationStyle is '{0}' instead of 'Exponential'.", calculationStyle ?? "unset"); return true; } if (chanceTable == null || !chanceTable.ContainsKey(1)) { inconsistencyReason = "DefaultCreatureLevelUpChance is missing key 1 (0-star threshold)."; return true; } float num = 100f; foreach (KeyValuePair item in chanceTable) { if (item.Value >= num) { inconsistencyReason = string.Format(CultureInfo.InvariantCulture, "DefaultCreatureLevelUpChance is not strictly decreasing at level {0} ({1} >= {2}).", item.Key, item.Value, num); return true; } num = item.Value; } return false; } public static bool HasValidExponentialStarDistribution(float expectedStarFrequency, int expectedCeilingStars, out string diagnosticReason) { if (HasDemonstratedDistributionInconsistency(out diagnosticReason)) { return false; } if (!ReadDefaultGeneratorDetails(out var _, out var maxLevel, out var levelUpChance, out var _, out var chanceTable)) { diagnosticReason = "Could not read LevelSettings.yaml generator details."; return false; } int num = expectedCeilingStars + 1; if (maxLevel != num) { diagnosticReason = string.Format(CultureInfo.InvariantCulture, "MaxLevel mismatch: expected {0}, found {1}.", num, maxLevel); return false; } if (Math.Abs(levelUpChance - expectedStarFrequency) >= 0.005f) { diagnosticReason = string.Format(CultureInfo.InvariantCulture, "LevelUpChance mismatch: expected {0:F2}, found {1:F2}.", expectedStarFrequency, levelUpChance); return false; } if (!chanceTable.ContainsKey(num) || Math.Abs(chanceTable[1] - expectedStarFrequency * 100f) >= 0.5f) { diagnosticReason = "DefaultCreatureLevelUpChance table does not match expected frequency/ceiling."; return false; } diagnosticReason = null; return true; } public static void ParseDefaultStarFrequencyFromYaml(string yaml, out float frequency, out int maxLevel) { frequency = 0.15f; maxLevel = 6; if (string.IsNullOrEmpty(yaml)) { return; } string text = yaml.Replace("\r\n", "\n"); string[] array = text.Split(new char[1] { '\n' }); bool flag = false; foreach (string text2 in array) { if (Regex.IsMatch(text2, "^DefaultLevelupGenerators:\\s*(?:#.*)?$")) { flag = true; } else { if (!flag) { continue; } if (text2.Length > 0 && !char.IsWhiteSpace(text2[0]) && !text2.TrimStart(new char[0]).StartsWith("-", StringComparison.Ordinal) && !text2.TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { flag = false; continue; } Match match = Regex.Match(text2, "^\\s*-\\s*MaxLevel:\\s*(\\d+)"); if (!match.Success) { match = Regex.Match(text2, "^\\s+MaxLevel:\\s*(\\d+)"); } if (match.Success) { int.TryParse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out maxLevel); } Match match2 = Regex.Match(text2, "^\\s+LevelUpChance:\\s*([0-9\\.]+)"); if (match2.Success && float.TryParse(match2.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { frequency = result; } } } if (!(frequency <= 0f)) { return; } bool flag2 = false; foreach (string text3 in array) { if (Regex.IsMatch(text3, "^DefaultCreatureLevelUpChance:\\s*(?:#.*)?$")) { flag2 = true; } else { if (!flag2) { continue; } if (text3.Length > 0 && !char.IsWhiteSpace(text3[0]) && !text3.TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { flag2 = false; continue; } Match match3 = Regex.Match(text3, "^\\s+1:\\s*([0-9\\.]+)"); if (match3.Success && float.TryParse(match3.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { frequency = result2 / 100f; } } } } public static bool TryUpdateDefaultStarDistributionInYaml(string originalYaml, float starFrequency, int maxCeilingStar, out string modifiedYaml, out string error) { modifiedYaml = null; error = null; if (string.IsNullOrEmpty(originalYaml)) { error = "Original YAML content is empty."; return false; } float num = Mathf.Clamp(starFrequency, 0.01f, 0.99f); int num2 = Mathf.Clamp(maxCeilingStar, 1, 16); int num3 = num2 + 1; float initialChance = num * 100f; SortedDictionary sortedDictionary = ComputeExponentialCurve(1, num3, initialChance); string separator = (originalYaml.Contains("\r\n") ? "\r\n" : "\n"); string text = originalYaml.Replace("\r\n", "\n"); List list = new List(text.Split(new char[1] { '\n' })); List list2 = new List(); list2.Add("DefaultCreatureLevelUpChance:"); foreach (KeyValuePair item in sortedDictionary) { list2.Add(string.Format(CultureInfo.InvariantCulture, " {0}: {1:0.#####}", item.Key, item.Value)); } List list3 = new List(); list3.Add("DefaultLevelupGenerators:"); list3.Add("- MinLevel: 1"); list3.Add(string.Format(CultureInfo.InvariantCulture, " MaxLevel: {0}", num3)); list3.Add(string.Format(CultureInfo.InvariantCulture, " LevelUpChance: {0:0.##}", num)); list3.Add(" LevelupCalculationStyle: Exponential"); int num4 = -1; int num5 = -1; for (int i = 0; i < list.Count; i++) { if (Regex.IsMatch(list[i], "^DefaultCreatureLevelUpChance:\\s*(?:#.*)?$")) { num4 = i; break; } } if (num4 >= 0) { num5 = list.Count; for (int j = num4 + 1; j < list.Count; j++) { if (list[j].Length > 0 && !char.IsWhiteSpace(list[j][0]) && !list[j].TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { num5 = j; break; } } list.RemoveRange(num4, num5 - num4); list.InsertRange(num4, list2); } else { list.AddRange(list2); } int num6 = -1; int num7 = -1; for (int k = 0; k < list.Count; k++) { if (Regex.IsMatch(list[k], "^DefaultLevelupGenerators:\\s*(?:#.*)?$")) { num6 = k; break; } } if (num6 >= 0) { num7 = list.Count; for (int l = num6 + 1; l < list.Count; l++) { if (list[l].Length > 0 && !char.IsWhiteSpace(list[l][0]) && !list[l].TrimStart(new char[0]).StartsWith("-", StringComparison.Ordinal) && !list[l].TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { num7 = l; break; } } list.RemoveRange(num6, num7 - num6); list.InsertRange(num6, list3); } else { list.AddRange(list3); } modifiedYaml = string.Join(separator, list.ToArray()); return true; } internal static void ParseCreatureScalingFromYaml(string yaml, out float baseHealth, out float starHealth, out float starDamage) { baseHealth = 1f; starHealth = 1f; starDamage = 0.5f; if (string.IsNullOrEmpty(yaml)) { return; } string text = yaml.Replace("\r\n", "\n"); string[] array = text.Split(new char[1] { '\n' }); bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; foreach (string text2 in array) { string text3 = text2.Trim(); if (text3.StartsWith("#", StringComparison.Ordinal) || text3.Length == 0) { continue; } if (text2.Length > 0 && !char.IsWhiteSpace(text2[0])) { if (Regex.IsMatch(text2, "^BiomeConfiguration:\\s*(?:#.*)?$")) { flag = true; flag2 = false; continue; } if (flag) { flag = false; flag2 = false; } } if (!flag) { continue; } if (Regex.IsMatch(text2, "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$")) { Match match = Regex.Match(text2, "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$"); flag2 = string.Equals(match.Groups[1].Value, "All", StringComparison.OrdinalIgnoreCase); flag3 = false; flag4 = false; } else { if (!flag2) { continue; } if (Regex.IsMatch(text2, "^\\s{4}CreatureBaseValueModifiers:\\s*(?:#.*)?$")) { flag3 = true; flag4 = false; continue; } if (Regex.IsMatch(text2, "^\\s{4}CreaturePerLevelValueModifiers:\\s*(?:#.*)?$")) { flag4 = true; flag3 = false; continue; } if (text2.Length > 4 && text2.Substring(0, 4) == " " && (text2.Length <= 4 || !char.IsWhiteSpace(text2[4]))) { flag3 = false; flag4 = false; } if (flag3) { Match match2 = Regex.Match(text2, "^\\s+BaseHealth:\\s*([0-9\\.]+)"); if (match2.Success && float.TryParse(match2.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { baseHealth = result; } } else if (flag4) { Match match3 = Regex.Match(text2, "^\\s+HealthPerLevel:\\s*([0-9\\.]+)"); if (match3.Success && float.TryParse(match3.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { starHealth = result2; } Match match4 = Regex.Match(text2, "^\\s+DamagePerLevel:\\s*([0-9\\.]+)"); if (match4.Success && float.TryParse(match4.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result3)) { starDamage = result3; } } } } } public static bool TryUpdateCreatureScalingInYaml(string originalYaml, float? baseHealth, float? starHealth, float? starDamage, out string modifiedYaml, out string error) { modifiedYaml = null; error = null; if (string.IsNullOrEmpty(originalYaml)) { error = "Original YAML content is empty."; return false; } string separator = (originalYaml.Contains("\r\n") ? "\r\n" : "\n"); string text = originalYaml.Replace("\r\n", "\n"); List list = new List(text.Split(new char[1] { '\n' })); int num = -1; for (int i = 0; i < list.Count; i++) { if (Regex.IsMatch(list[i], "^BiomeConfiguration:\\s*(?:#.*)?$")) { num = i; break; } } if (num == -1) { error = "BiomeConfiguration section not found in LevelSettings.yaml."; return false; } int num2 = list.Count; for (int j = num + 1; j < list.Count; j++) { if (list[j].Length > 0 && !char.IsWhiteSpace(list[j][0]) && !list[j].TrimStart(new char[0]).StartsWith("#", StringComparison.Ordinal)) { num2 = j; break; } } int num3 = -1; int num4 = num2; for (int k = num + 1; k < num2; k++) { Match match = Regex.Match(list[k], "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$"); if (match.Success) { if (string.Equals(match.Groups[1].Value, "All", StringComparison.OrdinalIgnoreCase)) { num3 = k; } else if (num3 >= 0 && num4 == num2) { num4 = k; } } } if (num3 == -1) { List list2 = new List(); list2.Add(" All:"); List collection = list2; list.InsertRange(num + 1, collection); num3 = num + 1; num4 = num3 + 1; } ParseCreatureScalingFromYaml(originalYaml, out var baseHealth2, out var starHealth2, out var starDamage2); float num5 = (baseHealth.HasValue ? baseHealth.Value : baseHealth2); float num6 = (starHealth.HasValue ? starHealth.Value : starHealth2); float num7 = (starDamage.HasValue ? starDamage.Value : starDamage2); int num8 = -1; int num9 = -1; int num10 = -1; int num11 = -1; for (int l = num3 + 1; l < num4; l++) { if (Regex.IsMatch(list[l], "^\\s{4}CreatureBaseValueModifiers:\\s*(?:#.*)?$")) { num8 = l; int m; for (m = l + 1; m < num4 && (list[m].Trim().Length == 0 || (list[m].Length > 4 && char.IsWhiteSpace(list[m][4]))); m++) { } num9 = m; } else if (Regex.IsMatch(list[l], "^\\s{4}CreaturePerLevelValueModifiers:\\s*(?:#.*)?$")) { num10 = l; int n; for (n = l + 1; n < num4 && (list[n].Trim().Length == 0 || (list[n].Length > 4 && char.IsWhiteSpace(list[n][4]))); n++) { } num11 = n; } } List list3 = new List(); list3.Add(" CreatureBaseValueModifiers:"); list3.Add(string.Format(CultureInfo.InvariantCulture, " BaseHealth: {0:0.##}", num5)); List collection2 = list3; List list4 = new List(); list4.Add(" CreaturePerLevelValueModifiers:"); list4.Add(string.Format(CultureInfo.InvariantCulture, " HealthPerLevel: {0:0.##}", num6)); list4.Add(string.Format(CultureInfo.InvariantCulture, " DamagePerLevel: {0:0.##}", num7)); List collection3 = list4; if (num10 >= 0) { list.RemoveRange(num10, num11 - num10); list.InsertRange(num10, collection3); } else { list.InsertRange(num3 + 1, collection3); } num8 = -1; for (int num12 = num3 + 1; num12 < list.Count && (list[num12].Length <= 0 || char.IsWhiteSpace(list[num12][0])) && (!Regex.IsMatch(list[num12], "^ ([A-Za-z_]\\w*):\\s*(?:#.*)?$") || Regex.IsMatch(list[num12], "^ All:\\s*(?:#.*)?$")); num12++) { if (Regex.IsMatch(list[num12], "^\\s{4}CreatureBaseValueModifiers:\\s*(?:#.*)?$")) { num8 = num12; int num13; for (num13 = num12 + 1; num13 < list.Count && (list[num13].Trim().Length == 0 || (list[num13].Length > 4 && char.IsWhiteSpace(list[num13][4]))); num13++) { } num9 = num13; break; } } if (num8 >= 0) { list.RemoveRange(num8, num9 - num8); list.InsertRange(num8, collection2); } else { list.InsertRange(num3 + 1, collection2); } modifiedYaml = string.Join(separator, list.ToArray()); return true; } private static string CreateBackupFile(string originalPath, string content, string hash) { try { string directoryName = Path.GetDirectoryName(originalPath); string fileName = Path.GetFileName(originalPath); string arg = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); string arg2 = ((hash.Length > 8) ? hash.Substring(0, 8) : hash); string path = $"{fileName}.{arg}.{arg2}.bak"; string text = Path.Combine(directoryName, path); File.WriteAllText(text, content, Encoding.UTF8); return text; } catch (Exception ex) { Log.LogWarning((object)("[StarLevelSystemAdapter] Failed to create backup file: " + ex.Message)); return null; } } private static void RestoreFromBackup(string targetPath, string backupPath) { if (!string.IsNullOrEmpty(backupPath) && File.Exists(backupPath)) { try { File.Copy(backupPath, targetPath, overwrite: true); Log.LogWarning((object)("[StarLevelSystemAdapter] Restored original file from backup: " + backupPath)); } catch (Exception ex) { Log.LogError((object)("[StarLevelSystemAdapter] Catastrophic backup restore failure: " + ex.Message)); } } } private static void WriteTextPreservingEncoding(string path, string referenceText, string newText) { Encoding encoding = DetectEncoding(path); File.WriteAllText(path, newText, encoding); } private static Encoding DetectEncoding(string path) { try { using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); if (fileStream.Length >= 3) { byte[] array = new byte[3]; fileStream.Read(array, 0, 3); if (array[0] == 239 && array[1] == 187 && array[2] == 191) { return new UTF8Encoding(encoderShouldEmitUTF8Identifier: true); } } } catch { } return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); } private static bool TryReloadSlsInMemory() { try { Type type = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (string.Equals(assembly.GetName().Name, "StarLevelSystem", StringComparison.OrdinalIgnoreCase)) { type = assembly.GetType("StarLevelSystem.common.YamlConfigManager"); break; } } if (type == null) { return false; } FieldInfo field = type.GetField("LevelSettings", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { return false; } object value = field.GetValue(null); if (value == null) { return false; } MethodInfo method = type.GetMethod("ReloadFromDisk", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { return false; } method.Invoke(null, new object[2] { value, true }); Log.LogInfo((object)"[StarLevelSystemAdapter] Successfully triggered StarLevelSystem live reload and client broadcast."); return true; } catch (Exception ex) { Log.LogWarning((object)("[StarLevelSystemAdapter] TryReloadSlsInMemory failed (non-critical if offline): " + ex.Message)); return false; } } } } namespace TameMate.Survival { public static class SurvivalPolicy0741 { public static bool Finite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } public static float FunctionalBase(float nativeHealth, float basicDamage) { if (!Finite(nativeHealth) || !Finite(basicDamage) || nativeHealth <= 0f || nativeHealth >= 200f || basicDamage <= 0f) { return nativeHealth; } return Math.Max(nativeHealth, Math.Min(240f, Math.Min(nativeHealth * 4f, basicDamage * 3f))); } public static float HealthScale(float nativeHealth, float functionalBase, int level, bool special) { if (special || !Finite(nativeHealth) || !Finite(functionalBase) || nativeHealth <= 0f || functionalBase <= nativeHealth) { return 1f; } return functionalBase / nativeHealth * (1f + (float)Math.Min(49, Math.Max(0, level - 1)) * 0.005f); } public static float PreserveFraction(float health, float maximum) { if (Finite(health) && Finite(maximum) && !(maximum <= 0f)) { return Math.Max(0f, Math.Min(1f, health / maximum)); } return 0f; } public static float GrowthLimit(int difficulty) { return difficulty switch { 3 => 2.2f, 2 => 1.9f, 0 => 1.5f, _ => 1.7f, }; } public static float IncomingFactor(int difficulty, int stars, float observedGrowth, float bloodMoon) { if (!Finite(observedGrowth) || observedGrowth <= 0f || !Finite(bloodMoon) || bloodMoon <= 0f) { return 1f; } int num = ((difficulty < 0 || difficulty > 3) ? 1 : difficulty); stars = Math.Max(0, stars); float num2 = num switch { 3 => 0.6f, 2 => 0.55f, 0 => 0.35f, _ => 0.5f, }; float num3 = num switch { 3 => 0.18f, 2 => 0.14f, 0 => 0.08f, _ => 0.1f, }; float num4 = 1f + (float)stars * num2; float num5 = Math.Min(num4, 1f + 0.5f * (float)Math.Min(2, stars) + num3 * (float)Math.Max(0, stars - 2)); float num6 = observedGrowth * Math.Max(1f, Math.Min(3f, bloodMoon)); float num7 = ((num6 <= 1f) ? num6 : Math.Min(GrowthLimit(num), 1f + (num6 - 1f) * 0.5f)); return Math.Max(0f, Math.Min(1f, num5 / num4 * num7 / num6)); } } public struct VitalsSnapshot0741 { public bool Valid; public float Fraction; public int Level; } public struct DamageSnapshot0741 { public bool Valid; public float Before; } public struct SpeciesVitals0741 { public Character Character; public float Native; public float Functional; } public static class SurvivalRuntime0741 { private static Harmony gameplay; private static Harmony advice; private static ManualLogSource log; private static Func view; private static Func tier; private static Func level; private static Func undead; private static Func healthFactor; private static Func difficulty; private static Func moon; private static Func moonDamage; private static readonly Dictionary Species = new Dictionary(); private static readonly int AdviceKey = StringExtensionMethods.GetStableHashCode("TM_0741_SurvivalAdvice"); private static bool ready; private static bool adviceFailed; private static MethodInfo Required(Type type, string name, params Type[] args) { MethodInfo methodInfo = AccessTools.Method(type, name, args, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.FullName, name); } return methodInfo; } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(SurvivalRuntime0741), name, (Type[])null); } public static void Install() { //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03d2: Expected O, but got Unknown //IL_04fc: Unknown result type (might be due to invalid IL or missing references) //IL_0506: Expected O, but got Unknown if (ready) { return; } log = Logger.CreateLogSource("TameMate Survival"); try { if (!Chainloader.PluginInfos.TryGetValue("mitsu.tamemate", out var value)) { throw new InvalidOperationException("TameMate core not loaded"); } Assembly assembly = ((object)value.Instance).GetType().Assembly; Type type = assembly.GetType("TameMate.SupremeTierEngine", throwOnError: true); Type type2 = assembly.GetType("TameMate.CompanionState", throwOnError: true); Type type3 = assembly.GetType("TameMate.DifficultyManager", throwOnError: true); Type type4 = assembly.GetType("TameMate.UndeadSystem", throwOnError: true); ParameterExpression parameterExpression = Expression.Parameter(typeof(Character)); view = Expression.Lambda>(Expression.Field(parameterExpression, AccessTools.Field(typeof(Character), "m_nview")), new ParameterExpression[1] { parameterExpression }).Compile(); tier = Expression.Lambda>(Expression.Convert(Expression.Call(Required(type, "GetTier", typeof(Character)), parameterExpression), typeof(int)), new ParameterExpression[1] { parameterExpression }).Compile(); level = (Func)Delegate.CreateDelegate(typeof(Func), Required(type2, "Level", typeof(Character))); undead = (Func)Delegate.CreateDelegate(typeof(Func), Required(type4, "IsUndead", typeof(Character))); healthFactor = (Func)Delegate.CreateDelegate(typeof(Func), Required(type, "GetTierHealthMultiplier", typeof(Character))); difficulty = Expression.Lambda>(Expression.Convert(Expression.Property(null, AccessTools.Property(type3, "Current")), typeof(int)), new ParameterExpression[0]).Compile(); moon = (Func)Delegate.CreateDelegate(typeof(Func), AccessTools.PropertyGetter(assembly.GetType("TameMate.BloodMoonManager", throwOnError: true), "IsActive")); MemberExpression memberExpression = Expression.Field(null, AccessTools.Field(assembly.GetType("TameMate.TameMateConfig", throwOnError: true), "BloodMoonDamageMultiplier")); moonDamage = Expression.Lambda>(Expression.Condition(Expression.Equal(memberExpression, Expression.Constant(null, memberExpression.Type)), Expression.Constant(1f), Expression.Property(memberExpression, "Value")), new ParameterExpression[0]).Compile(); MethodInfo methodInfo = Required(type, "GetTierHealthMultiplier", typeof(Character)); MethodInfo methodInfo2 = Required(type, "ApplyTierCombatModifiers", typeof(Character), typeof(Character), typeof(HitData)); MethodInfo methodInfo3 = Required(type, "EnsureTierHealthAndScale", typeof(Character), typeof(bool)); MethodInfo methodInfo4 = Required(typeof(Character), "RPC_SetTamed", typeof(long), typeof(bool)); MethodInfo methodInfo5 = Required(type2, "AddXp", typeof(Character), typeof(int)); MethodInfo methodInfo6 = Required(typeof(ZNetScene), "OnDestroy", Type.EmptyTypes); gameplay = new Harmony("mitsu.tamemate.survival0741"); gameplay.Patch((MethodBase)methodInfo, (HarmonyMethod)null, Hook("Health"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); gameplay.Patch((MethodBase)methodInfo2, Hook("BeforeDamage"), Hook("AfterDamage"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); gameplay.Patch((MethodBase)methodInfo3, Hook("BeforeEnsure"), Hook("AfterEnsure"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); gameplay.Patch((MethodBase)methodInfo4, Hook("BeforeTame"), Hook("AfterTame"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); gameplay.Patch((MethodBase)methodInfo5, Hook("BeforeXp"), Hook("AfterXp"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); gameplay.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, Hook("Clear"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); ready = true; log.LogInfo((object)"0.7.42 companion survival active: selective vitals, authoritative recalculation and wild bonus budget. Native attacks and player difficulty retained."); } catch (Exception ex) { if (gameplay != null) { gameplay.UnpatchSelf(); } ready = false; Species.Clear(); log.LogError((object)("Survival inactive; no partial gameplay hooks retained: " + ex.GetBaseException().Message)); return; } try { advice = new Harmony("mitsu.tamemate.survival-advice0741"); advice.Patch((MethodBase)Required(typeof(GlobalBalance), "AppendGuide", typeof(string)), (HarmonyMethod)null, Hook("Guide"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); advice.Patch((MethodBase)Required(typeof(Player), "OnSpawned", typeof(bool)), (HarmonyMethod)null, Hook("Spawned"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex2) { if (advice != null) { advice.UnpatchSelf(); } log.LogWarning((object)("Survival guide unavailable; gameplay retained: " + ex2.GetBaseException().Message)); } } private static bool NetworkReady(Character c) { ZNetView val = (((Object)(object)c == (Object)null || view == null) ? null : view(c)); if ((Object)(object)val != (Object)null) { return val.IsValid(); } return false; } private static bool Companion(Character c) { if (NetworkReady(c) && !c.IsPlayer()) { return c.IsTamed(); } return false; } private static bool Ordinary(Character c) { if (Companion(c) && !c.IsBoss() && !undead(c)) { return tier(c) != 9; } return false; } private static bool Owner(Character c) { ZNetView val = (((Object)(object)c == (Object)null || view == null) ? null : view(c)); if ((Object)(object)val != (Object)null && val.IsValid()) { return val.IsOwner(); } return false; } private static float BasicDamage(GameObject prefab) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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_005d: Invalid comparison between Unknown and I4 if ((Object)(object)prefab == (Object)null) { return 0f; } ItemDrop component = prefab.GetComponent(); if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null) { return 0f; } Attack attack = component.m_itemData.m_shared.m_attack; if (attack == null || ((int)attack.m_attackType != 0 && (int)attack.m_attackType != 1)) { return 0f; } DamageTypes damage = component.m_itemData.GetDamage(); float num = (damage.m_blunt + damage.m_slash + damage.m_pierce) * attack.m_damageMultiplier; if (!SurvivalPolicy0741.Finite(num) || !(num > 0f)) { return 0f; } return num; } private static void Scan(GameObject[] items, ref float minimum) { if (items == null) { return; } for (int i = 0; i < items.Length; i++) { float num = BasicDamage(items[i]); if (num > 0f && (minimum <= 0f || num < minimum)) { minimum = num; } } } private static float Functional(Character c, float native) { if (native <= 0f || native >= 200f) { return native; } int instanceID = ((Object)c).GetInstanceID(); if (Species.TryGetValue(instanceID, out var value) && object.ReferenceEquals(value.Character, c) && Math.Abs(value.Native - native) < 0.001f) { return value.Functional; } float minimum = 0f; Humanoid val = (Humanoid)(object)((c is Humanoid) ? c : null); if ((Object)(object)val != (Object)null) { Scan(val.m_defaultItems, ref minimum); Scan(val.m_randomWeapon, ref minimum); if ((Object)(object)val.m_unarmedWeapon != (Object)null) { float num = BasicDamage(((Component)val.m_unarmedWeapon).gameObject); if (num > 0f && (minimum <= 0f || num < minimum)) { minimum = num; } } } value.Character = c; value.Native = native; value.Functional = SurvivalPolicy0741.FunctionalBase(native, minimum); if (Species.Count >= 2048) { Species.Clear(); } Species[instanceID] = value; return value.Functional; } public static void Health(Character c, ref float __result) { if (Ordinary(c)) { float maxHealthBase = c.GetMaxHealthBase(); __result *= SurvivalPolicy0741.HealthScale(maxHealthBase, Functional(c, maxHealthBase), level(c), special: false); } } private static VitalsSnapshot0741 Snapshot(Character c) { VitalsSnapshot0741 result = default(VitalsSnapshot0741); if (!Owner(c) || c.IsPlayer()) { return result; } float health = c.GetHealth(); float maxHealth = c.GetMaxHealth(); if (health <= 0f || maxHealth <= 0f || !SurvivalPolicy0741.Finite(health) || !SurvivalPolicy0741.Finite(maxHealth)) { return result; } result.Valid = true; result.Fraction = SurvivalPolicy0741.PreserveFraction(health, maxHealth); result.Level = level(c); return result; } private static void Recalculate(Character c, VitalsSnapshot0741 s) { if (s.Valid && Ordinary(c) && Owner(c)) { float num = c.GetMaxHealthBase() * (float)Math.Max(1, c.GetLevel()) * healthFactor(c); if (SurvivalPolicy0741.Finite(num) && !(num <= 0f)) { c.SetMaxHealth(num); c.SetHealth(c.GetMaxHealth() * s.Fraction); } } } public static void BeforeEnsure(Character c, out VitalsSnapshot0741 __state) { __state = Snapshot(c); } public static void AfterEnsure(Character c, VitalsSnapshot0741 __state) { Recalculate(c, __state); } public static void BeforeTame(Character __instance, bool tamed, out VitalsSnapshot0741 __state) { __state = ((tamed && Owner(__instance) && !__instance.IsTamed()) ? Snapshot(__instance) : default(VitalsSnapshot0741)); } public static void AfterTame(Character __instance, VitalsSnapshot0741 __state) { Recalculate(__instance, __state); } public static void BeforeXp(Character c, out VitalsSnapshot0741 __state) { __state = Snapshot(c); } public static void AfterXp(Character c, VitalsSnapshot0741 __state) { if (__state.Valid && level(c) != __state.Level) { __state.Fraction = 1f; Recalculate(c, __state); } } public static void BeforeDamage(Character attacker, Character target, HitData hit, out DamageSnapshot0741 __state) { __state = default(DamageSnapshot0741); if (NetworkReady(attacker) && !((Object)(object)target == (Object)null) && hit != null && !attacker.IsPlayer() && !attacker.IsTamed() && !attacker.IsBoss() && Companion(target) && !target.IsBoss() && !(target.GetMaxHealthBase() >= 200f)) { float totalDamage = hit.GetTotalDamage(); if (SurvivalPolicy0741.Finite(totalDamage) && !(totalDamage <= 0f)) { __state.Valid = true; __state.Before = totalDamage; } } } public static void AfterDamage(Character attacker, Character target, HitData hit, DamageSnapshot0741 __state) { if (__state.Valid && hit != null) { float totalDamage = hit.GetTotalDamage(); hit.ApplyModifier(SurvivalPolicy0741.IncomingFactor(difficulty(), Math.Max(0, attacker.GetLevel() - 1), totalDamage / __state.Before, moon() ? moonDamage() : 1f)); } } public static void Guide(ref string __result) { __result += (ModLanguage.IsEnglish ? "\n\nCompanion survival: fragile ordinary melee species receive a bounded health floor based on their native basic attack, plus 0.5% health per companion level (up to 24.5%). Assigned points remain separate. Existing ordinary companions recalculate from native stats while preserving their health percentage. Excess wild tier, star, biome and Blood Moon bonuses are softened against companions below 200 native health; stronger companions, native attack damage, bosses and player combat retain their rules. Stronger tiers, equipment and dangerous enemies still matter." : "\n\nSupervivencia de compañeros: las especies ordinarias frágiles con ataque cuerpo a cuerpo reciben una base de salud acotada según su ataque normal y +0.5% de salud por nivel de compañero, hasta 24.5%. Los puntos asignados siguen siendo independientes. Las domas ordinarias se recalculan desde sus estadísticas nativas conservando el porcentaje de salud. Se moderan los bonos acumulados de tier, estrellas, ascensión del bioma y Luna de Sangre contra compañeros con menos de 200 de salud nativa; se conservan las reglas de los compañeros resistentes, el daño base de los ataques, los jefes y el combate del jugador. Los tiers superiores, el equipo y los enemigos peligrosos siguen siendo importantes."); } public static void Spawned(Player __instance) { } public static void Clear() { Species.Clear(); } public static void Uninstall() { if (advice != null) { advice.UnpatchSelf(); } if (gameplay != null) { gameplay.UnpatchSelf(); } ready = false; Species.Clear(); adviceFailed = false; } } } namespace TameMate { public static class TameMateVersion { public const string Major = "0"; public const string Minor = "8"; public const string Patch = "0"; public const string ReleaseStage = "RC1"; public const string PublicVersion = "0.8.0"; public const string DisplayVersion = "0.8.0 RC1"; public const string UpdateTitle = "The RPG Experience Update"; public const string FullTitle = "TameMate 0.8.0 — The RPG Experience Update"; public const string AssemblyVersionString = "0.8.0.0"; public const string PluginGuid = "mitsu.tamemate.lineages"; public const string PluginName = "TameMate Lineages Compatibility"; public const string GuidebookTitleSpanish = "\ud83d\udcdc CÓDICE DE TAMEMATE v0.8.0 · GUÍA Y CONFIGURACIÓN"; public const string GuidebookTitleEnglish = "\ud83d\udcdc TAMEMATE CODEX v0.8.0 · GUIDE & SETTINGS"; public const string DifficultyCodexTitle = "\ud83d\udcdc CÓDICE DE DIFICULTAD Y EXPERIENCIA v0.8.0"; public const string RpgCodexTitleSpanish = "Códice del Personaje | Adaptive RPG Archetypes (v0.8.0)"; public const string RpgCodexTitleEnglish = "Character Codex | Adaptive RPG Archetypes (v0.8.0)"; public const string MasteriesTitleSpanish = "CÓDICE DE MAESTRÍAS Y DOMA v0.8.0"; public const string MasteriesTitleEnglish = "MASTERY & TAMING CODEX v0.8.0"; public const string WelcomeTitleEs = "⚔ ¡Bienvenido a TameMate 0.8.0!"; public const string WelcomeSubtitleEs = "Pulsa [F11] para Dificultad, [F10] para Arquetipos RPG o [F7] para Maestrías."; public const string WelcomeMessageEs = "⚔ ¡Bienvenido a TameMate 0.8.0!\nPulsa [F11] para Dificultad, [F10] para Arquetipos RPG o [F7] para Maestrías."; public const string WelcomeTitleEn = "⚔ Welcome to TameMate 0.8.0!"; public const string WelcomeSubtitleEn = "Press [F11] for Difficulty, [F10] for RPG Archetypes or [F7] for Masteries."; public const string WelcomeMessageEn = "⚔ Welcome to TameMate 0.8.0!\nPress [F11] for Difficulty, [F10] for RPG Archetypes or [F7] for Masteries."; public const string HuginTitleEs = "⚔ TameMate 0.8.0 · The RPG Experience Update"; public const string HuginTitleEn = "⚔ TameMate 0.8.0 · The RPG Experience Update"; public const string HuginTextEs = "¡Saludos, noble guerrero! Has despertado bajo el manto de Odín con el don de vincularte con las bestias del décimo mundo.\n\n• Pulsa [F11] en cualquier momento para ajustar la Dificultad Personalizada (Fácil, Normal, Difícil, Supreme), consultar la Guía del Códice y calibrar estrellas SLS.\n• Pulsa [F10] para abrir el Códice del Personaje (Adaptive RPG Archetypes) e inspeccionar tu afinidad, especializaciones híbridas y desglose de combate.\n• Pulsa [F7] para acceder al Códice de Maestrías Nórdicas, equipar sendas rúnicas y realizar rituales chamánicos.\n• Rueda [U]: tus compañeros en postura Defensiva escoltan en cuña sin estorbar y solo atacan si tú o ellos son agredidos, o si tú golpeas a un enemigo.\n• [F9]: rescata compañeros caídos en tu tumba con protección divina.\n\n• Consagra pasivas con trofeos: consulta Jefes en F11. El trofeo oceánico se usa desde inventario."; public const string HuginTextEn = "Greetings, noble warrior! You have awoken under Odin's mantle with the gift of bonding with the beasts of the tenth realm.\n\n• Press [F11] at any time to adjust Custom Difficulty (Easy, Normal, Hard, Supreme), browse the Codex Guide, and calibrate SLS stars.\n• Press [F10] to open the Character Codex (Adaptive RPG Archetypes) and inspect your affinity, hybrid specializations, and combat breakdown.\n• Press [F7] for the Norse Masteries Codex, equipping runic paths and conducting shamanic rituals.\n• Wheel [U]: your companions in Defensive posture escort in wedge formation without crowding and only attack if you or they are hit, or if you strike first.\n• [F9]: rescue fallen companions at your tombstone with divine shielding.\n\n• Consecrate boss passives with trophies: check Bosses in F11. The ocean horn is used from inventory."; } } namespace TameMate.Lineages { public static class TamingPolicy0740 { private static readonly HashSet Starter = new HashSet(StringComparer.OrdinalIgnoreCase) { "Neck", "Boar", "Boar_piggy", "Deer", "Hare", "Seagull", "Crow", "Chicken", "Hen" }; private static readonly int[] Levels = new int[11] { 0, 1, 18, 32, 46, 60, 75, 88, 94, 0, 98 }; public static bool Peaceful(string prefab, int tier, bool undead) { if (tier == 1 && !undead) { return Starter.Contains(prefab ?? ""); } return false; } public static int Level(int tier) { if (tier < 0 || tier >= Levels.Length) { return 0; } return Levels[tier]; } public static float Scale(int d) { return d switch { 3 => 1.15f, 1 => 0.85f, 0 => 0.5f, _ => 1f, }; } public static float Duration(int d, bool boss) { return (!boss) ? (d switch { 3 => 5, 1 => 3, 0 => 2, _ => 4, }) : (d switch { 3 => 18, 1 => 12, 0 => 10, _ => 15, }); } public static float Threshold(int d, bool boss) { float num = d switch { 3 => 0.2f, 1 => 0.35f, 0 => 0.45f, _ => 0.25f, }; if (!boss) { return num; } return Math.Min(0.25f, num); } public static bool Mature(float now, float first, float last, int d, bool boss) { if (now >= first && now - last <= 15f) { return now - first >= Duration(d, boss); } return false; } } public sealed class RequirementValues0740 { public int Level; public int Strength; public int Agility; public int Intellect; public int Body; public int Vigour; } public static class TamingRules0740 { private sealed class Trial { public Character Target; public Player Actor; public float First; public float Last; public bool Active; } public delegate bool CustomRequirementsDelegate(Character c, ref int level, ref int strength, ref int agility, ref int intellect, ref int body, ref int trophy); private static readonly Dictionary Trials = new Dictionary(); private static Func Tier; private static Func Undead; private static Func Blocked; private static Func Enabled; private static Func Mmo; private static Func Difficulty; private static Func PlayerLevel; private static RequirementCheck CanTame; private static Action Complete; private static Action Track; private static Func Unarmed; private static Func RightItem; private static Action ReadRequirements; private static MethodInfo CoreRequirements; private static FieldInfo AttemptScale; private static Func NativeScale; private static readonly RequirementValues0740 HoverRequirements = new RequirementValues0740(); private static Character hoverTarget; private static Player hoverPlayer; private static int hoverDifficulty; private static float hoverUntil; private static string hoverText; private static string hoverBase; private static string hoverFull; private static bool lastInspectState; private static readonly string[] StatLabelsEn = new string[5] { "STR", "AGI", "INT", "BODY", "VIG" }; private static readonly string[] StatLabelsEs = new string[5] { "FUE", "AGI", "INT", "CUE", "VIG" }; public static CustomRequirementsDelegate CustomRequirementsHook; private static readonly HashSet HerbivoreFoods = new HashSet(StringComparer.OrdinalIgnoreCase) { "Raspberry", "Blueberries", "Mushroom", "MushroomYellow", "MushroomBlue", "Carrot", "Turnip", "Onion", "Dandelion", "Cloudberry", "Barley" }; private static MethodInfo Method(Type type, string name, params Type[] p) { MethodInfo methodInfo = AccessTools.Method(type, name, p, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.FullName, name); } return methodInfo; } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(TamingRules0740), name, (Type[])null); } public static void Install(Harmony h, Assembly core) { ChestFoodQuery.Initialize(); FaunaAiRuntimeSafety.Install(h); Type type = core.GetType("TameMate.TamingRequirements", throwOnError: true); Type type2 = core.GetType("TameMate.UniversalTamingEngine", throwOnError: true); Type type3 = core.GetType("TameMate.SupremeTierEngine", throwOnError: true); Type type4 = core.GetType("TameMate.DifficultyManager", throwOnError: true); Type type5 = core.GetType("TameMate.TameMateConfig", throwOnError: true); Type type6 = core.GetType("TameMate.EpicMMOBridge", throwOnError: true); ParameterExpression parameterExpression = Expression.Parameter(typeof(Character), "c"); Tier = Expression.Lambda>(Expression.Convert(Expression.Call(Method(type3, "GetTier", typeof(Character)), parameterExpression), typeof(int)), new ParameterExpression[1] { parameterExpression }).Compile(); Undead = (Func)Delegate.CreateDelegate(typeof(Func), Method(core.GetType("TameMate.UndeadSystem", throwOnError: true), "IsUndead", typeof(Character))); Blocked = (Func)Delegate.CreateDelegate(typeof(Func), Method(core.GetType("TameMate.BiomeLordsPolicy", throwOnError: true), "IsBlocked", typeof(Character))); CanTame = (RequirementCheck)Delegate.CreateDelegate(typeof(RequirementCheck), Method(type, "CanTame", typeof(Player), typeof(Character), typeof(string).MakeByRefType())); MemberExpression expression = Expression.Property(null, AccessTools.Property(type4, "Current")); Difficulty = Expression.Lambda>(Expression.Convert(expression, typeof(int)), new ParameterExpression[0]).Compile(); NativeScale = (Func)Delegate.CreateDelegate(typeof(Func), AccessTools.PropertyGetter(type4, "TamingRequirementScale")); AttemptScale = AccessTools.Field(typeof(RevisionRuntime), "requirementScale"); if (AttemptScale == null || AttemptScale.FieldType != typeof(Func)) { throw new NotSupportedException("Attempt scale binding changed"); } PlayerLevel = (Func)Delegate.CreateDelegate(typeof(Func), AccessTools.PropertyGetter(type6, "PlayerLevel")); Mmo = (Func)Delegate.CreateDelegate(typeof(Func), AccessTools.PropertyGetter(type6, "IsInstalled")); MemberExpression expression2 = Expression.Field(null, AccessTools.Field(type5, "UniversalTamingEnabled")); Enabled = Expression.Lambda>(Expression.Property(expression2, "Value"), new ParameterExpression[0]).Compile(); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(Player), "p"); RightItem = Expression.Lambda>(Expression.Field(parameterExpression2, AccessTools.Field(typeof(Humanoid), "m_rightItem")), new ParameterExpression[1] { parameterExpression2 }).Compile(); Unarmed = Expression.Lambda>(Expression.Field(parameterExpression2, AccessTools.Field(typeof(Humanoid), "m_unarmedWeapon")), new ParameterExpression[1] { parameterExpression2 }).Compile(); Complete = (Action)Delegate.CreateDelegate(typeof(Action), Method(type2, "CompleteCombatTaming", typeof(Character), typeof(Player))); Track = (Action)Delegate.CreateDelegate(typeof(Action), Method(type2, "NotifyOrEnsureCombatTracker", typeof(Character))); CoreRequirements = AccessTools.Method(type, "GetRequirements", (Type[])null, (Type[])null); if (CoreRequirements == null || CoreRequirements.GetParameters().Length != 11) { throw new NotSupportedException("Requirement signature changed"); } ParameterExpression parameterExpression3 = Expression.Parameter(typeof(RequirementValues0740), "values"); MethodCallExpression methodCallExpression = Expression.Call(Method(typeof(Utils), "GetPrefabName", typeof(GameObject)), Expression.Property(parameterExpression, "gameObject")); List list = new List(); list.Add(parameterExpression); list.Add(methodCallExpression); list.Add(Expression.Call(methodCallExpression, Method(typeof(string), "ToLowerInvariant"))); list.Add(Expression.Call(Method(type3, "GetTier", typeof(Character)), parameterExpression)); list.Add(Expression.Call(parameterExpression, Method(typeof(Character), "IsBoss"))); List list2 = list; string[] array = new string[6] { "Level", "Strength", "Agility", "Intellect", "Body", "Vigour" }; foreach (string fieldName in array) { list2.Add(Expression.Field(parameterExpression3, fieldName)); } ReadRequirements = Expression.Lambda>(Expression.Call(CoreRequirements, list2), new ParameterExpression[2] { parameterExpression, parameterExpression3 }).Compile(); MethodInfo methodInfo = Method(type, "IsPeacefulTameOnly", typeof(Character)); MethodInfo methodInfo2 = Method(type, "CanTame", typeof(Player), typeof(Character), typeof(string).MakeByRefType()); MethodInfo methodInfo3 = Method(type2, "TrySubdueOrTrackDamage", typeof(Character), typeof(Player), typeof(HitData)); MethodInfo methodInfo4 = Method(core.GetType("TameMate.CombatTamingTracker", throwOnError: true), "CompleteTaming", typeof(Player)); MethodInfo methodInfo5 = Method(typeof(Character), "ApplyDamage", typeof(HitData), typeof(bool), typeof(bool), typeof(DamageModifier)); h.Patch((MethodBase)methodInfo, Hook("Peaceful"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)CoreRequirements, (HarmonyMethod)null, Hook("Requirements"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.PropertyGetter(type4, "TamingRequirementScale"), (HarmonyMethod)null, Hook("Scale"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, Hook("CreatureRequirement"), (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo3, Hook("NoPrediction"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo5, Hook("BeforeDamage"), Hook("AfterDamage"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(type2, "CompleteCombatTaming", typeof(Character), typeof(Player)), Hook("BeforeComplete"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo4, Hook("BeforeTrackerComplete"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(core.GetType("TameMate.CombatTamingTracker", throwOnError: true), "Update"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("NoLowHealthSpecies"), (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(core.GetType("TameMate.TameHoverPatch", throwOnError: true), "Postfix", typeof(Tameable), typeof(string).MakeByRefType()), (HarmonyMethod)null, (HarmonyMethod)null, Hook("NoLowHealthSpecies"), (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(typeof(Character), "OnDestroy"), Hook("Destroyed"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(typeof(ZNetScene), "OnDestroy"), Hook("Clear"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(typeof(Tameable), "GetHoverText"), (HarmonyMethod)null, Hook("Hover"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)Method(typeof(Tameable), "DecreaseRemainingTime", typeof(float)), Hook("Food"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo6 = AccessTools.Method(typeof(Tameable), "TamingUpdate", (Type[])null, (Type[])null); if (methodInfo6 != null) { h.Patch((MethodBase)methodInfo6, Hook("AnimalAITamingUpdate"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo7 = AccessTools.Method(typeof(AnimalAI), "UpdateAI", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo7 != null) { h.Patch((MethodBase)methodInfo7, Hook("AnimalAIUpdatePrefix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Type type7 = core.GetType("TameMate.AnimalAIChestFeedingPatch", throwOnError: false); if (type7 != null) { h.Patch((MethodBase)Method(type7, "Postfix", typeof(AnimalAI), typeof(float)), Hook("AnimalChestFeedingPrefix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo8 = AccessTools.Method(typeof(Character), "SetTamed", new Type[1] { typeof(bool) }, (Type[])null); if (methodInfo8 != null) { h.Patch((MethodBase)methodInfo8, (HarmonyMethod)null, Hook("CharacterTamedPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Type type8 = core.GetType("TameMate.VirtualMount", throwOnError: false); if (type8 != null) { MethodInfo methodInfo9 = AccessTools.Method(type8, "Mount", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo9 != null) { h.Patch((MethodBase)methodInfo9, Hook("BeforeVirtualMount"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } MethodInfo methodInfo10 = AccessTools.Method(type8, "TryAttach", new Type[1] { typeof(Tameable) }, (Type[])null); if (methodInfo10 != null) { h.Patch((MethodBase)methodInfo10, Hook("BeforeVirtualTryAttach"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } h.Patch((MethodBase)Method(typeof(GlobalBalance), "AppendGuide", typeof(string)), (HarmonyMethod)null, Hook("Guide"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Type typeFromHandle = typeof(SpecialTiers); if (typeFromHandle != null) { MethodInfo methodInfo11 = AccessTools.Method(typeFromHandle, "EffectiveRequirement", new Type[3] { typeof(int), typeof(Character), typeof(int) }, (Type[])null); if (methodInfo11 != null) { h.Patch((MethodBase)methodInfo11, Hook("EffectiveRequirementPrefix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } Type typeFromHandle2 = typeof(SpecialTierPolicy); if (typeFromHandle2 != null) { MethodInfo methodInfo12 = AccessTools.Method(typeFromHandle2, "Requirement", new Type[4] { typeof(int), typeof(int), typeof(bool), typeof(bool) }, (Type[])null); if (methodInfo12 != null) { h.Patch((MethodBase)methodInfo12, Hook("SpecialTierRequirementPrefix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } h.Patch((MethodBase)Method(typeof(RevisionRuntime), "Configure", typeof(Type)), (HarmonyMethod)null, Hook("SyncAttemptScale"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); SyncAttemptScale(); } public static bool Peaceful(Character __0, ref bool __result) { __result = Object.op_Implicit((Object)(object)__0) && TamingPolicy0740.Peaceful(Utils.GetPrefabName(((Component)__0).gameObject), Tier(__0), Undead(__0)); return false; } public static bool Food(Tameable __instance) { if (!Enabled()) { return true; } Character val = (Object.op_Implicit((Object)(object)__instance) ? ((Component)__instance).GetComponent() : null); if (Object.op_Implicit((Object)(object)val) && !val.IsTamed()) { return PeacefulTarget(val); } return true; } public static void Scale(ref float __result) { __result = TamingPolicy0740.Scale(Difficulty()); } public static float CurrentScale() { return TamingPolicy0740.Scale(Difficulty()); } public static void SyncAttemptScale() { AttemptScale.SetValue(null, new Func(CurrentScale)); } public static void Uninstall() { if (AttemptScale != null && NativeScale != null) { AttemptScale.SetValue(null, NativeScale); } CustomRequirementsHook = null; Clear(); } public static bool EffectiveRequirementPrefix(int raw, Character c, int maximum, ref int __result) { int val = Math.Max(1, maximum - 1); __result = Math.Max(1, Math.Min(raw, val)); return false; } public static bool SpecialTierRequirementPrefix(int raw, int maximum, bool cat, bool undead, ref int __result) { int val = Math.Max(1, maximum - 1); __result = Math.Max(1, Math.Min(raw, val)); return false; } public static void Requirements(Character __0, ref int __5, ref int __6, ref int __7, ref int __8, ref int __9, ref int __10) { if (Object.op_Implicit((Object)(object)__0)) { bool flag = false; if (CustomRequirementsHook != null) { flag = CustomRequirementsHook(__0, ref __5, ref __6, ref __7, ref __8, ref __9, ref __10); } bool flag2 = __0.IsBoss(); int num = Tier(__0); int num2 = TamingPolicy0740.Level(num); bool flag3 = Undead(__0); if (!flag2 && num2 > 0) { __5 = Math.Max(__5, num2 + (flag3 ? 8 : 0)); } else if (flag2 && flag3) { __5 += 8; } if (!flag && !flag2) { int num3 = num switch { 10 => 55, 8 => 48, 7 => 40, 5 => 30, 2 => 12, _ => 0, }; int num4 = ((num == 3) ? 20 : 0); int num5 = ((num == 4) ? 25 : 0); int num6 = ((num == 6) ? 35 : 0); float num7 = (flag3 ? 1.15f : 1f); __6 = Math.Max(__6, (int)Math.Ceiling((float)num3 * num7)); __7 = Math.Max(__7, (int)Math.Ceiling((float)num5 * num7)); __8 = Math.Max(__8, (int)Math.Ceiling((float)num6 * num7)); __9 = Math.Max(__9, (int)Math.Ceiling((float)num4 * num7)); } else if (!flag && flag2 && flag3) { float num8 = 1.15f; __6 = (int)Math.Ceiling((float)__6 * num8); __7 = (int)Math.Ceiling((float)__7 * num8); __8 = (int)Math.Ceiling((float)__8 * num8); __9 = (int)Math.Ceiling((float)__9 * num8); __10 = (int)Math.Ceiling((float)__10 * num8); } } } public static IEnumerable CreatureRequirement(IEnumerable source) { List list = new List(source); int num = 0; int num2 = 0; foreach (CodeInstruction item in list) { if (item.operand is MethodInfo) { MethodInfo methodInfo = (MethodInfo)item.operand; if (methodInfo.Name == "get_TamingRequirementScale" && methodInfo.DeclaringType.FullName == "TameMate.DifficultyManager") { item.opcode = OpCodes.Call; item.operand = Method(typeof(TamingRules0740), "CurrentScale"); num2++; } } } for (int i = 1; i < list.Count; i++) { if (list[i].operand is MethodInfo && ((MethodInfo)list[i].operand).DeclaringType == typeof(RevisionRuntime) && ((MethodInfo)list[i].operand).Name == "SpecialRequirement") { if (list[i - 1].opcode != OpCodes.Ldarg_0) { throw new NotSupportedException("Creature requirement argument changed"); } list[i - 1].opcode = OpCodes.Ldarg_1; num++; } } if (num != 1 || num2 != 1) { throw new NotSupportedException("Expected one special requirement and one scale call"); } return list; } public static IEnumerable NoLowHealthSpecies(IEnumerable source) { List list = new List(source); int num = 0; for (int i = 1; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && object.Equals(list[i].operand, 60f) && list[i - 1].operand is MethodInfo && ((MethodInfo)list[i - 1].operand).Name == "GetMaxHealth") { list[i].operand = 0f; num++; } } if (num == 0) { throw new NotSupportedException("Health-based species shortcut shape changed"); } return list; } public static bool NoPrediction(ref bool __result) { __result = false; return false; } public static void BeforeDamage(Character __instance, HitData __0, out float __state) { __state = ((Object.op_Implicit((Object)(object)__instance) && !__instance.IsPlayer() && !__instance.IsTamed()) ? __instance.GetHealth() : 0f); if (!Object.op_Implicit((Object)(object)__instance) || __instance.IsPlayer() || __instance.IsTamed() || __0 == null || !PeacefulTarget(__instance)) { return; } Character attacker = __0.GetAttacker(); Player val = (Player)(object)((attacker is Player) ? attacker : null); if (Object.op_Implicit((Object)(object)val) && BareHands(val, __0)) { float health = __instance.GetHealth(); if (__0.GetTotalDamage() >= health) { __0.m_damage.m_blunt = Mathf.Max(0.5f, health - 1f); __0.m_damage.m_slash = 0f; __0.m_damage.m_pierce = 0f; __0.m_damage.m_chop = 0f; __0.m_damage.m_pickaxe = 0f; __0.m_damage.m_fire = 0f; __0.m_damage.m_frost = 0f; __0.m_damage.m_lightning = 0f; __0.m_damage.m_poison = 0f; __0.m_damage.m_spirit = 0f; } } } public static bool BareHands(Player actor, HitData hit) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 if (!Object.op_Implicit((Object)(object)actor) || hit == null || (int)hit.m_skill != 11 || RightItem(actor) != null) { return false; } ItemDrop val = Unarmed(actor); if (Object.op_Implicit((Object)(object)val)) { return object.ReferenceEquals(((Humanoid)actor).GetCurrentWeapon(), val.m_itemData); } return false; } private static bool PeacefulTarget(Character c) { return TamingPolicy0740.Peaceful(Utils.GetPrefabName(((Component)c).gameObject), Tier(c), Undead(c)); } public static void AfterDamage(Character __instance, HitData __0, float __state) { //IL_00b2: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)__instance) || __instance.IsPlayer() || __instance.IsTamed() || __instance.IsDead() || __instance.GetHealth() <= 0f || __instance.GetHealth() >= __state || __0 == null || !Enabled()) { return; } CataclysmicHudFormatter.CheckCharacterLevelChange(__instance); Character attacker = __0.GetAttacker(); Player val = (Player)(object)((attacker is Player) ? attacker : null); ZNetView component = ((Component)__instance).GetComponent(); string text = default(string); if (!Object.op_Implicit((Object)(object)val) || ((Character)val).IsDead() || !Object.op_Implicit((Object)(object)component) || !component.IsValid() || !component.IsOwner() || Blocked(__instance) || RevisionRuntime.CoolingDown(__instance) || (PeacefulTarget(__instance) && !BareHands(val, __0)) || (int)__0.m_skill == 0 || !CanTame(val, __instance, out var _) || (!PeacefulTarget(__instance) && !RevisionRuntime.HasTrophy(val, __instance, ref text))) { return; } int instanceID = ((Object)__instance).GetInstanceID(); float time = Time.time; if (!Trials.TryGetValue(instanceID, out var value) || !object.ReferenceEquals(value.Target, __instance) || (Object)(object)value.Actor != (Object)(object)val || !value.Active || time - value.Last > 15f) { if (Trials.Count >= 512) { Trials.Clear(); } Trial trial = new Trial(); trial.Target = __instance; trial.Actor = val; trial.First = time; trial.Active = true; value = trial; Trials[instanceID] = value; } value.Last = time; Track(__instance); if (Ready(__instance, val)) { Complete(__instance, val); } } private static bool Ready(Character c, Player actor) { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)c) || !Object.op_Implicit((Object)(object)actor) || ((Character)actor).IsDead() || !Enabled() || c.IsDead() || c.IsTamed() || c.GetHealth() <= 0f || Blocked(c) || RevisionRuntime.CoolingDown(c)) { return false; } ZNetView component = ((Component)c).GetComponent(); if (!Object.op_Implicit((Object)(object)component) || !component.IsValid() || !component.IsOwner()) { return false; } if (!Trials.TryGetValue(((Object)c).GetInstanceID(), out var value) || !value.Active || !object.ReferenceEquals(value.Target, c) || (Object)(object)value.Actor != (Object)(object)actor) { return false; } if (Vector3.Distance(((Component)c).transform.position, ((Component)actor).transform.position) > 22f) { return false; } bool boss = c.IsBoss() || Tier(c) >= 10; int d = Difficulty(); if (!CanTame(actor, c, out var _)) { return false; } if (PeacefulTarget(c)) { ItemDrop val = Unarmed(actor); if (RightItem(actor) == null && Object.op_Implicit((Object)(object)val) && object.ReferenceEquals(((Humanoid)actor).GetCurrentWeapon(), val.m_itemData)) { if (c.GetMaxHealthBase() <= 25f) { return true; } if (!TamingPolicy0740.Mature(Time.time, value.First, value.Last, d, boss) || c.GetHealthPercentage() > TamingPolicy0740.Threshold(d, boss)) { return false; } return true; } return false; } if (!TamingPolicy0740.Mature(Time.time, value.First, value.Last, d, boss) || c.GetHealthPercentage() > TamingPolicy0740.Threshold(d, boss)) { return false; } string text = default(string); return RevisionRuntime.HasTrophy(actor, c, ref text); } public static bool AnimalChestFeedingPrefix(AnimalAI __0) { if ((Object)(object)__0 == (Object)null) { return true; } Character component = ((Component)__0).GetComponent(); if (!((Object)(object)component == (Object)null) && !component.IsTamed()) { return (Object)(object)((Component)__0).GetComponent() == (Object)null; } return true; } internal static bool IsHerbivoreFood(ItemData item) { if (item == null) { return false; } if ((Object)(object)item.m_dropPrefab != (Object)null && HerbivoreFoods.Contains(((Object)item.m_dropPrefab).name)) { return true; } if (item.m_shared != null && !string.IsNullOrEmpty(item.m_shared.m_name)) { switch (item.m_shared.m_name) { case "$item_raspberries": case "$item_blueberries": case "$item_mushroom": case "$item_mushroomyellow": case "$item_carrot": case "$item_turnip": case "$item_onion": case "$item_dandelion": case "$item_cloudberry": case "$item_barley": return true; } } return false; } private static void ResetHungerTimer(Tameable tameable) { if (!((Object)(object)tameable == (Object)null)) { ZNetView component = ((Component)tameable).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && (Object)(object)ZNet.instance != (Object)null) { component.GetZDO().Set(ZDOVars.s_tameLastFeeding, ZNet.instance.GetTime().Ticks); } } } private static int CalculateTameness(Tameable tameable) { if ((Object)(object)tameable == (Object)null) { return 0; } ZNetView component = ((Component)tameable).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return 0; } FieldInfo fieldInfo = AccessTools.Field(typeof(Tameable), "m_tamingTime"); float num = ((fieldInfo != null) ? ((float)fieldInfo.GetValue(tameable)) : 1800f); if (num <= 0f) { return 100; } float num2 = component.GetZDO().GetFloat(ZDOVars.s_tameTimeLeft, num); return Mathf.Clamp((int)((1f - Mathf.Clamp01(num2 / num)) * 100f), 0, 100); } private static bool TryFeedAnimalFromChest(Tameable tameable) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)tameable == (Object)null) { return false; } ZNetView component = ((Component)tameable).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner()) { return false; } if (ChestFoodQuery.Find(((Component)tameable).GetComponent(), firstOnly: true, out var source, out var meal, out var _) == 0) { return false; } ZNetView component2 = ((Component)source).GetComponent(); if ((Object)(object)component2 != (Object)null && component2.IsValid() && !component2.IsOwner()) { component2.ClaimOwnership(); if (!component2.IsOwner()) { return false; } } Inventory inventory = source.GetInventory(); if (inventory == null || !inventory.RemoveOneItem(meal)) { return false; } ResetHungerTimer(tameable); FieldInfo fieldInfo = AccessTools.Field(typeof(Tameable), "m_sootheEffect"); EffectList val = ((!(fieldInfo != null)) ? ((EffectList)null) : ((EffectList)fieldInfo.GetValue(tameable))); if (val != null) { val.Create(((Component)tameable).transform.position, ((Component)tameable).transform.rotation, ((Component)tameable).transform, 1f, -1, default(ZDOID)); } return true; } public static bool AnimalAITamingUpdate(Tameable __instance) { //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null) { return true; } ZNetView component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner()) { return true; } if (__instance.IsTamed()) { return true; } if ((Object)(object)((Component)__instance).GetComponent() != (Object)null) { return true; } BaseAI component2 = ((Component)__instance).GetComponent(); if ((Object)(object)component2 == (Object)null) { return true; } if (__instance.IsHungry()) { if (component2.IsAlerted()) { return false; } if (!TryFeedAnimalFromChest(__instance)) { return false; } } if (component2.IsAlerted()) { return false; } ZDO zDO = component.GetZDO(); if (zDO == null) { return false; } FieldInfo fieldInfo = AccessTools.Field(typeof(Tameable), "m_tamingTime"); float num = ((fieldInfo != null) ? ((float)fieldInfo.GetValue(__instance)) : 1800f); float num2 = zDO.GetFloat(ZDOVars.s_tameTimeLeft, num); num2 = Mathf.Max(0f, num2 - 3f); zDO.Set(ZDOVars.s_tameTimeLeft, num2); if (num2 <= 0f) { Character component3 = ((Component)__instance).GetComponent(); if ((Object)(object)component3 != (Object)null) { component3.SetTamed(true); FieldInfo fieldInfo2 = AccessTools.Field(typeof(Tameable), "m_tamedEffect"); EffectList val = ((!(fieldInfo2 != null)) ? ((EffectList)null) : ((EffectList)fieldInfo2.GetValue(__instance))); if (val != null) { val.Create(((Component)__instance).transform.position, ((Component)__instance).transform.rotation, (Transform)null, 1f, -1, default(ZDOID)); } Player closestPlayer = Player.GetClosestPlayer(((Component)__instance).transform.position, 30f); if ((Object)(object)closestPlayer != (Object)null && Localization.instance != null) { ((Character)closestPlayer).Message((MessageType)2, component3.m_name + " " + Localization.instance.Localize("$hud_tamedone"), 0, (Sprite)null, false); } MasteriesSystem.RegisterTamedCreature(component3, closestPlayer); } return false; } FieldInfo fieldInfo3 = AccessTools.Field(typeof(Tameable), "m_sootheEffect"); EffectList val2 = ((!(fieldInfo3 != null)) ? ((EffectList)null) : ((EffectList)fieldInfo3.GetValue(__instance))); if (val2 != null) { val2.Create(((Component)__instance).transform.position, ((Component)__instance).transform.rotation, ((Component)__instance).transform, 1f, -1, default(ZDOID)); } return false; } public static void EnsureMonsterCompanionAI(Character c) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_02da: 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_013e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)c == (Object)null || !c.IsTamed()) { return; } string text = ((Object)c).name ?? ""; if (!((Object)(object)((Component)c).GetComponent() != (Object)null) && !text.StartsWith("Deer") && !text.StartsWith("Hare")) { return; } AnimalAI component = ((Component)c).GetComponent(); MonsterAI monster = ((Component)c).GetComponent(); if ((Object)(object)monster != (Object)null) { return; } ZNetView component2 = ((Component)c).GetComponent(); if ((Object)(object)component2 == (Object)null || !component2.IsValid()) { return; } if ((Object)(object)monster == (Object)null) { AgentType pathAgentType = (AgentType)((!((Object)(object)component != (Object)null)) ? 1 : ((int)((BaseAI)component).m_pathAgentType)); float moveMinAngle = (((Object)(object)component != (Object)null) ? ((BaseAI)component).m_moveMinAngle : 0f); bool smoothMovement = (Object)(object)component != (Object)null && ((BaseAI)component).m_smoothMovement; float jumpInterval = (((Object)(object)component != (Object)null) ? ((BaseAI)component).m_jumpInterval : 0f); if (!FaunaAiHandoff.TryReplace(c, component, component2, out monster)) { return; } ((BaseAI)monster).m_viewRange = 30f; ((BaseAI)monster).m_hearRange = 30f; monster.m_alertRange = 20f; ((BaseAI)monster).m_randomMoveInterval = 30f; ((BaseAI)monster).m_randomMoveRange = 4f; ((BaseAI)monster).m_avoidFire = false; ((BaseAI)monster).m_afraidOfFire = false; ((BaseAI)monster).m_pathAgentType = pathAgentType; if ((Object)(object)component != (Object)null) { ((BaseAI)monster).m_moveMinAngle = moveMinAngle; ((BaseAI)monster).m_smoothMovement = smoothMovement; ((BaseAI)monster).m_jumpInterval = jumpInterval; } } FieldInfo fieldInfo = AccessTools.Field(typeof(Character), "m_baseAI"); if (fieldInfo != null) { fieldInfo.SetValue(c, monster); } Tameable component3 = ((Component)c).GetComponent(); if ((Object)(object)component3 != (Object)null) { component3.m_commandable = true; FieldInfo fieldInfo2 = AccessTools.Field(typeof(Tameable), "m_monsterAI"); if (fieldInfo2 != null) { fieldInfo2.SetValue(component3, monster); } if ((Object)(object)component3.m_saddle != (Object)null) { if ((Object)(object)((Component)component3.m_saddle).gameObject != (Object)null && ((Object)((Component)component3.m_saddle).gameObject).name == "TameMate_VirtualMount") { Object.Destroy((Object)(object)((Component)component3.m_saddle).gameObject); } component3.m_saddle = null; } } Type type = AccessTools.TypeByName("TameMate.CompanionMotor"); if (type != null) { Component val = ((Component)c).GetComponent(type); if ((Object)(object)val == (Object)null) { val = ((Component)c).gameObject.AddComponent(type); } if ((Object)(object)val != (Object)null) { FieldInfo fieldInfo3 = AccessTools.Field(type, "ai"); if (fieldInfo3 != null) { fieldInfo3.SetValue(val, monster); } FieldInfo fieldInfo4 = AccessTools.Field(type, "ActiveMotors"); if (fieldInfo4 != null && fieldInfo4.GetValue(null) is IDictionary dictionary) { dictionary[monster] = val; } } } if (!component2.IsOwner()) { return; } Player val2 = Player.GetClosestPlayer(((Component)c).transform.position, 35f); if ((Object)(object)val2 == (Object)null) { val2 = Player.m_localPlayer; } if (!((Object)(object)val2 != (Object)null) || !((Object)(object)component2 != (Object)null) || !component2.IsValid()) { return; } ZDO zDO = component2.GetZDO(); if (zDO == null) { return; } Type type2 = AccessTools.TypeByName("TameMate.CompanionState"); if (!(type2 != null)) { return; } FieldInfo fieldInfo5 = AccessTools.Field(type2, "OwnerKey"); FieldInfo fieldInfo6 = AccessTools.Field(type2, "OrderKey"); FieldInfo fieldInfo7 = AccessTools.Field(type2, "CommandActiveKey"); if (!(fieldInfo6 != null) || zDO.GetInt((int)fieldInfo6.GetValue(null), -1) == -1) { monster.SetFollowTarget(((Component)val2).gameObject); if (fieldInfo5 != null && zDO.GetLong((int)fieldInfo5.GetValue(null), 0L) == 0) { zDO.Set((int)fieldInfo5.GetValue(null), val2.GetPlayerID()); } if (fieldInfo6 != null) { zDO.Set((int)fieldInfo6.GetValue(null), 1, false); } if (fieldInfo7 != null) { zDO.Set((int)fieldInfo7.GetValue(null), 1, false); } } } public static bool AnimalAIUpdatePrefix(AnimalAI __instance, float __0) { if ((Object)(object)__instance == (Object)null) { return true; } Character component = ((Component)__instance).GetComponent(); if ((Object)(object)component != (Object)null && component.IsTamed()) { EnsureMonsterCompanionAI(component); return (Object)(object)((Component)component).GetComponent() == (Object)null; } return true; } public static void CharacterTamedPostfix(Character __instance, bool __0) { if ((Object)(object)__instance != (Object)null && __0) { EnsureMonsterCompanionAI(__instance); MasteriesSystem.RegisterTamedCreature(__instance, null); } } public static bool BeforeVirtualMount(Character __0) { if ((Object)(object)__0 == (Object)null) { return true; } string text = ((Object)__0).name ?? ""; if (text.StartsWith("Deer") || text.StartsWith("Hare") || (Object)(object)((Component)__0).GetComponent() != (Object)null) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { ((Character)localPlayer).Message((MessageType)2, ModLanguage.IsEnglish ? "This creature is too delicate to be ridden." : "Esta criatura es demasiado delicada para ser montada.", 0, (Sprite)null, false); } return false; } return true; } public static bool BeforeVirtualTryAttach(Tameable __0) { if ((Object)(object)__0 == (Object)null) { return true; } Character component = ((Component)__0).GetComponent(); if ((Object)(object)component == (Object)null) { return true; } string text = ((Object)component).name ?? ""; if (text.StartsWith("Deer") || text.StartsWith("Hare") || (Object)(object)((Component)component).GetComponent() != (Object)null) { return false; } return true; } public static bool BeforeComplete(Character __0, Player __1) { if (!Ready(__0, __1)) { return false; } Trials[((Object)__0).GetInstanceID()].Active = false; MasteriesSystem.RegisterTamedCreature(__0, __1); return true; } public static bool BeforeTrackerComplete(Player __0, Character ___character) { return Ready(___character, __0); } public static void Destroyed(Character __instance) { if (Object.op_Implicit((Object)(object)__instance)) { Trials.Remove(((Object)__instance).GetInstanceID()); FaunaAiHandoff.Forget(__instance); } } public static void Clear() { Trials.Clear(); FaunaAiHandoff.Clear(); hoverTarget = null; hoverPlayer = null; hoverText = null; hoverBase = null; hoverFull = null; lastInspectState = false; } private static string ExtractFirstLine(string text) { if (string.IsNullOrEmpty(text)) { return ""; } int num = text.IndexOf('\n'); return ((num >= 0) ? text.Substring(0, num) : text).Trim(); } private static string ExtractTierBadge(string text) { if (string.IsNullOrEmpty(text)) { return null; } int num = text.IndexOf("[Tier "); if (num < 0) { return null; } int num2 = text.IndexOf(']', num); if (num2 > num) { return "" + text.Substring(num, num2 - num + 1) + ""; } return null; } private static string GetShortReason(string raw) { if (string.IsNullOrEmpty(raw)) { if (!ModLanguage.IsEnglish) { return "Requisitos no cumplidos"; } return "Requirements not met"; } int num = raw.IndexOf("Requiere Nivel", StringComparison.OrdinalIgnoreCase); if (num >= 0) { int num2 = raw.IndexOf(")", num); if (num2 > num) { return raw.Substring(num, num2 - num + 1).Trim(); } return raw.Substring(num).Trim(); } num = raw.IndexOf("Requires Level", StringComparison.OrdinalIgnoreCase); if (num >= 0) { int num3 = raw.IndexOf(")", num); if (num3 > num) { return raw.Substring(num, num3 - num + 1).Trim(); } return raw.Substring(num).Trim(); } if (raw.IndexOf("BiomeLords", StringComparison.OrdinalIgnoreCase) >= 0) { if (!ModLanguage.IsEnglish) { return "Indomable por diseño (BiomeLords)"; } return "Untameable by design (BiomeLords)"; } if (raw.IndexOf("trofeo", StringComparison.OrdinalIgnoreCase) >= 0 || raw.IndexOf("trophy", StringComparison.OrdinalIgnoreCase) >= 0) { if (!ModLanguage.IsEnglish) { return "Requiere Trofeo de la especie"; } return "Requires species trophy"; } if (raw.IndexOf("jefe", StringComparison.OrdinalIgnoreCase) >= 0 || raw.IndexOf("boss", StringComparison.OrdinalIgnoreCase) >= 0) { if (!ModLanguage.IsEnglish) { return "Requiere derrotar al jefe del bioma"; } return "Requires defeating biome boss"; } if (raw.Length <= 40) { return raw.Trim(); } return raw.Substring(0, 38).Trim() + "..."; } public static void Hover(Tameable __instance, ref string __result) { Character val = (Object.op_Implicit((Object)(object)__instance) ? ((Component)__instance).GetComponent() : null); Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)val) || val.IsTamed() || !Object.op_Implicit((Object)(object)localPlayer) || !Enabled()) { return; } int num = Difficulty(); bool flag = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303); BaseAI component = ((Component)val).GetComponent(); bool flag2 = (((Object)(object)component != (Object)null && component.IsAlerted()) || ((Character)localPlayer).InAttack() || ((Character)localPlayer).InDodge() || (((Humanoid)localPlayer).GetCurrentWeapon() != null && (Object)(object)((Humanoid)localPlayer).GetCurrentWeapon().m_dropPrefab != (Object)null && !localPlayer.InShelter())) && !flag; if ((Object)(object)val != (Object)(object)hoverTarget || (Object)(object)localPlayer != (Object)(object)hoverPlayer || num != hoverDifficulty || Time.time >= hoverUntil || flag != lastInspectState) { hoverTarget = val; hoverPlayer = localPlayer; hoverDifficulty = num; hoverUntil = Time.time + 0.35f; lastInspectState = flag; hoverFull = null; ReadRequirements(val, HoverRequirements); int num2 = RevisionRuntime.SpecialRequirement(Math.Max(1, Mathf.RoundToInt((float)HoverRequirements.Level * TamingPolicy0740.Scale(num))), val); string reason; bool flag3 = CanTame(localPlayer, val, out reason); bool flag4 = PeacefulTarget(val); bool flag5 = Mmo(); float num3 = ((flag5 || Tier(val) == 9 || Undead(val)) ? SpecialTiers.Chance(flag5 ? PlayerLevel() : num2, num2, val) : 1f); bool boss = val.IsBoss() || Tier(val) >= 10; if (flag2) { string text = ExtractFirstLine(__result); string text2 = ExtractTierBadge(__result); string text3 = ((!string.IsNullOrEmpty(text2)) ? (text2 + " " + text) : text); if (!flag3) { string shortReason = GetShortReason(reason); string text4 = text3; text3 = text4 + "\n\ud83d\udd12 " + (ModLanguage.IsEnglish ? "Taming Locked: " : "Doma Bloqueada: ") + shortReason + ""; } else if (flag4) { text3 = text3 + "\n\ud83c\udf3e " + (ModLanguage.IsEnglish ? "Peaceful Taming (Chests / Bare fists)" : "Doma Pacífica (Alimento en cofre / Puños)") + ""; } else { int num4 = (int)Math.Round(TamingPolicy0740.Threshold(num, boss) * 100f); text3 = text3 + "\n⚔\ufe0f " + (ModLanguage.IsEnglish ? $"Combat Taming (Lower health to ≤{num4}%)" : $"Doma por Combate (Salud ≤{num4}%)") + ""; } if (__instance.IsHungry()) { text3 = text3 + "\n\ud83c\udf7d\ufe0f " + (ModLanguage.IsEnglish ? "[HUNGRY]" : "[HAMBRIENTO]") + ""; } else { int num5 = CalculateTameness(__instance); if (num5 > 0 && num5 < 100) { text3 = text3 + "\n❤\ufe0f " + (ModLanguage.IsEnglish ? $"Taming: {num5}%" : $"Domesticándose: {num5}%") + ""; } } text3 = text3 + "\n" + (ModLanguage.IsEnglish ? "[Hold Shift: Full Details]" : "[Shift: Ver Detalles Completos]") + ""; hoverFull = text3; } else { if (Blocked(val)) { hoverText = (ModLanguage.IsEnglish ? "\n\ud83d\udd12 [BIOMELORDS BOSS — UNTAMEABLE]\nThis supreme entity cannot be tamed by world balance design." : "\n\ud83d\udd12 [JEFE DE BIOMELORDS — INDOMABLE]\nEsta entidad suprema no puede ser domesticada por diseño de balance del mundo."); } else { hoverText = (ModLanguage.IsEnglish ? "\nTaming: " : "\nDoma: "); hoverText += ((!flag4) ? (((!ModLanguage.IsEnglish) ? (flag5 ? "nivel MMO requerido " : "requisito base de progresión ") : (flag5 ? "required MMO level " : "base progression requirement ")) + num2) : (ModLanguage.IsEnglish ? "starter food / bare fists" : "comida inicial / puños sin arma")); if (!flag4) { string[] array = (ModLanguage.IsEnglish ? StatLabelsEn : StatLabelsEs); int[] array2 = new int[5] { HoverRequirements.Strength, HoverRequirements.Agility, HoverRequirements.Intellect, HoverRequirements.Body, HoverRequirements.Vigour }; for (int i = 0; i < array2.Length; i++) { if (array2[i] > 0) { object obj = hoverText; hoverText = string.Concat(obj, " | ", array[i], " ", Mathf.RoundToInt((float)array2[i] * TamingPolicy0740.Scale(num))); } } } object obj2 = hoverText; hoverText = string.Concat(obj2, ModLanguage.IsEnglish ? " | real health ≤" : " | salud real ≤", Math.Round(TamingPolicy0740.Threshold(num, boss) * 100f), "% | ", TamingPolicy0740.Duration(num, boss), " s"); object obj3 = hoverText; hoverText = string.Concat(obj3, ModLanguage.IsEnglish ? " | combat chance " : " | probabilidad de combate ", Math.Round(num3 * 100f), "%"); if (!flag3 && !string.IsNullOrEmpty(reason)) { string text5 = reason.Trim(); if (__result == null || (!__result.Contains(text5) && !__result.Contains("DOMA BLOQUEADA") && !__result.Contains("TAMING LOCKED"))) { hoverText = hoverText + "\n" + text5; } } } if ((Object)(object)component != (Object)null && component.IsAlerted()) { hoverText += (ModLanguage.IsEnglish ? "\n⚠\ufe0f [ALERTED - Step back or sneak so it calms down]" : "\n⚠\ufe0f [ASUSTADO - Aléjate o agáchate en sigilo para que se calme]"); } else if (__instance.IsHungry()) { hoverText += (ModLanguage.IsEnglish ? "\n\ud83c\udf7d\ufe0f [HUNGRY - Put valid food in a nearby chest]" : "\n\ud83c\udf7d\ufe0f [HAMBRIENTO - Pon comida adecuada en un cofre cercano]"); } else { int num6 = CalculateTameness(__instance); hoverText += (ModLanguage.IsEnglish ? $"\n❤\ufe0f [TAMING: {num6}% - Feeding & Calmed]" : $"\n❤\ufe0f [DOMESTICÁNDOSE: {num6}% - Comiendo y Tranquilo]"); } } } if (flag2) { __result = hoverFull; return; } if (hoverFull == null || !string.Equals(hoverBase, __result, StringComparison.Ordinal)) { hoverBase = __result; hoverFull = __result + hoverText; } __result = hoverFull; } public static void Guide(ref string __result) { __result += (ModLanguage.IsEnglish ? "\n\nTaming requirements (0.7.42)\nOnly exact starter species at Feral tier can be tamed with food or bare fists. Other wild creatures require combat or an eligible racial ability; feeding existing companions is unchanged. Higher ordinary tiers use the greater of species and tier requirements. Requirement scales: Easy 50%, Normal 85%, Hard 100%, Supreme 115%. The existing maximum-level normalization still applies. Combat needs actual surviving health at 45/35/25/20% and 2/3/4/5 seconds respectively; bosses need 25/25/25/20% and 10/12/15/18 seconds. A real player hit starts the trial; status ticks and nearby allies cannot finish it for you. Lethal hits kill the creature. One success roll is made per eligible trial; rejection requires a new trial after its cooldown. Racial abilities retain their own roll and do not require injury. Check the hover for live requirements." : "\n\nRequisitos de doma (0.7.42)\nSolo las especies iniciales exactas en tier Feral se domestican con comida o puños sin arma. Las demás criaturas salvajes requieren combate o una habilidad racial válida; alimentar compañeros existentes no cambia. Los tiers ordinarios superiores usan el mayor requisito entre especie y tier. Escalas: Fácil 50%, Normal 85%, Difícil 100%, Supreme 115%; se conserva la normalización al nivel máximo. El combate exige salud real no letal al 45/35/25/20% y 2/3/4/5 segundos, respectivamente. Jefes: 25/25/25/20% y 10/12/15/18 segundos. Un golpe real del jugador inicia la prueba; los estados de daño y otros jugadores cercanos no la terminan por ti. Los golpes letales matan a la criatura. Hay una tirada por prueba válida; tras un rechazo se necesita otra prueba después de la recarga. La habilidad racial conserva su propia tirada sin exigir herir. Consulta los requisitos actuales al apuntar."); } public static void Advice(Player __instance) { if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { AdviceFeature.Queue("tamemate_taming_rules_0742", "TameMate", ModLanguage.IsEnglish ? "Starter Feral animals remain accessible. Higher tiers and Monstrum creatures require progression. Combat uses real health loss, bare fists for starter knockouts, and a sustained trial. See the target's hover and F11." : "Los animales Feral iniciales siguen siendo accesibles. Los tiers superiores y criaturas de Monstrum requieren progresión. La doma de combate usa pérdida real de salud, puños sin arma para los noqueos iniciales y una prueba sostenida. Consulta los requisitos al apuntar y en F11.", "tamemate_guide"); AdviceFeature.Queue("tamemate_passive_saddlebags_0743", ModLanguage.IsEnglish ? "Saddlebags & Resources" : "Alforjas y Recursos", ModLanguage.IsEnglish ? "Tamed companions autonomously generate unique world resources into their saddlebags. Aim at your companion and press Shift + E to open its inventory. Check F11 for species catalogue." : "Tus criaturas domesticadas generan recursos del mundo de forma autónoma en sus alforjas. Apunta a tu compañero y pulsa Shift + E para abrir su inventario. Consulta F11 para ver el catálogo de recursos.", "tamemate_guide"); AdviceFeature.Queue("tamemate_wildlife_fauna_0744", ModLanguage.IsEnglish ? "Wildlife Fauna" : "Fauna Silvestre", ModLanguage.IsEnglish ? "Deer and hares can be knocked out and tamed with bare fists. They follow you and carry saddlebags, but are too delicate to be ridden. Check F11." : "Los ciervos y liebres se domestican noqueándolos a puño limpio. Te seguirán y llevarán alforjas, pero son demasiado delicados para montarlos. Consulta F11.", "tamemate_guide"); AdviceFeature.Queue("tamemate_masteries_codex_0745", ModLanguage.IsEnglish ? "Mastery Codex" : "Códice de Maestrías", ModLanguage.IsEnglish ? "Ancient spirits grant you mastery paths. Press F7 to open the Mastery Codex and choose up to 2 active masteries for you and your beasts. Drag HUD medallions with Shift + Click. Check F11." : "Los espíritus antiguos te otorgan sus Maestrías rúnicas. Pulsa F7 para abrir el Códice y equipar hasta 2 sendas activas para ti y tus bestias. Arrastra los medallones del HUD con Shift + Clic. Consulta F11.", "tamemate_guide"); } } } public static class SpawnAdvice0740 { public static bool TamingActive; private static Action warning; private static bool tamingFailed; private static bool raceFailed; public static void Install(Harmony h, Action report) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown warning = report; tamingFailed = (raceFailed = false); MethodInfo methodInfo = AccessTools.Method(typeof(Player), "OnSpawned", new Type[1] { typeof(bool) }, (Type[])null); if (methodInfo == null) { throw new MissingMethodException("Player", "OnSpawned(bool)"); } h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(SpawnAdvice0740), "Spawned", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void Spawned(Player __instance) { } } public static class FloatingSafety0740 { private static readonly HashSet Reported = new HashSet(); private static Action warning; public static void Install(Harmony h, Action report) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown warning = report; MethodInfo methodInfo = AccessTools.Method(typeof(Floating), "TerrainCheck", Type.EmptyTypes, (Type[])null); FieldInfo fieldInfo = AccessTools.Field(typeof(Floating), "m_nview"); MethodInfo methodInfo2 = AccessTools.Method(typeof(ZNetScene), "OnDestroy", Type.EmptyTypes, (Type[])null); if (methodInfo == null || fieldInfo == null || fieldInfo.FieldType != typeof(ZNetView) || methodInfo2 == null) { throw new NotSupportedException("Floating.TerrainCheck/m_nview or scene teardown signature changed"); } h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FloatingSafety0740), "BeforeTerrain", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(FloatingSafety0740), "Clear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static bool BeforeTerrain(Floating __instance, ref ZNetView ___m_nview) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)__instance)) { return false; } if (!Object.op_Implicit((Object)(object)___m_nview)) { ___m_nview = ((Component)__instance).GetComponent(); } if (!Object.op_Implicit((Object)(object)___m_nview)) { if (Reported.Count < 256 && Reported.Add(((Object)__instance).GetInstanceID()) && warning != null) { warning(string.Concat("Floating.TerrainCheck deferred: object='", ((Object)((Component)__instance).gameObject).name, "' position=", ((Component)__instance).transform.position, "; missing ZNetView. No object removed; native check resumes if the view becomes available.")); } return false; } return (Object)(object)ZoneSystem.instance != (Object)null; } public static void Clear() { Reported.Clear(); } } public static class UndeadMitigationCap { private static Func s_isUndeadFunc; private static Func s_getTierReductionFunc; private static Func s_getEquippedArmorFunc; private static Func s_getMmoDefenseBonusFunc; private static readonly int s_defenseKey = StringExtensionMethods.GetStableHashCode("tm_stat_defense"); private static readonly int s_isUndeadKey = StringExtensionMethods.GetStableHashCode("TM_IsUndead"); private static bool s_installed = false; public static void Install(Harmony harmony, Assembly coreAssembly) { //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Expected O, but got Unknown if (s_installed) { return; } s_installed = true; try { Type type = coreAssembly.GetType("TameMate.UndeadSystem"); if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "IsUndead", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo != null) { s_isUndeadFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo); } } Type type2 = coreAssembly.GetType("TameMate.SupremeTierEngine"); if (type2 != null) { MethodInfo methodInfo2 = AccessTools.Method(type2, "GetTierDamageReduction", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo2 != null) { s_getTierReductionFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo2); } } Type type3 = coreAssembly.GetType("TameMate.CompanionEquipment"); if (type3 != null) { MethodInfo methodInfo3 = AccessTools.Method(type3, "GetTotalEquippedArmor", new Type[1] { typeof(Character) }, (Type[])null); if (methodInfo3 != null) { s_getEquippedArmorFunc = (Func)Delegate.CreateDelegate(typeof(Func), methodInfo3); } } Type type4 = coreAssembly.GetType("TameMate.EpicMMOBridge"); if (type4 != null) { PropertyInfo propertyInfo = AccessTools.Property(type4, "CompanionDefenseBonus"); if (propertyInfo != null && propertyInfo.GetGetMethod() != null) { s_getMmoDefenseBonusFunc = (Func)Delegate.CreateDelegate(typeof(Func), propertyInfo.GetGetMethod()); } } MethodInfo methodInfo4 = AccessTools.Method(typeof(Character), "Damage", new Type[1] { typeof(HitData) }, (Type[])null); MethodInfo methodInfo5 = AccessTools.Method(typeof(UndeadMitigationCap), "ApplyPhysicalMitigationCap", (Type[])null, (Type[])null); if (methodInfo4 != null && methodInfo5 != null) { harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(methodInfo5, 200, (string[])null, (string[])null, (bool?)null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch (Exception ex) { Debug.LogWarning((object)("[TameMate Lineages] UndeadMitigationCap.Install warning: " + ex.Message)); } } public static bool IsUndead(Character c) { if ((Object)(object)c == (Object)null) { return false; } if (s_isUndeadFunc != null) { try { return s_isUndeadFunc(c); } catch { } } ZNetView component = ((Component)c).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (val != null) { return val.GetInt(s_isUndeadKey, 0) == 1; } return false; } public static float GetTierReduction(Character c) { if ((Object)(object)c == (Object)null) { return 0f; } ZNetView component = ((Component)c).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && !object.ReferenceEquals(component, null) && component.IsValid()) ? component.GetZDO() : null); if (val != null) { int effectiveBaseTier = CataclysmicStateReader.GetEffectiveBaseTier(val); bool isCataclysmic = CataclysmicStateReader.IsCataclysmic(val); bool isUndead = IsUndead(c); return CataclysmicCombatPipeline.ComputeEffectiveDamageReduction(effectiveBaseTier, isCataclysmic, isUndead, c.IsTamed()); } if (s_getTierReductionFunc != null) { try { return s_getTierReductionFunc(c); } catch { } } return 0f; } public static float GetEquippedArmor(Character c) { if ((Object)(object)c == (Object)null) { return 0f; } if (s_getEquippedArmorFunc != null) { try { return s_getEquippedArmorFunc(c); } catch { } } return 0f; } public static float GetMmoBonus() { if (s_getMmoDefenseBonusFunc != null) { try { return s_getMmoDefenseBonusFunc(); } catch { } } return 0f; } public static int GetDefensePoints(Character c) { if ((Object)(object)c == (Object)null) { return 0; } ZNetView component = ((Component)c).GetComponent(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (val == null) { return 0; } return val.GetInt(s_defenseKey, 0); } public static float ComputePhysicalCorrectionFactor(float tierRed, int defPoints, float mmoBonus, float equippedArmor, bool isTamed, bool isUndead) { if (!isTamed || !isUndead) { return 1f; } float num = Mathf.Clamp01(1f - tierRed); float num2 = (float)defPoints * 0.02f; float num3 = Mathf.Min(0.6f, num2) + mmoBonus; bool flag = equippedArmor > 0f; if (flag) { float num4 = Mathf.Clamp01(equippedArmor / (equippedArmor + 50f)); num3 = Mathf.Min(0.85f, num3 + num4 * 0.45f); } float num5 = Mathf.Clamp01(1f - num3); float num6 = num * num5; float num7 = (flag ? 0.8f : 0.75f); float num8 = 1f - num7; if (num6 < num8 && num6 > 0.0001f) { return num8 / num6; } return 1f; } [HarmonyPriority(200)] public static void ApplyPhysicalMitigationCap(Character __instance, HitData hit) { if ((Object)(object)__instance == (Object)null || hit == null || !__instance.IsTamed() || __instance.IsPlayer() || !IsUndead(__instance)) { return; } float num = hit.m_damage.m_blunt + hit.m_damage.m_slash + hit.m_damage.m_pierce; if (!(num <= 0.0001f)) { float tierReduction = GetTierReduction(__instance); int defensePoints = GetDefensePoints(__instance); float mmoBonus = GetMmoBonus(); float equippedArmor = GetEquippedArmor(__instance); float num2 = ComputePhysicalCorrectionFactor(tierReduction, defensePoints, mmoBonus, equippedArmor, isTamed: true, isUndead: true); if (num2 > 1.0001f) { ref DamageTypes damage = ref hit.m_damage; damage.m_blunt *= num2; ref DamageTypes damage2 = ref hit.m_damage; damage2.m_slash *= num2; ref DamageTypes damage3 = ref hit.m_damage; damage3.m_pierce *= num2; } } } } public enum PortalMode { Normal, TeleportAll, NoPortals, NoBossPortals } public enum DeathPenaltyMode { Casual, VeryEasy, Normal, Hard, Hardcore } public sealed class VanillaWorldSnapshot { public DateTime CapturedAtUtc { get; set; } public string WorldName { get; set; } public float ResourceRate { get; set; } public float EventRate { get; set; } public float PlayerDamageRate { get; set; } public float EnemyDamageRate { get; set; } public float EnemySpeedSize { get; set; } public float EnemyLevelUpRate { get; set; } public float SkillReductionRate { get; set; } public float StaminaRate { get; set; } public float MoveStaminaRate { get; set; } public float StaminaRegenRate { get; set; } public bool TeleportAll { get; set; } public bool NoPortals { get; set; } public bool NoBossPortals { get; set; } public bool DeathKeepInventory { get; set; } public bool DeathKeepEquip { get; set; } public bool DeathDeleteItems { get; set; } public bool DeathSkillsReset { get; set; } public bool NoBuildCost { get; set; } public bool NoCraftCost { get; set; } public bool PassiveMobs { get; set; } public Dictionary RawScalarKeys { get; private set; } public HashSet RawFlagKeys { get; private set; } public VanillaWorldSnapshot() { CapturedAtUtc = DateTime.UtcNow; WorldName = string.Empty; ResourceRate = 1f; EventRate = 1f; PlayerDamageRate = 1f; EnemyDamageRate = 1f; EnemySpeedSize = 1f; EnemyLevelUpRate = 1f; SkillReductionRate = 1f; StaminaRate = 1f; MoveStaminaRate = 1f; StaminaRegenRate = 1f; RawScalarKeys = new Dictionary(StringComparer.OrdinalIgnoreCase); RawFlagKeys = new HashSet(StringComparer.OrdinalIgnoreCase); } public VanillaWorldSnapshot Clone() { VanillaWorldSnapshot vanillaWorldSnapshot = new VanillaWorldSnapshot(); vanillaWorldSnapshot.CapturedAtUtc = CapturedAtUtc; vanillaWorldSnapshot.WorldName = WorldName; vanillaWorldSnapshot.ResourceRate = ResourceRate; vanillaWorldSnapshot.EventRate = EventRate; vanillaWorldSnapshot.PlayerDamageRate = PlayerDamageRate; vanillaWorldSnapshot.EnemyDamageRate = EnemyDamageRate; vanillaWorldSnapshot.EnemySpeedSize = EnemySpeedSize; vanillaWorldSnapshot.EnemyLevelUpRate = EnemyLevelUpRate; vanillaWorldSnapshot.SkillReductionRate = SkillReductionRate; vanillaWorldSnapshot.StaminaRate = StaminaRate; vanillaWorldSnapshot.MoveStaminaRate = MoveStaminaRate; vanillaWorldSnapshot.StaminaRegenRate = StaminaRegenRate; vanillaWorldSnapshot.TeleportAll = TeleportAll; vanillaWorldSnapshot.NoPortals = NoPortals; vanillaWorldSnapshot.NoBossPortals = NoBossPortals; vanillaWorldSnapshot.DeathKeepInventory = DeathKeepInventory; vanillaWorldSnapshot.DeathKeepEquip = DeathKeepEquip; vanillaWorldSnapshot.DeathDeleteItems = DeathDeleteItems; vanillaWorldSnapshot.DeathSkillsReset = DeathSkillsReset; vanillaWorldSnapshot.NoBuildCost = NoBuildCost; vanillaWorldSnapshot.NoCraftCost = NoCraftCost; vanillaWorldSnapshot.PassiveMobs = PassiveMobs; VanillaWorldSnapshot vanillaWorldSnapshot2 = vanillaWorldSnapshot; foreach (KeyValuePair rawScalarKey in RawScalarKeys) { vanillaWorldSnapshot2.RawScalarKeys[rawScalarKey.Key] = rawScalarKey.Value; } foreach (string rawFlagKey in RawFlagKeys) { vanillaWorldSnapshot2.RawFlagKeys.Add(rawFlagKey); } return vanillaWorldSnapshot2; } } public sealed class WorldAdapterResult { public bool Success { get; private set; } public string ErrorMessage { get; private set; } public string SettingName { get; private set; } public float RequestedValue { get; private set; } public float EffectiveValue { get; private set; } public bool RequiresReload { get; private set; } private WorldAdapterResult() { } public static WorldAdapterResult Ok(string setting, float requested, float effective, bool requiresReload = false) { WorldAdapterResult worldAdapterResult = new WorldAdapterResult(); worldAdapterResult.Success = true; worldAdapterResult.ErrorMessage = string.Empty; worldAdapterResult.SettingName = setting; worldAdapterResult.RequestedValue = requested; worldAdapterResult.EffectiveValue = effective; worldAdapterResult.RequiresReload = requiresReload; return worldAdapterResult; } public static WorldAdapterResult Fail(string setting, float requested, float effective, string reason) { WorldAdapterResult worldAdapterResult = new WorldAdapterResult(); worldAdapterResult.Success = false; worldAdapterResult.ErrorMessage = reason ?? "Unknown failure"; worldAdapterResult.SettingName = setting; worldAdapterResult.RequestedValue = requested; worldAdapterResult.EffectiveValue = effective; worldAdapterResult.RequiresReload = false; return worldAdapterResult; } } public static class VanillaWorldAdapter { private static readonly ManualLogSource Log = Logger.CreateLogSource("TameMate.VanillaWorldAdapter"); private static VanillaWorldSnapshot s_worldBaseline; private static string s_activeWorldName = string.Empty; private static FieldInfo s_fGlobalKeysValues; private static FieldInfo s_fGlobalKeys; private static FieldInfo s_fGlobalKeysEnums; public static bool IsAvailable { get { if (HasRef(ZoneSystem.instance)) { return HasRef(Game.instance); } return false; } } private static bool HasRef(object obj) { return !object.ReferenceEquals(obj, null); } public static bool HasAuthority() { if (!HasRef(ZNet.instance)) { return true; } return ZNet.instance.IsServer(); } public static VanillaWorldSnapshot CaptureCurrentState() { VanillaWorldSnapshot vanillaWorldSnapshot = new VanillaWorldSnapshot(); vanillaWorldSnapshot.CapturedAtUtc = DateTime.UtcNow; vanillaWorldSnapshot.WorldName = (HasRef(ZNet.instance) ? ZNet.instance.GetWorldName() : "UnknownWorld"); if (HasRef(Game.instance)) { vanillaWorldSnapshot.ResourceRate = Game.m_resourceRate; vanillaWorldSnapshot.EventRate = Game.m_eventRate; vanillaWorldSnapshot.PlayerDamageRate = Game.m_playerDamageRate; vanillaWorldSnapshot.EnemyDamageRate = Game.m_enemyDamageRate; vanillaWorldSnapshot.EnemySpeedSize = Game.m_enemySpeedSize; vanillaWorldSnapshot.EnemyLevelUpRate = Game.m_enemyLevelUpRate; vanillaWorldSnapshot.SkillReductionRate = Game.m_skillReductionRate; vanillaWorldSnapshot.StaminaRate = Game.m_staminaRate; vanillaWorldSnapshot.MoveStaminaRate = Game.m_moveStaminaRate; vanillaWorldSnapshot.StaminaRegenRate = Game.m_staminaRegenRate; } if (HasRef(ZoneSystem.instance)) { vanillaWorldSnapshot.TeleportAll = ZoneSystem.instance.GetGlobalKey((GlobalKeys)35); vanillaWorldSnapshot.NoPortals = ZoneSystem.instance.GetGlobalKey((GlobalKeys)32); vanillaWorldSnapshot.NoBossPortals = ZoneSystem.instance.GetGlobalKey((GlobalKeys)33); vanillaWorldSnapshot.DeathKeepInventory = ZoneSystem.instance.GetGlobalKey((GlobalKeys)23); vanillaWorldSnapshot.DeathKeepEquip = ZoneSystem.instance.GetGlobalKey((GlobalKeys)19); vanillaWorldSnapshot.DeathDeleteItems = ZoneSystem.instance.GetGlobalKey((GlobalKeys)20); vanillaWorldSnapshot.DeathSkillsReset = ZoneSystem.instance.GetGlobalKey((GlobalKeys)22); vanillaWorldSnapshot.NoBuildCost = ZoneSystem.instance.GetGlobalKey((GlobalKeys)24); vanillaWorldSnapshot.NoCraftCost = ZoneSystem.instance.GetGlobalKey((GlobalKeys)25); vanillaWorldSnapshot.PassiveMobs = ZoneSystem.instance.GetGlobalKey((GlobalKeys)30); float num = default(float); if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)4, ref num)) { vanillaWorldSnapshot.RawScalarKeys["resourcerate"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)3, ref num)) { vanillaWorldSnapshot.RawScalarKeys["eventrate"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)0, ref num)) { vanillaWorldSnapshot.RawScalarKeys["playerdamage"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)1, ref num)) { vanillaWorldSnapshot.RawScalarKeys["enemydamage"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)13, ref num)) { vanillaWorldSnapshot.RawScalarKeys["skillreductionrate"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)5, ref num)) { vanillaWorldSnapshot.RawScalarKeys["staminarate"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)10, ref num)) { vanillaWorldSnapshot.RawScalarKeys["movestaminarate"] = num.ToString(CultureInfo.InvariantCulture); } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)11, ref num)) { vanillaWorldSnapshot.RawScalarKeys["staminaregenrate"] = num.ToString(CultureInfo.InvariantCulture); } } return vanillaWorldSnapshot; } public static void EnsureBaselineCaptured() { if (IsAvailable) { string text = (HasRef(ZNet.instance) ? ZNet.instance.GetWorldName() : "ActiveWorld"); if (s_worldBaseline == null || s_activeWorldName != text) { s_activeWorldName = text; s_worldBaseline = CaptureCurrentState(); Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Captured baseline for world '{0}': Resources x{1:0.##}, Raids x{2:0.##}, Combat Player x{3:0.##}, Enemy x{4:0.##}", s_activeWorldName, s_worldBaseline.ResourceRate, s_worldBaseline.EventRate, s_worldBaseline.PlayerDamageRate, s_worldBaseline.EnemyDamageRate)); } } } public static VanillaWorldSnapshot GetBaseline() { if (s_worldBaseline == null) { return null; } return s_worldBaseline.Clone(); } public static float ReadEffectiveResourceRate() { if (HasRef(Game.instance)) { return Game.m_resourceRate; } float num = default(float); if (HasRef(ZoneSystem.instance) && ZoneSystem.instance.GetGlobalKey((GlobalKeys)4, ref num)) { return num / 100f; } return 1f; } public static WorldAdapterResult SetResourceRate(float multiplier) { if (!IsAvailable) { return WorldAdapterResult.Fail("ResourceRate", multiplier, ReadEffectiveResourceRate(), "ZoneSystem or Game instance not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("ResourceRate", multiplier, ReadEffectiveResourceRate(), "Unauthorized: World modifiers can only be altered by the server instance (Singleplayer, Host, or Dedicated Server). Remote clients cannot mutate server configuration."); } float num = Mathf.Clamp(multiplier, 0.25f, 5f); EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { float value = num * 100f; SetNativeKey((GlobalKeys)4, value); ForceLocalWorldRatesUpdate(); float num2 = ReadEffectiveResourceRate(); if (Mathf.Abs(num2 - num) > 0.05f) { Rollback(snapshot); return WorldAdapterResult.Fail("ResourceRate", num, num2, string.Format(CultureInfo.InvariantCulture, "Verification failed: requested {0:0.##}x but effective was {1:0.##}x. Rolled back.", num, num2)); } Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Resource multiplier set to {0:0.##}x (Effective: {1:0.##}x)", num, num2)); return WorldAdapterResult.Ok("ResourceRate", num, num2); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("ResourceRate", num, ReadEffectiveResourceRate(), "Exception during apply: " + ex.Message); } } public static bool ReadAreRaidsEnabled() { if (HasRef(Game.instance)) { return Game.m_eventRate > 0.01f; } float num = default(float); if (HasRef(ZoneSystem.instance) && ZoneSystem.instance.GetGlobalKey((GlobalKeys)3, ref num)) { return num > 0.01f; } return true; } public static float ReadEffectiveEventRate() { if (HasRef(Game.instance)) { return Game.m_eventRate; } float num = default(float); if (HasRef(ZoneSystem.instance) && ZoneSystem.instance.GetGlobalKey((GlobalKeys)3, ref num)) { return num / 100f; } return 1f; } public static WorldAdapterResult SetRaidsEnabled(bool enabled, float activeRate = 1f) { if (!IsAvailable) { return WorldAdapterResult.Fail("EventRate", enabled ? activeRate : 0f, ReadEffectiveEventRate(), "ZoneSystem or Game instance not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("EventRate", enabled ? activeRate : 0f, ReadEffectiveEventRate(), "Unauthorized: World modifiers can only be altered by the server instance (Singleplayer, Host, or Dedicated Server). Remote clients cannot mutate server configuration."); } float num = (enabled ? Mathf.Clamp(activeRate, 0.25f, 5f) : 0f); EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { float value = num * 100f; SetNativeKey((GlobalKeys)3, value); ForceLocalWorldRatesUpdate(); float num2 = ReadEffectiveEventRate(); bool flag = num2 > 0.01f; if (flag != enabled) { Rollback(snapshot); return WorldAdapterResult.Fail("EventRate", num, num2, "Verification failed: raid state mismatch after apply. Rolled back."); } Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Raids {0} (EventRate effective: {1:0.##}x)", enabled ? "ENABLED" : "DISABLED", num2)); return WorldAdapterResult.Ok("EventRate", num, num2); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("EventRate", num, ReadEffectiveEventRate(), "Exception during apply: " + ex.Message); } } public static float ReadEffectivePlayerDamage() { if (!HasRef(Game.instance)) { return 1f; } return Game.m_playerDamageRate; } public static float ReadEffectiveEnemyDamage() { if (!HasRef(Game.instance)) { return 1f; } return Game.m_enemyDamageRate; } public static float ReadEffectiveEnemySpeedSize() { if (!HasRef(Game.instance)) { return 1f; } return Game.m_enemySpeedSize; } public static WorldAdapterResult SetEnemySpeedSize(float speedSize) { if (!IsAvailable) { return WorldAdapterResult.Fail("EnemySpeedSize", speedSize, ReadEffectiveEnemySpeedSize(), "Instances not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("EnemySpeedSize", speedSize, ReadEffectiveEnemySpeedSize(), "Unauthorized: World modifiers can only be altered by server."); } float num = Mathf.Clamp(speedSize, 0.5f, 2f); EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { SetNativeKey((GlobalKeys)14, num * 100f); ForceLocalWorldRatesUpdate(); float num2 = ReadEffectiveEnemySpeedSize(); Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] EnemySpeedSize set to {0:0.##} (eff: {1:0.##})", num, num2)); return WorldAdapterResult.Ok("EnemySpeedSize", num, num2); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("EnemySpeedSize", num, ReadEffectiveEnemySpeedSize(), "Exception: " + ex.Message); } } public static WorldAdapterResult SetCombatRates(float playerDamageRate, float enemyDamageRate, float speedSize = 1f, float levelUpRate = 1f) { if (!IsAvailable) { return WorldAdapterResult.Fail("CombatRates", playerDamageRate, ReadEffectivePlayerDamage(), "Instances not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("CombatRates", playerDamageRate, ReadEffectivePlayerDamage(), "Unauthorized: World modifiers can only be altered by the server instance (Singleplayer, Host, or Dedicated Server). Remote clients cannot mutate server configuration."); } float num = Mathf.Clamp(playerDamageRate, 0.1f, 5f); float num2 = Mathf.Clamp(enemyDamageRate, 0.1f, 5f); float num3 = Mathf.Clamp(speedSize, 0.5f, 2f); float num4 = Mathf.Clamp(levelUpRate, 0.1f, 5f); EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { SetNativeKey((GlobalKeys)0, num * 100f); SetNativeKey((GlobalKeys)1, num2 * 100f); SetNativeKey((GlobalKeys)14, num3 * 100f); SetNativeKey((GlobalKeys)15, num4 * 100f); ForceLocalWorldRatesUpdate(); float num5 = ReadEffectivePlayerDamage(); float num6 = ReadEffectiveEnemyDamage(); Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Combat rates applied: Player x{0:0.##} (eff: {1:0.##}), Enemy x{2:0.##} (eff: {3:0.##})", num, num5, num2, num6)); return WorldAdapterResult.Ok("CombatRates", num, num5); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("CombatRates", num, ReadEffectivePlayerDamage(), "Exception: " + ex.Message); } } public static float ReadEffectiveStaminaRate() { if (!HasRef(Game.instance)) { return 1f; } return Game.m_staminaRate; } public static float ReadEffectiveMoveStaminaRate() { if (!HasRef(Game.instance)) { return 1f; } return Game.m_moveStaminaRate; } public static float ReadEffectiveStaminaRegenRate() { if (!HasRef(Game.instance)) { return 1f; } return Game.m_staminaRegenRate; } public static WorldAdapterResult SetStaminaRates(float staminaRate, float moveStaminaRate, float staminaRegenRate) { if (!IsAvailable) { return WorldAdapterResult.Fail("StaminaRates", staminaRate, ReadEffectiveStaminaRate(), "Instances not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("StaminaRates", staminaRate, ReadEffectiveStaminaRate(), "Unauthorized: World modifiers can only be altered by the server instance."); } float num = Mathf.Clamp(staminaRate, 0.25f, 2f); float num2 = Mathf.Clamp(moveStaminaRate, 0.25f, 2f); float num3 = Mathf.Clamp(staminaRegenRate, 0.25f, 2f); EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { SetNativeKey((GlobalKeys)5, num * 100f); SetNativeKey((GlobalKeys)10, num2 * 100f); SetNativeKey((GlobalKeys)11, num3 * 100f); ForceLocalWorldRatesUpdate(); float num4 = ReadEffectiveStaminaRate(); float num5 = ReadEffectiveMoveStaminaRate(); float num6 = ReadEffectiveStaminaRegenRate(); Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Stamina rates applied: Attack x{0:0.##} (eff: {1:0.##}), Move x{2:0.##} (eff: {3:0.##}), Regen x{4:0.##} (eff: {5:0.##})", num, num4, num2, num5, num3, num6)); return WorldAdapterResult.Ok("StaminaRates", num, num4); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("StaminaRates", num, ReadEffectiveStaminaRate(), "Exception: " + ex.Message); } } public static WorldAdapterResult SetStaminaRate(float staminaRate) { return SetStaminaRates(staminaRate, ReadEffectiveMoveStaminaRate(), ReadEffectiveStaminaRegenRate()); } public static WorldAdapterResult SetMoveStaminaRate(float moveStaminaRate) { return SetStaminaRates(ReadEffectiveStaminaRate(), moveStaminaRate, ReadEffectiveStaminaRegenRate()); } public static WorldAdapterResult SetStaminaRegenRate(float staminaRegenRate) { return SetStaminaRates(ReadEffectiveStaminaRate(), ReadEffectiveMoveStaminaRate(), staminaRegenRate); } public static PortalMode ReadEffectivePortalMode() { if (HasRef(ZoneSystem.instance)) { if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)32)) { return PortalMode.NoPortals; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)35)) { return PortalMode.TeleportAll; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)33)) { return PortalMode.NoBossPortals; } } return PortalMode.Normal; } public static WorldAdapterResult SetPortalMode(PortalMode mode) { if (!IsAvailable) { return WorldAdapterResult.Fail("PortalMode", (float)mode, (float)ReadEffectivePortalMode(), "ZoneSystem or Game instance not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("PortalMode", (float)mode, (float)ReadEffectivePortalMode(), "Unauthorized: World modifiers can only be altered by the server instance."); } EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { SetNativeFlag((GlobalKeys)35, mode == PortalMode.TeleportAll); SetNativeFlag((GlobalKeys)32, mode == PortalMode.NoPortals); SetNativeFlag((GlobalKeys)33, mode == PortalMode.NoBossPortals); ForceLocalWorldRatesUpdate(); PortalMode portalMode = ReadEffectivePortalMode(); if (portalMode != mode) { Rollback(snapshot); return WorldAdapterResult.Fail("PortalMode", (float)mode, (float)portalMode, "Verification failed: portal mode mismatch after apply."); } Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Portal mode set to {0}", mode)); return WorldAdapterResult.Ok("PortalMode", (float)mode, (float)portalMode); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("PortalMode", (float)mode, (float)ReadEffectivePortalMode(), "Exception: " + ex.Message); } } public static DeathPenaltyMode ReadEffectiveDeathPenalty() { if (HasRef(ZoneSystem.instance)) { if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)20) || ZoneSystem.instance.GetGlobalKey((GlobalKeys)22)) { return DeathPenaltyMode.Hardcore; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)23)) { return DeathPenaltyMode.Casual; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)19)) { return DeathPenaltyMode.VeryEasy; } float num = 1f; float num2 = default(float); if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)13, ref num2)) { num = num2 / 100f; } else if (HasRef(Game.instance)) { num = Game.m_skillReductionRate; } if (num >= 1.5f) { return DeathPenaltyMode.Hard; } } return DeathPenaltyMode.Normal; } public static WorldAdapterResult SetDeathPenaltyMode(DeathPenaltyMode mode) { if (!IsAvailable) { return WorldAdapterResult.Fail("DeathPenalty", (float)mode, (float)ReadEffectiveDeathPenalty(), "ZoneSystem or Game instance not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("DeathPenalty", (float)mode, (float)ReadEffectiveDeathPenalty(), "Unauthorized: World modifiers can only be altered by the server instance."); } EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { switch (mode) { case DeathPenaltyMode.Casual: SetNativeFlag((GlobalKeys)23, enabled: true); SetNativeFlag((GlobalKeys)19, enabled: false); SetNativeFlag((GlobalKeys)20, enabled: false); SetNativeFlag((GlobalKeys)22, enabled: false); SetNativeKey((GlobalKeys)13, 0f); break; case DeathPenaltyMode.VeryEasy: SetNativeFlag((GlobalKeys)23, enabled: false); SetNativeFlag((GlobalKeys)19, enabled: true); SetNativeFlag((GlobalKeys)20, enabled: false); SetNativeFlag((GlobalKeys)22, enabled: false); SetNativeKey((GlobalKeys)13, 25f); break; case DeathPenaltyMode.Normal: SetNativeFlag((GlobalKeys)23, enabled: false); SetNativeFlag((GlobalKeys)19, enabled: false); SetNativeFlag((GlobalKeys)20, enabled: false); SetNativeFlag((GlobalKeys)22, enabled: false); SetNativeKey((GlobalKeys)13, 100f); break; case DeathPenaltyMode.Hard: SetNativeFlag((GlobalKeys)23, enabled: false); SetNativeFlag((GlobalKeys)19, enabled: false); SetNativeFlag((GlobalKeys)20, enabled: false); SetNativeFlag((GlobalKeys)22, enabled: false); SetNativeKey((GlobalKeys)13, 200f); break; case DeathPenaltyMode.Hardcore: SetNativeFlag((GlobalKeys)23, enabled: false); SetNativeFlag((GlobalKeys)19, enabled: false); SetNativeFlag((GlobalKeys)20, enabled: true); SetNativeFlag((GlobalKeys)22, enabled: true); SetNativeKey((GlobalKeys)13, 100f); break; } ForceLocalWorldRatesUpdate(); DeathPenaltyMode deathPenaltyMode = ReadEffectiveDeathPenalty(); if (deathPenaltyMode != mode) { Rollback(snapshot); return WorldAdapterResult.Fail("DeathPenalty", (float)mode, (float)deathPenaltyMode, "Verification failed: death penalty mode mismatch after apply."); } Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, "[VanillaWorldAdapter] Death penalty set to {0}", mode)); return WorldAdapterResult.Ok("DeathPenalty", (float)mode, (float)deathPenaltyMode); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("DeathPenalty", (float)mode, (float)ReadEffectiveDeathPenalty(), "Exception: " + ex.Message); } } public static bool ReadEffectiveFreeBuild() { if (HasRef(ZoneSystem.instance)) { return ZoneSystem.instance.GetGlobalKey((GlobalKeys)24); } return false; } public static WorldAdapterResult SetFreeBuild(bool free) { if (!IsAvailable) { return WorldAdapterResult.Fail("FreeBuild", free ? 1f : 0f, ReadEffectiveFreeBuild() ? 1f : 0f, "ZoneSystem or Game instance not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("FreeBuild", free ? 1f : 0f, ReadEffectiveFreeBuild() ? 1f : 0f, "Unauthorized."); } EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { SetNativeFlag((GlobalKeys)24, free); ForceLocalWorldRatesUpdate(); bool flag = ReadEffectiveFreeBuild(); if (flag != free) { Rollback(snapshot); return WorldAdapterResult.Fail("FreeBuild", free ? 1f : 0f, flag ? 1f : 0f, "Verification failed."); } Log.LogInfo((object)$"[VanillaWorldAdapter] FreeBuild set to {free}"); return WorldAdapterResult.Ok("FreeBuild", free ? 1f : 0f, flag ? 1f : 0f); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("FreeBuild", free ? 1f : 0f, ReadEffectiveFreeBuild() ? 1f : 0f, "Exception: " + ex.Message); } } public static bool ReadEffectiveFreeCraft() { if (HasRef(ZoneSystem.instance)) { return ZoneSystem.instance.GetGlobalKey((GlobalKeys)25); } return false; } public static WorldAdapterResult SetFreeCraft(bool free) { if (!IsAvailable) { return WorldAdapterResult.Fail("FreeCraft", free ? 1f : 0f, ReadEffectiveFreeCraft() ? 1f : 0f, "ZoneSystem or Game instance not ready."); } if (!HasAuthority()) { return WorldAdapterResult.Fail("FreeCraft", free ? 1f : 0f, ReadEffectiveFreeCraft() ? 1f : 0f, "Unauthorized."); } EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { SetNativeFlag((GlobalKeys)25, free); ForceLocalWorldRatesUpdate(); bool flag = ReadEffectiveFreeCraft(); if (flag != free) { Rollback(snapshot); return WorldAdapterResult.Fail("FreeCraft", free ? 1f : 0f, flag ? 1f : 0f, "Verification failed."); } Log.LogInfo((object)$"[VanillaWorldAdapter] FreeCraft set to {free}"); return WorldAdapterResult.Ok("FreeCraft", free ? 1f : 0f, flag ? 1f : 0f); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("FreeCraft", free ? 1f : 0f, ReadEffectiveFreeCraft() ? 1f : 0f, "Exception: " + ex.Message); } } public static WorldAdapterResult CombinePresetWithOverrides(float playerDamage, float enemyDamage, float? customResources, bool? raidsEnabled) { if (!IsAvailable || !HasAuthority()) { return WorldAdapterResult.Fail("CombinePreset", 0f, 0f, "Unavailable or unauthorized."); } EnsureBaselineCaptured(); VanillaWorldSnapshot snapshot = CaptureCurrentState(); try { WorldAdapterResult worldAdapterResult = SetCombatRates(playerDamage, enemyDamage); if (!worldAdapterResult.Success) { throw new InvalidOperationException("Combat apply failed: " + worldAdapterResult.ErrorMessage); } if (customResources.HasValue) { WorldAdapterResult worldAdapterResult2 = SetResourceRate(customResources.Value); if (!worldAdapterResult2.Success) { throw new InvalidOperationException("Resource apply failed: " + worldAdapterResult2.ErrorMessage); } } if (raidsEnabled.HasValue) { WorldAdapterResult worldAdapterResult3 = SetRaidsEnabled(raidsEnabled.Value); if (!worldAdapterResult3.Success) { throw new InvalidOperationException("Raids apply failed: " + worldAdapterResult3.ErrorMessage); } } return WorldAdapterResult.Ok("CombinePreset", customResources ?? 1f, ReadEffectiveResourceRate()); } catch (Exception ex) { Rollback(snapshot); return WorldAdapterResult.Fail("CombinePreset", 0f, 0f, "Transaction aborted, rolled back: " + ex.Message); } } public static bool Rollback(VanillaWorldSnapshot snapshot) { if (snapshot == null || !IsAvailable || !HasAuthority()) { return false; } try { SetNativeKey((GlobalKeys)4, snapshot.ResourceRate * 100f); SetNativeKey((GlobalKeys)3, snapshot.EventRate * 100f); SetNativeKey((GlobalKeys)0, snapshot.PlayerDamageRate * 100f); SetNativeKey((GlobalKeys)1, snapshot.EnemyDamageRate * 100f); SetNativeKey((GlobalKeys)14, snapshot.EnemySpeedSize * 100f); SetNativeKey((GlobalKeys)15, snapshot.EnemyLevelUpRate * 100f); SetNativeKey((GlobalKeys)13, snapshot.SkillReductionRate * 100f); SetNativeKey((GlobalKeys)5, snapshot.StaminaRate * 100f); SetNativeKey((GlobalKeys)10, snapshot.MoveStaminaRate * 100f); SetNativeKey((GlobalKeys)11, snapshot.StaminaRegenRate * 100f); SetNativeFlag((GlobalKeys)35, snapshot.TeleportAll); SetNativeFlag((GlobalKeys)32, snapshot.NoPortals); SetNativeFlag((GlobalKeys)33, snapshot.NoBossPortals); SetNativeFlag((GlobalKeys)23, snapshot.DeathKeepInventory); SetNativeFlag((GlobalKeys)19, snapshot.DeathKeepEquip); SetNativeFlag((GlobalKeys)20, snapshot.DeathDeleteItems); SetNativeFlag((GlobalKeys)22, snapshot.DeathSkillsReset); SetNativeFlag((GlobalKeys)24, snapshot.NoBuildCost); SetNativeFlag((GlobalKeys)25, snapshot.NoCraftCost); ForceLocalWorldRatesUpdate(); Log.LogWarning((object)("[VanillaWorldAdapter] World modifiers rolled back to snapshot from " + snapshot.CapturedAtUtc.ToString("o"))); return true; } catch (Exception ex) { Log.LogError((object)("[VanillaWorldAdapter] Catastrophic failure during rollback: " + ex.Message)); return false; } } public static bool RestoreToWorldBaseline() { if (s_worldBaseline == null) { return false; } return Rollback(s_worldBaseline); } private static void ForceLocalWorldRatesUpdate() { if (HasRef(ZoneSystem.instance) && HasRef(Game.instance)) { try { ZoneSystem.instance.UpdateWorldRates(); } catch (Exception ex) { Log.LogWarning((object)("[VanillaWorldAdapter] Native UpdateWorldRates GUI/achievement reflection deferred: " + ex.Message)); } SyncGameRatesDirectly(); } } private static void SyncGameRatesDirectly() { if (HasRef(ZoneSystem.instance) && HasRef(Game.instance)) { float num = default(float); if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)4, ref num)) { Game.m_resourceRate = num / 100f; } else { Game.m_resourceRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)3, ref num)) { Game.m_eventRate = num / 100f; } else { Game.m_eventRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)0, ref num)) { Game.m_playerDamageRate = num / 100f; } else { Game.m_playerDamageRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)1, ref num)) { Game.m_enemyDamageRate = num / 100f; } else { Game.m_enemyDamageRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)14, ref num)) { Game.m_enemySpeedSize = num / 100f; } else { Game.m_enemySpeedSize = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)15, ref num)) { Game.m_enemyLevelUpRate = num / 100f; } else { Game.m_enemyLevelUpRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)13, ref num)) { Game.m_skillReductionRate = num / 100f; } else { Game.m_skillReductionRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)5, ref num)) { Game.m_staminaRate = num / 100f; } else { Game.m_staminaRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)10, ref num)) { Game.m_moveStaminaRate = num / 100f; } else { Game.m_moveStaminaRate = 1f; } if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)11, ref num)) { Game.m_staminaRegenRate = num / 100f; } else { Game.m_staminaRegenRate = 1f; } } } private static void SetNativeKey(GlobalKeys key, float value) { //IL_0019: 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) if (HasRef(ZRoutedRpc.instance)) { ZoneSystem.instance.SetGlobalKey(key, value); } else { DirectSetKeyOffline(key, value); } } private static void SetNativeFlag(GlobalKeys key, bool enabled) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (HasRef(ZRoutedRpc.instance)) { if (enabled) { ZoneSystem.instance.SetGlobalKey(key); } else { ZoneSystem.instance.RemoveGlobalKey(key); } } else { DirectSetFlagOffline(key, enabled); } } private static void DirectSetKeyOffline(GlobalKeys key, float value) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) if (HasRef(ZoneSystem.instance)) { EnsureReflectionFields(); string key2 = ((object)key).ToString().ToLowerInvariant(); string text = value.ToString(CultureInfo.InvariantCulture); Dictionary dictionary = ((s_fGlobalKeysValues != null) ? (s_fGlobalKeysValues.GetValue(ZoneSystem.instance) as Dictionary) : null); if (dictionary != null) { dictionary[key2] = text; } ((s_fGlobalKeysEnums != null) ? (s_fGlobalKeysEnums.GetValue(ZoneSystem.instance) as HashSet) : null)?.Add(key); ((s_fGlobalKeys != null) ? (s_fGlobalKeys.GetValue(ZoneSystem.instance) as HashSet) : null)?.Add(string.Format(CultureInfo.InvariantCulture, "{0} {1}", key, text)); } } private static void DirectSetFlagOffline(GlobalKeys key, bool enabled) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) if (!HasRef(ZoneSystem.instance)) { return; } EnsureReflectionFields(); HashSet hashSet = ((s_fGlobalKeysEnums != null) ? (s_fGlobalKeysEnums.GetValue(ZoneSystem.instance) as HashSet) : null); if (hashSet != null) { if (enabled) { hashSet.Add(key); } else { hashSet.Remove(key); } } HashSet hashSet2 = ((s_fGlobalKeys != null) ? (s_fGlobalKeys.GetValue(ZoneSystem.instance) as HashSet) : null); if (hashSet2 != null) { if (enabled) { hashSet2.Add(((object)key).ToString()); } else { hashSet2.Remove(((object)key).ToString()); } } } private static void EnsureReflectionFields() { if (s_fGlobalKeysValues == null && HasRef(ZoneSystem.instance)) { Type typeFromHandle = typeof(ZoneSystem); s_fGlobalKeysValues = typeFromHandle.GetField("m_globalKeysValues", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); s_fGlobalKeys = typeFromHandle.GetField("m_globalKeys", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); s_fGlobalKeysEnums = typeFromHandle.GetField("m_globalKeysEnums", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } } }