Decompiled source of POGLib v0.1.0
POGLib.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using HarmonyLib; using Il2Cpp; using Il2CppEntities; using Il2CppGame.Gameplay; using Il2CppGame.Journal; using Il2CppGame.Networking; using Il2CppI2.Loc; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppInventory; using Il2CppItems; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Reflection; using MelonLoader; using POGLib; using POGLib.Core; using POGLib.Items; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: MelonInfo(typeof(Plugin), "POGLib", "0.1.0", "largo", null)] [assembly: MelonGame(null, "Pit of Goblin")] [assembly: MelonPriority(-1000)] [assembly: HarmonyDontPatchAll] [assembly: InternalsVisibleTo("POGShops")] [assembly: InternalsVisibleTo("POGLibRuntimeDriver")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("POGLib")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+b5619a05bea7c9f5bb75ab270bed9fe461336193")] [assembly: AssemblyProduct("POGLib")] [assembly: AssemblyTitle("POGLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace POGLib { public class Plugin : MelonMod { private const string Tag = "[POGLib]"; private bool _patchesChecked; public override void OnInitializeMelon() { MelonLogger.Msg("[POGLib] Initializing (MelonMod)..."); try { ClassInjector.RegisterTypeInIl2Cpp<ModItemHandle>(); } catch (Exception ex) { MelonLogger.Error("[POGLib] ClassInjector failed: " + ex.Message); } CompatibilityProbe.Check(); CoreServices.Init(); PluginRegistry.Add(new ItemsPlugin()); PluginRegistry.Boot(); HarmonyPatcher.PatchEachClass(typeof(Plugin).Assembly, ((MelonBase)this).HarmonyInstance, "[POGLib]"); MelonLogger.Msg("[POGLib] Boot done. Waiting for scene + session."); } public override void OnSceneWasLoaded(int buildIndex, string sceneName) { if (!_patchesChecked) { _patchesChecked = true; HarmonyPatcher.CheckEachPatchOnce(((MelonBase)this).HarmonyInstance, "[POGLib]"); } PluginRegistry.Dispatch(PluginStage.SceneLoaded); } } } namespace POGLib.Items { public abstract class ItemCapability { public abstract string Name { get; } public abstract void Attach(InventoryItem item); protected static T AddOrGet<T>(GameObject go) where T : Component { T component = go.GetComponent<T>(); if (!((Object)(object)component != (Object)null)) { return go.AddComponent<T>(); } return component; } } public abstract class ItemVisualEffect : ItemCapability { public const string ChildPrefix = "ModEffect_"; protected static GameObject CreateEffectChild(InventoryItem item, string effectName, Vector3 localOffset = default(Vector3)) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown string text = "ModEffect_" + effectName; Transform val = ((Component)item).transform.Find(text); if ((Object)(object)val != (Object)null) { return ((Component)val).gameObject; } GameObject val2 = new GameObject(text); val2.transform.SetParent(((Component)item).transform, false); val2.transform.localPosition = localOffset; return val2; } protected static Transform GetVisualRoot(InventoryItem item) { Transform val = ((Component)item).transform.Find("ModItemVisual"); if (!((Object)(object)val != (Object)null)) { return ((Component)item).transform; } return val; } internal static void RestartEffectsOn(InventoryItem item) { if ((Object)(object)item == (Object)null) { return; } foreach (Transform componentsInChild in ((Component)item).GetComponentsInChildren<Transform>(true)) { if ((Object)(object)componentsInChild == (Object)null || !((Object)componentsInChild).name.StartsWith("ModEffect_")) { continue; } ((Component)componentsInChild).gameObject.SetActive(true); foreach (ParticleSystem componentsInChild2 in ((Component)componentsInChild).GetComponentsInChildren<ParticleSystem>(true)) { if (!((Object)(object)componentsInChild2 == (Object)null)) { ((Component)componentsInChild2).gameObject.SetActive(true); try { componentsInChild2.Play(true); } catch { } } } } } internal static bool HasEffects(GameObject root) { if ((Object)(object)root == (Object)null) { return false; } foreach (Transform componentsInChild in root.GetComponentsInChildren<Transform>(true)) { if ((Object)(object)componentsInChild != (Object)null && ((Object)componentsInChild).name.StartsWith("ModEffect_")) { return true; } } return false; } internal static void SetEffectsVisible(GameObject root, bool visible) { if ((Object)(object)root == (Object)null) { return; } foreach (Transform componentsInChild in root.GetComponentsInChildren<Transform>(true)) { if ((Object)(object)componentsInChild == (Object)null || !((Object)componentsInChild).name.StartsWith("ModEffect_")) { continue; } ((Component)componentsInChild).gameObject.SetActive(visible); if (!visible) { continue; } foreach (ParticleSystem componentsInChild2 in ((Component)componentsInChild).GetComponentsInChildren<ParticleSystem>(true)) { if (!((Object)(object)componentsInChild2 == (Object)null)) { try { componentsInChild2.Play(true); } catch { } } } } } } public sealed class UsableCapability : ItemVisualEffect { public float ReadyDuration; public float FovChange; public bool UseCrosshair; public override string Name => "ActiveItem_ReadyItem (usable)"; public override void Attach(InventoryItem item) { ActiveItem_ReadyItem obj = ItemCapability.AddOrGet<ActiveItem_ReadyItem>(((Component)item).gameObject); ReadyItemFields.Fill(obj, item, null); obj.m_readyItemDuration = ReadyDuration; obj.m_fovChange = FovChange; obj.m_useCrosshair = UseCrosshair; } } internal static class ReadyItemFields { public static void Fill(ActiveItem_ReadyItem ready, InventoryItem item, ActiveItem_ReadyItem donor) { ready.m_inventoryItem = item; ready.m_readyItemDuration = (((Object)(object)donor != (Object)null) ? donor.m_readyItemDuration : 0f); ready.m_readyItemCurve = ((donor != null) ? donor.m_readyItemCurve : null) ?? AnimationCurve.Linear(0f, 0f, 1f, 1f); ready.m_effectTime = (((Object)(object)donor != (Object)null) ? donor.m_effectTime : 0f); ready.m_fovChange = (((Object)(object)donor != (Object)null) ? donor.m_fovChange : 0f); ready.m_fovChangeReadyFactor = (((Object)(object)donor != (Object)null) ? donor.m_fovChangeReadyFactor : 1f); ready.m_useCrosshair = (Object)(object)donor != (Object)null && donor.m_useCrosshair; ready.m_useCrosshairReadyOnly = (Object)(object)donor != (Object)null && donor.m_useCrosshairReadyOnly; ready.m_preventUseIfExhausted = (Object)(object)donor != (Object)null && donor.m_preventUseIfExhausted; if ((Object)(object)ready.m_endPositionTransform == (Object)null) { ready.m_endPositionTransform = EndPoint(item, donor); } } private static Transform EndPoint(InventoryItem item, ActiveItem_ReadyItem donor) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_0074: 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_007f: Unknown result type (might be due to invalid IL or missing references) Transform val = ((donor != null) ? donor.m_endPositionTransform : null); if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)((Component)donor).transform) { return ((Component)item).transform; } GameObject val2 = new GameObject("POG_ReadyEnd"); val2.transform.SetParent(((Component)item).transform, false); val2.transform.localPosition = ((Component)donor).transform.InverseTransformPoint(val.position); val2.transform.localRotation = Quaternion.Inverse(((Component)donor).transform.rotation) * val.rotation; return val2.transform; } } public sealed class EatCapability : ItemCapability { public string CopyFrom; public float? HealthOnEating; public float? DamageOnEating; public float? StaminaRefill; public float? MinStaminaBonus; public float? MaxStaminaBonus; public float? StomachFullTime; public bool? UseStaminaMin; public int? BodyValue; public int? StaminaValue; public int? StrengthValue; public string BuffFrom; public float? BuffValueToAdd; public float? BuffValueToStart; public override string Name => "ActiveItem_Eat"; public override void Attach(InventoryItem item) { ActiveItem_Eat val = ItemCapability.AddOrGet<ActiveItem_Eat>(((Component)item).gameObject); ActiveItem_Eat val2 = null; if (!string.IsNullOrEmpty(CopyFrom)) { val2 = FindVanillaEat(CopyFrom); if ((Object)(object)val2 != (Object)null) { CopySettings(val2, val); } else { MelonLogger.Warning("[POGLib] EatCapability: CopyFrom '" + CopyFrom + "' unavailable; starting empty."); } } ReadyItemFields.Fill((ActiveItem_ReadyItem)(object)val, item, (ActiveItem_ReadyItem)(object)val2); if (HealthOnEating.HasValue) { val.m_healthOnEating = HealthOnEating.Value; } if (DamageOnEating.HasValue) { val.m_damageOnEating = DamageOnEating.Value; } if (StaminaRefill.HasValue) { val.m_staminaRefill = StaminaRefill.Value; } if (MinStaminaBonus.HasValue) { val.m_minStaminaBonus = MinStaminaBonus.Value; } if (MaxStaminaBonus.HasValue) { val.m_maxStaminaBonus = MaxStaminaBonus.Value; } if (StomachFullTime.HasValue) { val.m_stomachFullTime = StomachFullTime.Value; } if (UseStaminaMin.HasValue) { val.m_useStaminaMin = UseStaminaMin.Value; } if (BodyValue.HasValue) { val.m_bodyValue = BodyValue.Value; } if (StaminaValue.HasValue) { val.m_staminaValue = StaminaValue.Value; } if (StrengthValue.HasValue) { val.m_strengthValue = StrengthValue.Value; } if (!string.IsNullOrEmpty(BuffFrom)) { ActiveItem_Eat val3 = FindVanillaEat(BuffFrom); if ((Object)(object)val3 != (Object)null && (Object)(object)val3.m_applyBuff != (Object)null) { val.m_applyBuff = val3.m_applyBuff; val.m_buffValueToAdd = val3.m_buffValueToAdd; val.m_buffValueToStart = val3.m_buffValueToStart; } else { MelonLogger.Warning("[POGLib] EatCapability: BuffFrom '" + BuffFrom + "' has no buff (or is not a loaded food item)."); } } if (BuffValueToAdd.HasValue) { val.m_buffValueToAdd = BuffValueToAdd.Value; } if (BuffValueToStart.HasValue) { val.m_buffValueToStart = BuffValueToStart.Value; } } private static ActiveItem_Eat FindVanillaEat(string prefabName) { InventoryItem val = GameAssets.FindItemPrefab(prefabName); if ((Object)(object)val == (Object)null) { MelonLogger.Warning("[POGLib] EatCapability: no item prefab named '" + prefabName + "' is loaded yet."); return null; } ActiveItem_Eat componentInChildren = ((Component)val).GetComponentInChildren<ActiveItem_Eat>(true); if ((Object)(object)componentInChildren == (Object)null) { MelonLogger.Warning("[POGLib] EatCapability: '" + prefabName + "' is loaded but has no ActiveItem_Eat (not a food item)."); } return componentInChildren; } private static void CopySettings(ActiveItem_Eat from, ActiveItem_Eat to) { to.m_healthOnEating = from.m_healthOnEating; to.m_damageOnEating = from.m_damageOnEating; to.m_staminaRefill = from.m_staminaRefill; to.m_minStaminaBonus = from.m_minStaminaBonus; to.m_maxStaminaBonus = from.m_maxStaminaBonus; to.m_stomachFullTime = from.m_stomachFullTime; to.m_useStaminaMin = from.m_useStaminaMin; to.m_bodyValue = from.m_bodyValue; to.m_staminaValue = from.m_staminaValue; to.m_strengthValue = from.m_strengthValue; to.m_applyBuff = from.m_applyBuff; to.m_buffValueToAdd = from.m_buffValueToAdd; to.m_buffValueToStart = from.m_buffValueToStart; to.m_eatVfx = from.m_eatVfx; } } public sealed class MeleeWeaponCapability : ItemCapability { public int MaxDurability = 100; public int DurabilityLossOnEntityHit = 1; public int DurabilityLossOnDestructibleHit = 1; public float HitCooldown = 0.5f; public override string Name => "ActiveItem_MeleeWeapon"; public override void Attach(InventoryItem item) { ActiveItem_MeleeWeapon obj = ItemCapability.AddOrGet<ActiveItem_MeleeWeapon>(((Component)item).gameObject); obj.m_maxDurability = MaxDurability; obj.m_durabilityLossOnEntityHit = DurabilityLossOnEntityHit; obj.m_durabilityLossOnDestructibleHit = DurabilityLossOnDestructibleHit; obj.m_meleeHitCooldown = HitCooldown; } } public sealed class GlowCapability : ItemVisualEffect { public Color Colour = Color.white; public float Intensity = 2f; public bool CastsLight; public float LightIntensity = 1f; public float LightRange = 4f; public Vector3 LocalOffset = Vector3.zero; public Color? EmissiveColour; public string MaterialFilter; public bool Pulse; public float PulseStrength = 1f; public float PulseDuration = 1f; public int PulseVibrato = 10; public float PulseRandomness; public override string Name { get { if (!CastsLight) { return "Glow (emissive)"; } return "Glow (emissive + Light)"; } } public override void Attach(InventoryItem item) { //IL_0023: 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_0038: 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_00ba: 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) GameObject gameObject = ((Component)item).gameObject; ApplyEmissive(gameObject, (Color)(((??)EmissiveColour) ?? Colour) * Mathf.Max(0f, Intensity), MaterialFilter); if (CastsLight) { Transform val = gameObject.transform.Find("ModGlowLight"); GameObject val2 = (GameObject)(((Object)(object)val != (Object)null) ? ((object)((Component)val).gameObject) : ((object)new GameObject("ModGlowLight"))); if ((Object)(object)val == (Object)null) { val2.transform.SetParent(gameObject.transform, false); val2.transform.localPosition = LocalOffset; } Light val3 = ItemCapability.AddOrGet<Light>(val2); val3.type = (LightType)2; val3.color = Colour; val3.intensity = LightIntensity; val3.range = LightRange; if (Pulse) { LightFlicker obj = ItemCapability.AddOrGet<LightFlicker>(val2); obj.m_light = val3; obj.m_strength = PulseStrength; obj.m_duration = PulseDuration; obj.m_vibrato = PulseVibrato; obj.m_randomness = PulseRandomness; } } } private static void ApplyEmissive(GameObject root, Color colour, string materialFilter) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00b0: 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) bool flag = !string.IsNullOrEmpty(materialFilter); int num = 0; foreach (MeshRenderer componentsInChild in root.GetComponentsInChildren<MeshRenderer>(true)) { if ((Object)(object)componentsInChild == (Object)null || ((Object)((Component)componentsInChild).gameObject).name.Contains("Outline")) { continue; } Il2CppReferenceArray<Material> materials = ((Renderer)componentsInChild).materials; for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)materials).Length; i++) { if ((Object)(object)((Il2CppArrayBase<Material>)(object)materials)[i] == (Object)null || (flag && ((Object)((Il2CppArrayBase<Material>)(object)materials)[i]).name.IndexOf(materialFilter, StringComparison.OrdinalIgnoreCase) < 0)) { continue; } num++; Material val = new Material(((Il2CppArrayBase<Material>)(object)materials)[i]); if (val.HasProperty("_EmissiveColor")) { val.SetColor("_EmissiveColor", colour); } else { if (!val.HasProperty("_EmissionColor")) { continue; } val.SetColor("_EmissionColor", colour); val.EnableKeyword("_EMISSION"); } ((Il2CppArrayBase<Material>)(object)materials)[i] = val; } ((Renderer)componentsInChild).materials = materials; } if (flag && num == 0) { MelonLogger.Warning($"[POGLib] GlowCapability: no material matched '{materialFilter}' on {((Object)root).name}: nothing glows. Check the material name in the model file."); } } } public sealed class ParticleEffect : ItemVisualEffect { public string EffectId = "Particles"; public string SourcePrefabName; public string SourceChildName; internal string BundlePath; internal string BundleAssetName; public Vector3 LocalOffset = Vector3.zero; public Vector3 LocalEuler = Vector3.zero; public float Scale = 1f; public bool FollowVisualMesh; public Color? Tint; public bool PlayOnAttach = true; public override string Name => "Particles(" + EffectId + ")"; public static ParticleEffect FromGameObject(string effectId, string sourcePrefabName, string sourceChildName) { return new ParticleEffect { EffectId = effectId, SourcePrefabName = sourcePrefabName, SourceChildName = sourceChildName }; } internal static ParticleEffect FromBundle(string effectId, string bundlePath, string assetName) { return new ParticleEffect { EffectId = effectId, BundlePath = bundlePath, BundleAssetName = assetName }; } public ParticleEffect At(Vector3 offset, Vector3 euler = default(Vector3), float scale = 1f) { //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_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) LocalOffset = offset; LocalEuler = euler; Scale = scale; return this; } public ParticleEffect Coloured(Color colour) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Tint = colour; return this; } public override void Attach(InventoryItem item) { //IL_00ae: 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_0136: 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) //IL_017d: Unknown result type (might be due to invalid IL or missing references) GameObject val = ResolveSource(); if ((Object)(object)val == (Object)null) { MelonLogger.Warning($"[POGLib] ParticleEffect '{EffectId}': no source found (prefab='{SourcePrefabName}' child='{SourceChildName}' bundle='{BundlePath}')."); return; } GameObject val2 = ItemVisualEffect.CreateEffectChild(item, EffectId, LocalOffset); if (FollowVisualMesh) { val2.transform.SetParent(ItemVisualEffect.GetVisualRoot(item), false); } for (int num = val2.transform.childCount - 1; num >= 0; num--) { Object.Destroy((Object)(object)((Component)val2.transform.GetChild(num)).gameObject); } GameObject val3 = Object.Instantiate<GameObject>(val, val2.transform); ((Object)val3).name = EffectId; val3.transform.localPosition = Vector3.zero; val3.transform.localEulerAngles = LocalEuler; val3.transform.localScale = new Vector3(Scale, Scale, Scale); val3.SetActive(true); if (Tint.HasValue) { TintRenderers(val3, Tint.Value); } if (!PlayOnAttach) { return; } foreach (ParticleSystem componentsInChild in val3.GetComponentsInChildren<ParticleSystem>(true)) { if (!((Object)(object)componentsInChild == (Object)null)) { ((Component)componentsInChild).gameObject.SetActive(true); try { componentsInChild.Play(true); } catch { } } } } private GameObject ResolveSource() { if (!string.IsNullOrEmpty(BundlePath) && !string.IsNullOrEmpty(BundleAssetName)) { AssetBundle val = CoreServices.Assets.LoadBundle(BundlePath); if (!((Object)(object)val != (Object)null)) { return null; } return CoreServices.Assets.LoadAsset<GameObject>(val, BundleAssetName); } if (string.IsNullOrEmpty(SourcePrefabName) || string.IsNullOrEmpty(SourceChildName)) { return null; } InventoryItem val2 = GameAssets.FindItemPrefab(SourcePrefabName); GameObject val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).gameObject : GameAssets.FindGameObject(SourcePrefabName)); if ((Object)(object)val3 == (Object)null) { return null; } foreach (Transform componentsInChild in val3.GetComponentsInChildren<Transform>(true)) { if ((Object)(object)componentsInChild != (Object)null && ((Object)componentsInChild).name.Contains(SourceChildName)) { return ((Component)componentsInChild).gameObject; } } return null; } private static void TintRenderers(GameObject root, Color colour) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0062: 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_009a: Unknown result type (might be due to invalid IL or missing references) foreach (Renderer componentsInChild in root.GetComponentsInChildren<Renderer>(true)) { if ((Object)(object)componentsInChild == (Object)null) { continue; } Il2CppReferenceArray<Material> materials = componentsInChild.materials; for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)materials).Length; i++) { if (!((Object)(object)((Il2CppArrayBase<Material>)(object)materials)[i] == (Object)null)) { Material val = new Material(((Il2CppArrayBase<Material>)(object)materials)[i]); if (val.HasProperty("_BaseColor")) { val.SetColor("_BaseColor", colour); } else if (val.HasProperty("_Color")) { val.SetColor("_Color", colour); } if (val.HasProperty("_EmissiveColor")) { val.SetColor("_EmissiveColor", colour); } ((Il2CppArrayBase<Material>)(object)materials)[i] = val; } } componentsInChild.materials = materials; } } } public sealed class ThrowableCapability : ItemCapability { public int HealthMax = 1; public int HealthMin = 1; public float BounceFactor; public override string Name => "ActiveItem_Throwable"; public override void Attach(InventoryItem item) { ActiveItem_Throwable obj = ItemCapability.AddOrGet<ActiveItem_Throwable>(((Component)item).gameObject); obj.m_healthMax = HealthMax; obj.m_healthMin = HealthMin; obj.m_bounceFactor = BounceFactor; } } [HarmonyPatch(typeof(InventoryItem), "OnNetworkSpawn")] internal static class Patch_Item_OnNetworkSpawn { private static void Postfix(InventoryItem __instance) { if ((Object)(object)__instance == (Object)null) { return; } ItemsPlugin instance = ItemsPlugin.Instance; if (instance != null && instance.IsModItem(__instance)) { TemplateCopies.Release(((Component)__instance).gameObject); if ((Object)(object)((Component)__instance).GetComponent<ModItemHandle>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<ModItemHandle>(); } ItemVisualEffect.RestartEffectsOn(__instance); } } } [HarmonyPatch(typeof(InventoryItem), "StartPrimaryAction")] internal static class Patch_Item_StartPrimaryAction { private static void Postfix(InventoryItem __instance) { if (!((Object)(object)__instance == (Object)null)) { ItemsPlugin instance = ItemsPlugin.Instance; if (instance != null && instance.IsModItem(__instance)) { instance.TryUseItem(__instance, __instance.Entity); } } } } [HarmonyPatch(typeof(NetworkHandler), "GetNetworkPrefab")] internal static class Patch_NetworkHandler_GetNetworkPrefab { private static readonly HashSet<uint> _logged = new HashSet<uint>(); private static void Postfix(uint prefabIdHash, ref NetworkObject __result) { try { if ((Object)(object)__result != (Object)null) { return; } NetworkObject val = CoreServices.Content?.GetPrefabByHash(prefabIdHash); if (!((Object)(object)val == (Object)null)) { __result = val; if (_logged.Add(prefabIdHash)) { MelonLogger.Msg($"[POGLib] The game asked for network prefab {prefabIdHash:X8} (a copy of a mod item); answered with {((Object)val).name}."); } } } catch (Exception ex) { MelonLogger.Warning($"[POGLib] GetNetworkPrefab({prefabIdHash:X8}): {ex.GetType().Name}: {ex.Message}"); } } } public sealed class ItemsApi { internal ItemsPlugin Plugin; internal ItemsApi() { } private bool Guard() { if (Plugin != null) { return true; } MelonLogger.Error("[POGLib] Content.Items used before POGLib booted."); return false; } [MethodImpl(MethodImplOptions.NoInlining)] public void Register(ModItemDefinition definition) { RegisterFrom(definition, Assembly.GetCallingAssembly()); } private void RegisterFrom(ModItemDefinition definition, Assembly caller) { ContentOwners.Note(definition?.ModId, caller); if (Guard()) { Plugin.RegisterItem(definition); } } public void RegisterUseHandler(string handlerId, ModItemUseHandler handler) { if (Guard()) { Plugin.RegisterUseHandler(handlerId, handler); } } [MethodImpl(MethodImplOptions.NoInlining)] public void Register(ModItemDefinition definition, string handlerId, ModItemUseHandler handler) { RegisterFrom(definition, Assembly.GetCallingAssembly()); RegisterUseHandler(handlerId, handler); } } public static class Content { public static ItemsApi Items { get; } = new ItemsApi(); public static IReadOnlyCollection<string> ContentAssemblies => ContentOwners.Assemblies; internal static DiagnosticsApi Diagnostics { get; } = new DiagnosticsApi(); } public enum ItemShellKind { Diamond, Coin, Gem, BigItem } public sealed class UseContext { public bool IsHost { get; internal set; } public HostBridge Bridge { get; internal set; } internal UseContext() { } } public delegate bool ModItemUseHandler(InventoryItem item, Entity owner, UseContext ctx); internal sealed class ItemsPlugin : IPOGPlugin { private readonly Dictionary<string, ModItemUseHandler> _handlers = new Dictionary<string, ModItemUseHandler>(); private readonly List<ModItemDefinition> _defs = new List<ModItemDefinition>(); private readonly HashSet<string> _built = new HashSet<string>(); private readonly Dictionary<string, Sprite> _icons = new Dictionary<string, Sprite>(); public string Name => "Items"; public string Version => "0.1.0"; internal static ItemsPlugin Instance { get; private set; } internal IReadOnlyList<ModItemDefinition> Definitions => _defs; public bool IsRegistered(string fullId) { foreach (ModItemDefinition def in _defs) { if (ContentRegistry.FullId(def.ModId, def.ContentId) == fullId) { return true; } } return false; } public bool IsBuilt(string fullId) { return _built.Contains(fullId); } internal static string NameKeyOf(ModItemDefinition def) { if (string.IsNullOrEmpty(def.TooltipKey)) { return "MOD/" + def.ModId + "/" + def.ContentId; } return def.TooltipKey; } internal static string DescriptionKeyOf(ModItemDefinition def) { if (string.IsNullOrEmpty(def.TooltipDescriptionKey)) { return $"MOD/{def.ModId}/{def.ContentId}_Desc"; } return def.TooltipDescriptionKey; } internal static ItemGroup JournalGroupOf(ModItemDefinition def) { //IL_0020: 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_0019: 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) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (def.JournalGroup.HasValue) { return def.JournalGroup.Value; } if ((def.ItemType & 1) == 0) { if ((def.ItemType & 2) == 0) { return (ItemGroup)8; } return (ItemGroup)2; } return (ItemGroup)1; } internal Sprite IconFor(ModItemDefinition def) { string key = ContentRegistry.FullId(def.ModId, def.ContentId); if (_icons.TryGetValue(key, out var value) && (Object)(object)value != (Object)null) { return value; } Sprite val = null; if ((Object)(object)def.Icon != (Object)null) { val = def.Icon; } else if (!string.IsNullOrEmpty(def.IconSpriteName)) { val = GameAssets.FindSprite(def.IconSpriteName); } else if (!string.IsNullOrEmpty(def.IconFile)) { try { val = AssetLoader.LoadPngAsSprite(def.IconFile); } catch (Exception ex) { MelonLogger.Warning($"[POGLib.Items] {def.ContentId}: icon file '{def.IconFile}': {ex.Message}"); } if ((Object)(object)val != (Object)null) { MelonLogger.Msg($"[POGLib.Items] {def.ContentId}: icon from '{Path.GetFileName(def.IconFile)}' ({((Texture)val.texture).width}x{((Texture)val.texture).height})."); } } if ((Object)(object)val != (Object)null) { _icons[key] = val; } return val; } internal static ModItemDefinition ResolveDefinition(uint hash) { return CoreServices.Content.GetDefinitionByHash(hash) as ModItemDefinition; } public void RegisterUseHandler(string handlerId, ModItemUseHandler handler) { if (!string.IsNullOrEmpty(handlerId) && handler != null) { _handlers[handlerId] = handler; MelonLogger.Msg("[POGLib.Items] Use handler: " + handlerId); } } public void RegisterItem(ModItemDefinition def) { if (def == null || string.IsNullOrEmpty(def.ModId) || string.IsNullOrEmpty(def.ContentId)) { MelonLogger.Error("[POGLib.Items] Invalid ModItemDefinition."); } else if (CoreServices.Content.RegisterDefinition(def)) { _defs.Add(def); TryBuild(def); } } public void Build(PluginGraph graph) { Instance = this; Content.Items.Plugin = this; graph.AddSystem(PluginStage.SceneLoaded, Name, delegate { BuildPending(); NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null && singleton.IsServer) { CoreServices.Loot.InjectIntoLoadedTables(); } }); graph.AddSystem(PluginStage.GamePrefabsLoaded, Name, BuildPending); } private void BuildPending() { foreach (ModItemDefinition def in _defs) { TryBuild(def); } LinkConsumeSpawns(); Content.Diagnostics.RetryPending(); } private void TryBuild(ModItemDefinition def) { string item = ContentRegistry.FullId(def.ModId, def.ContentId); if (_built.Contains(item)) { return; } ItemShellKind itemShellKind = def.ShellKind; if (def.Big && itemShellKind == ItemShellKind.Diamond) { itemShellKind = ItemShellKind.BigItem; } InventoryItem val = CoreServices.Shells.BuildItemTemplate(itemShellKind, def.ModId, def.ContentId); if (!((Object)(object)val == (Object)null)) { ApplyIdentity(val, def); ApplyVisual(val, def); ApplyCapabilities(val, def); StandingPoints.Ensure(val, def.StandingPoint, def.StandingRotation); ((Component)val).gameObject.AddComponent<ModItemHandle>(); if (def.Loot != null) { CoreServices.Loot.AddRequest(val, def.Loot.Category, def.Loot.TableNames, def.Loot.Weight); } _built.Add(item); } } private static void ApplyIdentity(InventoryItem item, ModItemDefinition def) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) item.m_itemID = ContentRegistry.FullId(def.ModId, def.ContentId); item.m_itemType = def.ItemType; item.m_mapIconType = def.MapIcon; item.m_goldValue = def.GoldValue; item.m_foodValue = def.FoodValue; item.m_shopCost = def.ShopCost; item.m_doConsume = def.Consumable; item.m_isConsumed = false; item.m_spawnAmount = 0; item.m_spawnChance = 0f; item.m_isBigItem = def.Big; item.m_staminaPenaltyOnPickup = def.PickupStaminaPenalty; item.m_movementFactorWhenHeld = def.MovementFactorWhenHeld; Sprite val = Instance?.IconFor(def); if ((Object)(object)val != (Object)null) { item.m_itemIcon = val; } else { ItemVisual visual = def.Visual; if (visual != null && visual.Kind == ItemVisualKind.ObjFile) { MelonLogger.Warning("[POGLib.Items] " + def.ContentId + ": a model of its own but no icon (Icon, IconSpriteName or IconFile): it shows the shell's icon."); } } item.m_journalGroup = JournalGroupOf(def); item.m_showInJournal = def.ShowInJournal; string text = NameKeyOf(def); string text2 = DescriptionKeyOf(def); ModLocalization.Register(text, string.IsNullOrEmpty(def.DisplayName) ? def.ContentId : def.DisplayName); ((NetworkInteractableBase)item).m_itemTooltipID = text; if (!string.IsNullOrEmpty(def.DisplayDescription)) { ModLocalization.Register(text2, def.DisplayDescription); } ((NetworkInteractableBase)item).m_itemTooltipDescriptionID = text2; } private static void ApplyCapabilities(InventoryItem item, ModItemDefinition def) { if (!string.IsNullOrEmpty(def.UseHandlerId) && !HasUsableComponent(def)) { try { new UsableCapability().Attach(item); MelonLogger.Msg("[POGLib.Items] " + def.ContentId + ": made usable (ActiveItem_ReadyItem added)."); } catch (Exception ex) { MelonLogger.Warning("[POGLib.Items] " + def.ContentId + ": could not make usable: " + ex.Message); } } if (def.Capabilities == null || def.Capabilities.Count == 0) { return; } foreach (ItemCapability capability in def.Capabilities) { if (capability != null) { try { capability.Attach(item); MelonLogger.Msg($"[POGLib.Items] Capability '{capability.Name}' attached to {def.ContentId} (EXPERIMENTAL)."); } catch (Exception ex2) { MelonLogger.Warning($"[POGLib.Items] Capability '{capability.Name}' failed on {def.ContentId}: {ex2.Message}"); } } } } private void LinkConsumeSpawns() { foreach (ModItemDefinition def in _defs) { if (string.IsNullOrEmpty(def.SpawnOnConsume)) { continue; } InventoryItem val = ResolveTemplate(def.ModId, def.ContentId); if (!((Object)(object)val == (Object)null) && !((Object)(object)val.m_spawnOnDestroy != (Object)null)) { string text = def.ModId; string text2 = def.SpawnOnConsume; int num = def.SpawnOnConsume.IndexOf(':'); if (num > 0) { text = def.SpawnOnConsume.Substring(0, num); text2 = def.SpawnOnConsume.Substring(num + 1); } uint hash = ContentRegistry.ComputeHash(text, text2); NetworkObject prefabByHash = CoreServices.Content.GetPrefabByHash(hash); if (!((Object)(object)prefabByHash == (Object)null)) { val.m_spawnOnDestroy = prefabByHash; val.m_spawnAmount = 1; val.m_spawnChance = 1f; MelonLogger.Msg($"[POGLib.Items] {def.ContentId} leaves behind {text}:{text2} when used up."); } } } } private static InventoryItem ResolveTemplate(string modId, string contentId) { NetworkObject prefabByHash = CoreServices.Content.GetPrefabByHash(ContentRegistry.ComputeHash(modId, contentId)); if (!((Object)(object)prefabByHash != (Object)null)) { return null; } return ((Component)prefabByHash).GetComponent<InventoryItem>(); } private static bool HasUsableComponent(ModItemDefinition def) { if (def.Capabilities == null) { return false; } foreach (ItemCapability capability in def.Capabilities) { if (capability is UsableCapability || capability is EatCapability || capability is MeleeWeaponCapability || capability is ThrowableCapability) { return true; } } return false; } private static void ApplyVisual(InventoryItem item, ModItemDefinition def) { //IL_0158: Unknown result type (might be due to invalid IL or missing references) GameObject gameObject = ((Component)item).gameObject; try { if (def.Visual != null) { switch (def.Visual.Kind) { case ItemVisualKind.GameMesh: { InventoryItem val2 = GameAssets.FindItemPrefab(def.Visual.SourcePrefabName); if ((Object)(object)val2 != (Object)null) { ItemVisuals.ReplaceMeshes(gameObject, ((Component)val2).gameObject, def.Visual.ChildName); if (def.Visual.StripSpeakingStone) { ItemVisuals.StripVoiceComponents(gameObject); ItemVisuals.HideSpeakingStoneVfx(gameObject); } } else { MelonLogger.Warning("[POGLib.Items] Visual source not found: " + def.Visual.SourcePrefabName); } break; } case ItemVisualKind.ObjFile: { ObjMesh.Model model = ObjMesh.Load(def.Visual.Path); if (model != null) { ItemVisuals.ReplaceMeshes(gameObject, model.Mesh, model.Materials); ItemVisuals.ApplyColliders(gameObject, model.CollisionMeshes, model.Mesh); } else { MelonLogger.Warning("[POGLib.Items] " + def.ContentId + ": OBJ visual failed, keeping the shell mesh."); } break; } case ItemVisualKind.Png: if ((Object)(object)def.Icon == (Object)null) { Sprite val = AssetLoader.LoadPngAsSprite(def.Visual.Path); if ((Object)(object)val != (Object)null) { item.m_itemIcon = val; } } break; case ItemVisualKind.BundlePrefab: ApplyBundleVisual(item, def); break; } } if (def.Tint.HasValue) { ItemVisuals.ApplyTint(gameObject, def.Tint.Value, def.Visual?.ChildName); } } catch (Exception ex) { MelonLogger.Warning("[POGLib.Items] Visual failed for " + def.ContentId + ": " + ex.Message); } } private static void ApplyBundleVisual(InventoryItem item, ModItemDefinition def) { //IL_00cf: 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_00db: Unknown result type (might be due to invalid IL or missing references) ItemVisual visual = def.Visual; if (string.IsNullOrEmpty(visual.Path) || string.IsNullOrEmpty(visual.AssetName)) { MelonLogger.Warning("[POGLib.Items] Bundle visual for " + def.ContentId + " needs both a bundle path and an asset name."); return; } AssetBundle val = CoreServices.Assets.LoadBundle(visual.Path); if ((Object)(object)val == (Object)null) { return; } GameObject val2 = CoreServices.Assets.LoadAsset<GameObject>(val, visual.AssetName); if ((Object)(object)val2 == (Object)null) { MelonLogger.Error($"[POGLib.Items] Asset '{visual.AssetName}' not found in bundle '{visual.Path}'."); return; } GameObject val3 = ItemVisuals.AttachBundlePrefab(((Component)item).gameObject, val2, visual.LocalOffset, visual.LocalEuler, visual.LocalScale); if (!((Object)(object)val3 == (Object)null)) { if (visual.RepairShaders) { ItemVisuals.RepairBundleShaders(val3); } MelonLogger.Msg($"[POGLib.Items] Custom mesh '{visual.AssetName}' applied to {def.ContentId} (EXPERIMENTAL)."); } } public void TryUseItem(InventoryItem item, Entity owner) { if ((Object)(object)item == (Object)null || (Object)(object)owner == (Object)null) { return; } NetworkObject component = ((Component)item).GetComponent<NetworkObject>(); if ((Object)(object)component == (Object)null) { return; } ModItemDefinition modItemDefinition = ResolveDefinition(component.GlobalObjectIdHash); if (modItemDefinition == null) { return; } ModItemHandle component2 = ((Component)item).GetComponent<ModItemHandle>(); if ((Object)(object)component2 != (Object)null && component2.IsConsumed) { MelonLogger.Msg("[POGLib.Items] " + modItemDefinition.ContentId + ": already consumed."); return; } if (string.IsNullOrEmpty(modItemDefinition.UseHandlerId)) { MelonLogger.Msg("[POGLib.Items] " + modItemDefinition.ContentId + ": no UseHandlerId set — nothing to run."); return; } if (!_handlers.TryGetValue(modItemDefinition.UseHandlerId, out var value)) { MelonLogger.Warning($"[POGLib.Items] {modItemDefinition.ContentId}: use handler '{modItemDefinition.UseHandlerId}' is not registered."); return; } NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton != (Object)null) || !singleton.IsServer) { MelonLogger.Msg("[POGLib.Items] Use on client deferred (HostBridge RPC is a v2 feature)."); return; } UseContext ctx = new UseContext { IsHost = true, Bridge = CoreServices.Bridge }; if (!value(item, owner, ctx)) { MelonLogger.Msg("[POGLib.Items] " + modItemDefinition.ContentId + ": handler declined; use not spent."); } else { if (!((Object)(object)component2 != (Object)null)) { return; } component2.UsesRemaining--; MelonLogger.Msg($"[POGLib.Items] {modItemDefinition.ContentId}: used, {component2.UsesRemaining} use(s) left."); if (component2.UsesRemaining <= 0 && modItemDefinition.Consumable) { component2.IsConsumed = true; try { item.ConsumeItem_Owner(); return; } catch (Exception ex) { MelonLogger.Warning("[POGLib.Items] Consume failed: " + ex.Message); return; } } try { item.EndPrimaryAction(); } catch (Exception ex2) { MelonLogger.Warning("[POGLib.Items] EndPrimaryAction failed: " + ex2.Message); } } } public bool IsModItem(InventoryItem item) { if ((Object)(object)item == (Object)null) { return false; } NetworkObject component = ((Component)item).GetComponent<NetworkObject>(); if ((Object)(object)component != (Object)null) { return CoreServices.Content.GetDefinitionByHash(component.GlobalObjectIdHash) != null; } return false; } } [HarmonyPatch(typeof(UI_JournalGroupItems), "Initialize")] internal static class Patch_UI_JournalGroupItems_Initialize { private static void Prefix(UI_JournalGroupItems __instance) { try { JournalEntries.AddModEntries(__instance); } catch (Exception ex) { MelonLogger.Warning("[POGLib.Items] Journal entries: " + ex.GetType().Name + ": " + ex.Message); } } } internal static class JournalEntries { public const string EntryNamePrefix = "ModJournalEntry|"; public static void AddModEntries(UI_JournalGroupItems tab) { //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_020b: 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_0220: 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_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0240: 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_025d: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Expected O, but got Unknown //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) ItemsPlugin instance = ItemsPlugin.Instance; if ((Object)(object)tab == (Object)null || instance == null || tab.m_entries == null) { return; } List<UI_JournalEntryItem> entries = tab.m_entries; UI_JournalEntryItem val = null; int num = entries.Count - 1; while (num >= 0 && (Object)(object)val == (Object)null) { val = entries[num]; num--; } if ((Object)(object)val == (Object)null) { val = tab.m_entryPrefab; } if ((Object)(object)val == (Object)null) { return; } Transform val2 = ((entries.Count > 0 && (Object)(object)entries[entries.Count - 1] != (Object)null) ? ((Component)entries[entries.Count - 1]).transform.parent : ((Component)tab).transform); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); for (int i = 0; i < entries.Count; i++) { JournalEntryDataItem val3 = (((Object)(object)entries[i] != (Object)null) ? entries[i].m_entryData : null); if (val3 != null && !string.IsNullOrEmpty(val3.Name)) { hashSet.Add(val3.Name); } } int num2 = 0; foreach (ModItemDefinition definition in instance.Definitions) { if (definition == null || !definition.ShowInJournal || ItemsPlugin.JournalGroupOf(definition) != tab.m_itemGroup) { continue; } string text = ItemsPlugin.NameKeyOf(definition); if (hashSet.Contains(text)) { continue; } GameObject val4 = Object.Instantiate<GameObject>(((Component)val).gameObject, val2); ((Object)val4).name = "ModJournalEntry|" + ContentRegistryId(definition); UI_JournalEntryItem component = val4.GetComponent<UI_JournalEntryItem>(); if ((Object)(object)component == (Object)null) { Object.Destroy((Object)(object)val4); continue; } Sprite val5 = instance.IconFor(definition); bool flag = false; if ((Object)(object)val5 == (Object)null) { val5 = TemplateIcon(definition); flag = (Object)(object)val5 != (Object)null; } RarityObject val6 = null; bool flag2 = false; try { if ((Object)(object)tab.m_rarityData != (Object)null) { val6 = tab.m_rarityData.GetRarityData((ItemRarity)0); flag2 = true; } } catch { } JournalEntryDataItem val7 = new JournalEntryDataItem { Icon = val5, Name = text, Description = ItemsPlugin.DescriptionKeyOf(definition), Rarity = (ItemRarity)0, ItemGroup = tab.m_itemGroup, FoodValue = definition.FoodValue, CoinValue = definition.GoldValue, ShowFoodValue = (definition.FoodValue > 0), ShowCoinValue = (definition.GoldValue > 0) }; if (flag2) { val7.RarityColor = val6.PrimaryColor; val7.RarityIcon = val6.Sprite; } component.m_entryData = val7; if ((Object)(object)component.m_entryImage != (Object)null && (Object)(object)val5 != (Object)null) { component.m_entryImage.sprite = val5; } if ((Object)(object)component.m_rarityIcon != (Object)null && flag2 && (Object)(object)val6.Sprite != (Object)null) { component.m_rarityIcon.sprite = val6.Sprite; } entries.Add(component); hashSet.Add(text); num2++; MelonLogger.Msg($"[POGLib.Items] Journal: {definition.ContentId} listed under {tab.m_itemGroup} (shows once discovered; icon {(((Object)(object)val5 == (Object)null) ? "none" : (flag ? "the shell's" : "its own"))})."); } if (num2 > 0) { MelonLogger.Msg($"[POGLib.Items] Journal tab {tab.m_itemGroup}: {num2} mod item(s) added to its {entries.Count} entries."); } } private static Sprite TemplateIcon(ModItemDefinition def) { ContentRegistry content = CoreServices.Content; if (content == null) { return null; } foreach (NetworkObject allPrefab in content.AllPrefabs) { if ((Object)(object)allPrefab != (Object)null && content.GetDefinitionByHash(allPrefab.GlobalObjectIdHash) == def) { InventoryItem component = ((Component)allPrefab).GetComponent<InventoryItem>(); return (component != null) ? component.m_itemIcon : null; } } return null; } private static string ContentRegistryId(ModItemDefinition def) { return ContentRegistry.FullId(def.ModId, def.ContentId); } } internal enum ItemVisualKind { None, GameMesh, ObjFile, Png, BundlePrefab } public sealed class ItemVisual { internal ItemVisualKind Kind; internal string Path; internal string AssetName; internal string SourcePrefabName; internal string ChildName; internal bool StripSpeakingStone = true; internal Vector3 LocalOffset = Vector3.zero; internal Vector3 LocalEuler = Vector3.zero; internal Vector3 LocalScale = Vector3.one; internal bool RepairShaders = true; internal ItemVisual() { }//IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: 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) public static ItemVisual GameMesh(string sourcePrefabName, string childName) { return new ItemVisual { Kind = ItemVisualKind.GameMesh, SourcePrefabName = sourcePrefabName, ChildName = childName }; } public static ItemVisual Obj(string objPath) { return new ItemVisual { Kind = ItemVisualKind.ObjFile, Path = objPath }; } internal static ItemVisual Png(string path) { return new ItemVisual { Kind = ItemVisualKind.Png, Path = path }; } internal static ItemVisual Bundle(string bundlePath, string assetName) { return new ItemVisual { Kind = ItemVisualKind.BundlePrefab, Path = bundlePath, AssetName = assetName }; } internal ItemVisual At(Vector3 offset, Vector3 euler = default(Vector3), float scale = 1f) { //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_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_0012: 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) LocalOffset = offset; LocalEuler = euler; LocalScale = new Vector3(scale, scale, scale); return this; } } internal enum LootCategory { Treasure, Food, Useful, Big, Shop } internal sealed class LootPlacement { public LootCategory? Category; public string[] TableNames; public int Weight = 1; public static LootPlacement In(LootCategory category) { return new LootPlacement { Category = category }; } public static LootPlacement InTables(params string[] names) { return new LootPlacement { TableNames = names }; } public LootPlacement RestrictTo(params string[] names) { TableNames = names; return this; } public LootPlacement WithWeight(int w) { Weight = w; return this; } } public sealed class ModItemDefinition : IContentDefinition { public string ModId { get; set; } public string ContentId { get; set; } public ItemShellKind ShellKind { get; set; } public ItemVisual Visual { get; set; } public Sprite Icon { get; set; } public string IconSpriteName { get; set; } public string IconFile { get; set; } public Color? Tint { get; set; } public string DisplayName { get; set; } public string DisplayDescription { get; set; } public string TooltipKey { get; set; } public string TooltipDescriptionKey { get; set; } public ItemType ItemType { get; set; } = (ItemType)4; public MapIconType MapIcon { get; set; } public ItemGroup? JournalGroup { get; set; } public bool ShowInJournal { get; set; } = true; public int GoldValue { get; set; } = 50; public int FoodValue { get; set; } public int ShopCost { get; set; } public bool Big { get; set; } public float PickupStaminaPenalty { get; set; } public float MovementFactorWhenHeld { get; set; } = 1f; public bool Consumable { get; set; } = true; public int MaxUses { get; set; } = 1; public string UseHandlerId { get; set; } public string SpawnOnConsume { get; set; } public List<ItemCapability> Capabilities { get; } = new List<ItemCapability>(); internal LootPlacement Loot { get; set; } public Vector3? StandingPoint { get; set; } public Vector3? StandingRotation { get; set; } } public class ModItemHandle : MonoBehaviour { private bool _init; private int _usesRemaining; private bool _consumed; private InventoryItem _item; private bool _effectsShown = true; private bool _effectsChecked; private bool _hasEffects; internal uint Hash { get; private set; } internal int UsesRemaining { get { EnsureInit(); return _usesRemaining; } set { EnsureInit(); _usesRemaining = value; } } internal bool IsConsumed { get { EnsureInit(); return _consumed; } set { EnsureInit(); _consumed = value; } } public ModItemHandle(IntPtr ptr) : base(ptr) { } private void EnsureInit() { if (!_init) { _init = true; NetworkObject component = ((Component)this).GetComponent<NetworkObject>(); Hash = (((Object)(object)component != (Object)null) ? component.GlobalObjectIdHash : 0u); _usesRemaining = ItemsPlugin.ResolveDefinition(Hash)?.MaxUses ?? 1; _consumed = false; } } private void Update() { if (!_effectsChecked) { _effectsChecked = true; _item = ((Component)this).GetComponent<InventoryItem>(); _hasEffects = ItemVisualEffect.HasEffects(((Component)this).gameObject); } if (_hasEffects && !((Object)(object)_item == (Object)null)) { bool flag; try { flag = _item.IsVisible && !_item.IsInInventory; } catch { return; } if (flag != _effectsShown) { _effectsShown = flag; ItemVisualEffect.SetEffectsVisible(((Component)this).gameObject, flag); } } } } internal static class StandingPoints { public const string ChildName = "ModStandingPoint"; public static Transform Ensure(InventoryItem item, Vector3? localPos = null, Vector3? localEuler = null) { //IL_0048: 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_007f: 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) //IL_00be: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)item == (Object)null) { return null; } Transform val = item.m_standingTransform; if ((Object)(object)val == (Object)null || !val.IsChildOf(((Component)item).transform)) { Transform val2 = ((Component)item).transform.Find("ModStandingPoint"); GameObject val3 = (GameObject)(((Object)(object)val2 != (Object)null) ? ((object)((Component)val2).gameObject) : ((object)new GameObject("ModStandingPoint"))); val3.transform.SetParent(((Component)item).transform, false); val3.transform.localPosition = BottomCentre(item); val3.transform.localRotation = Quaternion.identity; item.m_standingTransform = val3.transform; val = val3.transform; } if (localPos.HasValue) { val.localPosition = localPos.Value; } if (localEuler.HasValue) { val.localEulerAngles = localEuler.Value; } return val; } public static Vector3 BottomCentre(InventoryItem item) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_007a: 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_0083: 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_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0178: 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_0158: 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_009e: Unknown result type (might be due to invalid IL or missing references) //IL_0095: 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_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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_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_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: 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_00f4: 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_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) bool flag = false; Bounds val = default(Bounds); Transform transform = ((Component)item).transform; foreach (MeshFilter componentsInChild in ((Component)item).GetComponentsInChildren<MeshFilter>(true)) { if ((Object)(object)componentsInChild == (Object)null || (Object)(object)componentsInChild.sharedMesh == (Object)null || ((Object)((Component)componentsInChild).gameObject).name.Contains("Outline")) { continue; } Bounds bounds = componentsInChild.sharedMesh.bounds; Vector3 center = ((Bounds)(ref bounds)).center; Vector3 extents = ((Bounds)(ref bounds)).extents; for (int i = 0; i < 8; i++) { Vector3 val2 = center + new Vector3(((i & 1) == 0) ? (0f - extents.x) : extents.x, ((i & 2) == 0) ? (0f - extents.y) : extents.y, ((i & 4) == 0) ? (0f - extents.z) : extents.z); Vector3 val3 = transform.InverseTransformPoint(((Component)componentsInChild).transform.TransformPoint(val2)); if (!flag) { val = new Bounds(val3, Vector3.zero); flag = true; } else { ((Bounds)(ref val)).Encapsulate(val3); } } } if (!flag) { MelonLogger.Warning("[POGLib] " + ((Object)item).name + ": no mesh to find a standing point from; using the pivot."); } if (!flag) { return Vector3.zero; } return new Vector3(((Bounds)(ref val)).center.x, ((Bounds)(ref val)).min.y, ((Bounds)(ref val)).center.z); } } } namespace POGLib.Core { internal static class Addresses { public static string AddressOf(string key) { if (string.IsNullOrEmpty(key)) { return null; } AsyncOperationHandle<IList<IResourceLocation>> val = Addressables.LoadResourceLocationsAsync((Object)(object)String.op_Implicit(key), (Type)null); try { IList<IResourceLocation> val2 = val.WaitForCompletion(); return (Count(val2) > 0) ? val2[0].PrimaryKey : null; } finally { Addressables.Release<IList<IResourceLocation>>(val); } } public static string NameOf(string address) { if (string.IsNullOrEmpty(address)) { return null; } int num = address.LastIndexOf('/'); string text = ((num >= 0) ? address.Substring(num + 1) : address); int num2 = text.LastIndexOf('.'); if (num2 <= 0) { return text; } return text.Substring(0, num2); } public static string PrefabNameOf(AssetReference r) { try { return (r == null) ? null : NameOf(AddressOf(r.AssetGUID)); } catch (Exception ex) { MelonLogger.Warning("[POGLib] address lookup failed: " + ex.GetType().Name + ": " + ex.Message); return null; } } public static TResult ReadNow<TAsset, TResult>(string key, Func<TAsset, TResult> read) where TAsset : Il2CppObjectBase { if (string.IsNullOrEmpty(key)) { return default(TResult); } AsyncOperationHandle<TAsset> val = Addressables.LoadAssetAsync<TAsset>((Object)(object)String.op_Implicit(key)); try { TAsset val2 = val.WaitForCompletion(); return (val2 == null) ? default(TResult) : read(val2); } finally { Addressables.Release<TAsset>(val); } } private static int Count(IList<IResourceLocation> l) { if (l != null) { return ((Il2CppObjectBase)l).Cast<ICollection<IResourceLocation>>().Count; } return 0; } } internal class AssetLoader { private readonly Dictionary<string, AssetBundle> _bundles = new Dictionary<string, AssetBundle>(); public AssetBundle LoadBundle(string path) { if (_bundles.TryGetValue(path, out var value)) { return value; } AssetBundle val = AssetBundle.LoadFromFile(path); if ((Object)(object)val == (Object)null) { MelonLogger.Error("[POGLib] Failed to load AssetBundle: " + path); return null; } _bundles[path] = val; MelonLogger.Msg("[POGLib] Loaded AssetBundle: " + path); return val; } public T LoadAsset<T>(AssetBundle bundle, string assetName) where T : Object { if ((Object)(object)bundle == (Object)null) { return default(T); } Object val = bundle.LoadAsset(assetName, Il2CppType.Of<T>()); T obj = ((val != (Object)null) ? ((Il2CppObjectBase)val).TryCast<T>() : default(T)); if ((Object)(object)obj == (Object)null) { MelonLogger.Warning("[POGLib] Asset '" + assetName + "' missing/wrong type in bundle."); } return obj; } public static Sprite LoadPngAsSprite(string path) { //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_0017: Expected O, but got Unknown //IL_003d: 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) byte[] array = File.ReadAllBytes(path); Texture2D val = new Texture2D(2, 2) { hideFlags = (HideFlags)32 }; ImageConversion.LoadImage(val, Il2CppStructArray<byte>.op_Implicit(array)); Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f)); ((Object)obj).hideFlags = (HideFlags)32; return obj; } public void UnloadAll() { foreach (AssetBundle value in _bundles.Values) { if ((Object)(object)value != (Object)null) { value.Unload(false); } } _bundles.Clear(); } } internal static class CompatibilityProbe { private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; private static readonly (Type type, string[] members)[] Expected = new(Type, string[])[12] { (typeof(InventoryItem), new string[24] { "m_itemID", "m_itemType", "m_mapIconType", "m_goldValue", "m_foodValue", "m_shopCost", "m_doConsume", "m_isConsumed", "m_itemIcon", "m_spawnOnDestroy", "m_spawnAmount", "m_spawnChance", "m_isBigItem", "m_staminaPenaltyOnPickup", "m_movementFactorWhenHeld", "Interact", "OnNetworkSpawn", "StartPrimaryAction", "m_itemTooltipID", "m_itemTooltipDescriptionID", "RefreshMeshInfo", "Entity", "IsInHands", "ConsumeItem_Owner" }), (typeof(ActiveItem_Eat), new string[14] { "m_healthOnEating", "m_damageOnEating", "m_staminaRefill", "m_minStaminaBonus", "m_maxStaminaBonus", "m_stomachFullTime", "m_useStaminaMin", "m_eatVfx", "m_bodyValue", "m_staminaValue", "m_strengthValue", "m_applyBuff", "m_buffValueToAdd", "m_buffValueToStart" }), (typeof(ActiveItem_MeleeWeapon), new string[4] { "m_maxDurability", "m_durabilityLossOnEntityHit", "m_durabilityLossOnDestructibleHit", "m_meleeHitCooldown" }), (typeof(ActiveItem_Throwable), new string[3] { "m_healthMax", "m_healthMin", "m_bounceFactor" }), (typeof(LootTable), new string[5] { "m_treasureItems", "m_foodItems", "m_usefulItems", "m_bigItems", "m_shopItems" }), (typeof(InventoryLootTable), new string[1] { "Items" }), (typeof(ItemContainer), new string[1] { "FromContainerData" }), (typeof(SpeakingStone), new string[2] { "Start", "SetEnabled" }), (typeof(LocalizationManager), new string[1] { "GetTranslation" }), (typeof(NetworkManager), new string[7] { "AddNetworkPrefab", "StartHost", "StartClient", "StartServer", "Shutdown", "NetworkConfig", "CustomMessagingManager" }), (typeof(NetworkObject), new string[1] { "GlobalObjectIdHash" }), (typeof(NetworkConfig), new string[2] { "ForceSamePrefabs", "Prefabs" }) }; private static readonly (string name, Func<Type> touch)[] CompiledBindings = new(string, Func<Type>)[13] { ("InventoryItem", () => typeof(InventoryItem)), ("ActiveItem_Eat", () => typeof(ActiveItem_Eat)), ("ActiveItem_MeleeWeapon", () => typeof(ActiveItem_MeleeWeapon)), ("ActiveItem_Throwable", () => typeof(ActiveItem_Throwable)), ("ActiveItem_ReadyItem", () => typeof(ActiveItem_ReadyItem)), ("MapIconType", () => typeof(MapIconType)), ("ItemType", () => typeof(ItemType)), ("LootTable", () => typeof(LootTable)), ("InventoryLootTable", () => typeof(InventoryLootTable)), ("ItemContainer", () => typeof(ItemContainer)), ("SpeakingStone", () => typeof(SpeakingStone)), ("LocalizationManager", () => typeof(LocalizationManager)), ("NetworkManager", () => typeof(NetworkManager)) }; internal static void Check() { Check("[POGLib]", Expected, CompiledBindings); } internal static void Check(string tag, (Type type, string[] members)[] expected, (string name, Func<Type> touch)[] compiledBindings) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; int num2 = 0; for (int i = 0; i < compiledBindings.Length; i++) { (string name, Func<Type> touch) tuple = compiledBindings[i]; string item = tuple.name; Func<Type> item2 = tuple.touch; num2++; try { if (item2() == null) { throw new TypeLoadException("resolved to null"); } } catch (Exception ex) { num++; stringBuilder.Append($"\n - compiled reference to {item} does not resolve ({ex.GetType().Name}: {ex.Message}) " + "— the game moved or changed this type; this DLL must be rebuilt against the current game"); } } for (int i = 0; i < expected.Length; i++) { (Type type, string[] members) tuple2 = expected[i]; Type item3 = tuple2.type; string[] item4 = tuple2.members; foreach (string text in item4) { num2++; try { if (item3.GetMember(text, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Length == 0) { num++; StringBuilder stringBuilder2 = stringBuilder; StringBuilder stringBuilder3 = stringBuilder2; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(6, 2, stringBuilder2); handler.AppendLiteral("\n - "); handler.AppendFormatted(item3.Name); handler.AppendLiteral("."); handler.AppendFormatted(text); stringBuilder3.Append(ref handler); } } catch (Exception ex2) { num++; StringBuilder stringBuilder2 = stringBuilder; StringBuilder stringBuilder4 = stringBuilder2; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(22, 3, stringBuilder2); handler.AppendLiteral("\n - "); handler.AppendFormatted(item3.Name); handler.AppendLiteral("."); handler.AppendFormatted(text); handler.AppendLiteral(" (probe error: "); handler.AppendFormatted(ex2.GetType().Name); handler.AppendLiteral(")"); stringBuilder4.Append(ref handler); } } } if (num == 0) { MelonLogger.Msg($"{tag} Compatibility OK ({num2} game members resolved)."); } else { MelonLogger.Warning($"{tag} COMPATIBILITY: {num}/{num2} expected game members NOT FOUND — the game may have updated. The framework may misbehave; update GameNames/bindings for this version. Missing:{stringBuilder}"); } } } internal static class ContentOwners { private static readonly Dictionary<string, string> _modToAssembly = new Dictionary<string, string>(StringComparer.Ordinal); private static readonly SortedSet<string> _assemblies = new SortedSet<string>(StringComparer.OrdinalIgnoreCase); private static readonly string Self = typeof(ContentOwners).Assembly.GetName().Name; public static IReadOnlyCollection<string> Assemblies => _assemblies; public static void Note(string modId, Assembly caller) { string text = caller?.GetName().Name; if (!string.IsNullOrEmpty(text)) { _assemblies.Add(text); _assemblies.Add(Self); if (!string.IsNullOrEmpty(modId)) { _modToAssembly[modId] = text; } } } } internal interface IContentDefinition { string ModId { get; } string ContentId { get; } } internal class ContentRegistry { private readonly Dictionary<string, IContentDefinition> _defsByFullId = new Dictionary<string, IContentDefinition>(); private readonly Dictionary<uint, IContentDefinition> _defsByHash = new Dictionary<uint, IContentDefinition>(); private readonly Dictionary<uint, NetworkObject> _prefabsByHash = new Dictionary<uint, NetworkObject>(); public IEnumerable<IContentDefinition> AllDefinitions => _defsByFullId.Values; public IEnumerable<NetworkObject> AllPrefabs => _prefabsByHash.Values; public static string FullId(string modId, string contentId) { return modId + ":" + contentId; } public static uint ComputeHash(string modId, string contentId, int salt = 0) { string s = ((salt == 0) ? FullId(modId, contentId) : $"{modId}:{contentId}#{salt}"); using MD5 mD = MD5.Create(); return BitConverter.ToUInt32(mD.ComputeHash(Encoding.UTF8.GetBytes(s)), 0); } public bool RegisterDefinition(IContentDefinition def) { if (def == null || string.IsNullOrEmpty(def.ModId) || string.IsNullOrEmpty(def.ContentId)) { MelonLogger.Error("[POGLib] Invalid content definition (empty ModId/ContentId)."); return false; } string text = FullId(def.ModId, def.ContentId); if (_defsByFullId.ContainsKey(text)) { MelonLogger.Warning("[POGLib] Duplicate content id ignored: " + text); return false; } uint num = ComputeHash(def.ModId, def.ContentId); _defsByFullId[text] = def; _defsByHash[num] = def; MelonLogger.Msg($"[POGLib] Registered definition: {text} (hash={num:X8})"); return true; } public void RegisterPrefab(NetworkObject prefab) { if (!((Object)(object)prefab == (Object)null)) { _prefabsByHash[prefab.GlobalObjectIdHash] = prefab; } } public IContentDefinition GetDefinition(string modId, string contentId) { if (!_defsByFullId.TryGetValue(FullId(modId, contentId), out var value)) { return null; } return value; } public IContentDefinition GetDefinitionByHash(uint hash) { if (!_defsByHash.TryGetValue(hash, out var value)) { return null; } return value; } public NetworkObject GetPrefabByHash(uint hash) { if (!_prefabsByHash.TryGetValue(hash, out var value)) { return null; } return value; } internal void Rekey(uint oldHash, uint newHash) { if (_defsByHash.TryGetValue(oldHash, out var value)) { _defsByHash.Remove(oldHash); _defsByHash[newHash] = value; } if (_prefabsByHash.TryGetValue(oldHash, out var value2)) { _prefabsByHash.Remove(oldHash); _prefabsByHash[newHash] = value2; } } } internal static class CoreServices { private static bool _init; public static ContentRegistry Content { get; private set; } public static ShellFactory Shells { get; private set; } public static NetworkRegistrar Network { get; private set; } public static AssetLoader Assets { get; private set; } public static HostBridge Bridge { get; private set; } public static LootInjector Loot { get; private set; } public static bool Ready => _init; public static void Init() { if (!_init) { _init = true; Content = new ContentRegistry(); Shells = new ShellFactory(Content); Network = new NetworkRegistrar(Content); Assets = new AssetLoader(); Bridge = new HostBridge(); Loot = new LootInjector(Content); MelonLogger.Msg("[POGLib] Core services initialized."); } } public static bool IsModItem(InventoryItem item) { if (!_init || (Object)(object)item == (Object)null) { return false; } NetworkObject component = ((Component)item).GetComponent<NetworkObject>(); if ((Object)(object)component != (Object)null) { return Content.GetDefinitionByHash(component.GlobalObjectIdHash) != null; } return false; } } internal sealed class DiagnosticsApi { public const string ProbeListFile = "UserData/pog_probe.txt"; private readonly HashSet<string> _pending = new HashSet<string>(); private readonly HashSet<string> _done = new HashSet<string>(); private readonly HashSet<string> _vfxFilters = new HashSet<string>(); private const int MaxVfxAttempts = 3; private int _vfxAttempts; private bool _listLoaded; public bool ProbeItem(string prefabName) { if (string.IsNullOrEmpty(prefabName)) { return false; } if (_done.Contains(prefabName)) { return true; } if (VisualProbe.ProbeItemPrefab(prefabName)) { _done.Add(prefabName); _pending.Remove(prefabName); return true; } _pending.Add(prefabName); return false; } public void ProbeObject(GameObject go, string label) { VisualProbe.ProbeGameObject(go, label); } public List<string> ListVfx(string filter = "", int limit = 200) { List<string> list = new List<string>(); try { foreach (ParticleSystem item2 in Resources.FindObjectsOfTypeAll<ParticleSystem>()) { if ((Object)(object)item2 == (Object)null) { continue; } string name = ((Object)((Component)item2).gameObject).name; if (filter.Length <= 0 || name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) { Transform val = ((Component)item2).transform; while ((Object)(object)val.parent != (Object)null) { val = val.parent; } string item = ((((Object)val).name == name) ? name : (((Object)val).name + " / " + name)); if (!list.Contains(item)) { list.Add(item); } if (list.Count >= limit) { break; } } } } catch (Exception ex) { MelonLogger.Warning("[POGLib.Probe] ListVfx failed: " + ex.Message); return list; } StringBuilder stringBuilder = new StringBuilder($"[POGLib.Probe] VFX matching '{filter}' ({list.Count}) — use as ParticleEffect.FromGameObject(id, ROOT, CHILD):"); foreach (string item3 in list) { stringBuilder.Append("\n ").Append(item3); } MelonLogger.Msg(stringBuilder.ToString()); return list; } internal void RetryPending() { LoadProbeListOnce(); if (_vfxFilters.Count > 0 && ++_vfxAttempts <= 3) { foreach (string item in new List<string>(_vfxFilters)) { if (ListVfx(item).Count > 0) { _vfxFilters.Remove(item); } } if (_vfxAttempts == 3 && _vfxFilters.Count > 0) { MelonLogger.Msg("[POGLib.Probe] No VFX matched: " + string.Join(", ", _vfxFilters) + " (try a shorter filter, or an empty 'vfx:' to list everything)."); } } if (_pending.Count == 0) { return; } foreach (string item2 in new List<string>(_pending)) { if (VisualProbe.ProbeItemPrefab(item2)) { _done.Add(item2); _pending.Remove(item2); } } } private void LoadProbeListOnce() { if (_listLoaded) { return; } _listLoaded = true; try { if (!File.Exists("UserData/pog_probe.txt")) { return; } string[] array = File.ReadAllLines("UserData/pog_probe.txt"); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length != 0 && text[0] != '#') { if (text.StartsWith("vfx:", StringComparison.OrdinalIgnoreCase)) { _vfxFilters.Add(text.Substring(4).Trim()); } else if (!_done.Contains(text)) { _pending.Add(text); } } } MelonLogger.Msg($"[POGLib.Probe] Probe list loaded from {"UserData/pog_probe.txt"} ({_pending.Count} entry/entries)."); } catch (Exception ex) { MelonLogger.Warning("[POGLib.Probe] Could not read UserData/pog_probe.txt: " + ex.Message); } } } internal static class GameAssets { public static InventoryItem FindItemPrefab(string prefabName) { if (string.IsNullOrEmpty(prefabName)) { return null; } GameObject val = GamePrefabs.Find(prefabName); if ((Object)(object)val != (Object)null && (Object)(object)val.GetComponent<InventoryItem>() != (Object)null) { return val.GetComponent<InventoryItem>(); } Il2CppArrayBase<InventoryItem> val2 = Resources.FindObjectsOfTypeAll<InventoryItem>(); for (int i = 0; i < val2.Length; i++) { if ((Object)(object)val2[i] != (Object)null && ((Object)((Component)val2[i]).gameObject).name == prefabName) { return val2[i]; } } return null; } public static GameObject FindGameObject(string objectName) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(objectName)) { return null; } GameObject val = null; Il2CppArrayBase<GameObject> val2 = Resources.FindObjectsOfTypeAll<GameObject>(); for (int i = 0; i < val2.Length; i++) { GameObject val3 = val2[i]; if (!((Object)(object)val3 == (Object)null) && !(((Object)val3).name != objectName)) { Scene scene = val3.scene; if (!((Scene)(ref scene)).IsValid()) { return val3; } if (val == null) { val = val3; } } } return val; } public static Sprite FindSprite(string spriteName) { if (string.IsNullOrEmpty(spriteName)) { return null; } Il2CppArrayBase<Sprite> val = Resources.FindObjectsOfTypeAll<Sprite>(); for (int i = 0; i < val.Length; i++) { if ((Object)(object)val[i] != (Object)null && ((Object)val[i]).name == spriteName) { return val[i]; } } return null; } } internal static class GameNames { public static class Shells { public const string Diamond = "Item_Diamond"; public const string Coin = "Item_Coin"; public const string GemEmerald = "Item_Gem_Emerald"; public const string BigItem = "BigItem_Decoration_01"; } public static class Shader { public const string BaseColor = "_BaseColor"; public const string Color = "_Color"; public const string EmissiveColor = "_EmissiveColor"; public const string EmissionColor = "_EmissionColor"; public const string EmissionKeyword = "_EMISSION"; public const string HdrpLit = "HDRP/Lit"; public const string ErrorShader = "Hidden/InternalErrorShader"; } public static class ModObjects { public const string GlowLight = "ModGlowLight"; } public static class VoiceComponents { public const string SpeakingStone = "SpeakingStone"; public const string VoiceProximity = "VoiceProximity"; } public static class Methods { public const string LocalizationManager_GetTranslation = "GetTranslation"; public const string SpeakingStone_Start = "Start"; public const string SpeakingStone_SetEnabled = "SetEnabled"; public const string InventoryItem_OnNetworkSpawn = "OnNetworkSpawn"; public const string InventoryItem_Interact = "Interact"; public const string InventoryItem_StartPrimaryAction = "StartPrimaryAction"; public const string ItemContainer_FromContainerData = "FromContainerData"; } public static readonly string[] SpeakingStoneVfx = new string[4] { "VFX_SpeakingStone", "SpeakingStoneOutline", "SpeakingStoneHolder", "SpeakingStoneParticles" }; public const string ModVisualChild = "ModItemVisual"; } internal static class GamePrefabs { public static NetworkPrefabsList Loaded { get { try { NetworkHandler singleton = NetworkHandler.Singleton; return (singleton != null) ? singleton.m_loadedNetworkPrefabsList : null; } catch { return null; } } } public static bool IsLoaded { get { NetworkPrefabsList loaded = Loaded; return ((loaded != null) ? loaded.List : null) != null; } } public static bool EnsureLoaded() { if (IsLoaded) { return true; } try { NetworkHandler singleton = NetworkHandler.Singleton; if ((Object)(object)singleton == (Object)null) { return false; } singleton.EnsureNetworkPrefabsRegistered(); } catch (Exception ex) { MelonLogger.Warning("[POGLib] Could not make the game load its network prefab list: " + ex.GetType().Name + ": " + ex.Message); } return IsLoaded; } public static GameObject Find(string prefabName) { NetworkPrefabsList loaded = Loaded; List<NetworkPrefab> val = ((loaded != null) ? loaded.List : null); if (val == null || string.IsNullOrEmpty(prefabName)) { return null; } for (int i = 0; i < val.Count; i++) { NetworkPrefab obj = val[i]; GameObject val2 = ((obj != null) ? obj.Prefab : null); if ((Object)(object)val2 != (Object)null && ((Object)val2).name == prefabName) { return val2; } } return null; } } internal static class HarmonyPatcher { internal static void PatchEachClass(Assembly assembly, Harmony harmony, string tag) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) int num = 0; int num2 = 0; Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Length == 0) { continue; } try { new PatchClassProcessor(harmony, type).Patch(); num++; } catch (Exception ex) { num2++; StringBuilder stringBuilder = new StringBuilder(); for (Exception ex2 = ex; ex2 != null; ex2 = ex2.InnerException) { stringBuilder.Append("\n ").Append(ex2.GetType().Name).Append(": ") .Append(ex2.Message); } MelonLogger.Error($"{tag} Harmony patch FAILED for {type.Name}:{stringBuilder}"); } } if (num2 == 0) { MelonLogger.Msg($"{tag} Harmony: {num} patch class(es) applied."); } else { MelonLogger.Warning($"{tag} Harmony: {num} applied, {num2} FAILED (those features are off; the rest work)."); } } internal static void CheckEachPatchOnce(Harmony harmony, string tag) { try { int num = 0; int num2 = 0; foreach (MethodBase patchedMethod in harmony.GetPatchedMethods()) { Patches patchInfo = Harmony.GetPatchInfo(patchedMethod); if (patchInfo == null) { continue; } List<Patch> list = (from p in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers) where p.owner == harmony.Id select p).ToList(); if (list.Count == 0) { continue; } num++; foreach (IGrouping<MethodInfo, Patch> item in from p in list group p by p.PatchMethod into g where g.Count() > 1 select g) { num2++; MelonLogger.Warning($"{tag} Harmony: {patchedMethod.DeclaringType?.Name}.{patchedMethod.Name} has {item.Key.DeclaringType?.Name}.{item.Key.Name} {item.Count()} times."); } } MelonLogger.Msg($"{tag} Harmony: {num} game method(s) patched; {((num2 == 0) ? "each patch once" : $"{num2} patch(es) more than once")}."); } catch (Exception ex) { MelonLogger.Warning(tag + " Harmony: could not check the patches: " + ex.Message); } } } public sealed class HostBridge { internal const string MessageName = "POGLib.HostBridge"; private const int MaxText = 65536; private readonly Dictionary<string, Action<ulong, string>> _handlers = new Dictionary<string, Action<ulong, string>>(); private CustomMessagingManager _registeredOn; private HandleNamedMessageDelegate _handler; internal HostBridge() { } public void RegisterHandler(string action, Action<ulong, string> handler) { if (!string.IsNullOrEmpty(action) && handler != null) { _handlers[action] = handler; } } internal void Hook() { NetworkManager singleton = NetworkManager.Singleton; CustomMessagingManager val = ((singleton != null) ? singleton.CustomMessagingManager : null); if (val == null || (_registeredOn != null && ((Il2CppObjectBase)_registeredOn).Pointer == ((Il2CppObjectBase)val).Pointer)) { return; } try { if ((Delegate)(object)_handler == (Delegate)null) { Action<ulong, FastBufferReader> action = OnMessage; _handler = HandleNamedMessageDelegate.op_Implicit(action); } val.RegisterNamedMessageHandler("POGLib.HostBridge", _handler); _registeredOn = val; MelonLogger.Msg("[POGLib] HostBridge hooked."); } catch (Exception ex) { MelonLogger.Warning("[POGLib] HostBridge could not register its message: " + ex.Message); } } internal void Unhook() { try { CustomMessagingManager registeredOn = _registeredOn; if (registeredOn != null) { registeredOn.UnregisterNamedMessageHandler("POGLib.HostBridge"); } } catch { } _registeredOn = null; } public void SendToServer(string action, string payload) { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.IsConnectedClient && !singleton.IsServer) { Send(singleton, NetworkManager.ServerClientId, action, payload); } } public void SendToClient(ulong clientId, string action, string payload) { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && clientId != NetworkManager.ServerClientId) { Send(singleton, clientId, action, payload); } } private void Send(NetworkManager nm, ulong to, string action, string payload) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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) Hook(); byte[] bytes = Encoding.UTF8.GetBytes(action ?? ""); byte[] bytes2 = Encoding.UTF8.GetBytes(payload ?? ""); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(bytes.Length + bytes2.Length + 8, (Allocator)2, -1); try { Write(val, bytes); Write(val, bytes2); nm.CustomMessagingManager.SendNamedMessage("POGLib.HostBridge", to, val, (NetworkDelivery)4); } finally { ((FastBufferWriter)(ref val)).Dispose(); } } private static void Write(FastBufferWriter w, byte[] bytes) { for (int i = 0; i < 4; i++) { ((FastBufferWriter)(ref w)).WriteByteSafe((byte)(bytes.Length >> 8 * i)); } foreach (byte b in bytes) { ((FastBufferWriter)(ref w)).WriteByteSafe(b); } } private static string Read(FastBufferReader r) { int num = 0; byte b = default(byte); for (int i = 0; i < 4; i++) { ((FastBufferReader)(ref r)).ReadByteSafe(ref b); num |= b << 8 * i; } if (num < 0 || num > 65536 || num > ((FastBufferReader)(ref r)).Length - ((FastBufferReader)(ref r)).Position) { return null; } byte[] array = new byte[num]; byte b2 = default(byte); for (int j = 0; j < num; j++) { ((FastBufferReader)(ref r)).ReadByteSafe(ref b2); array[j] = b2; } return Encoding.UTF8.GetString(array); } private void OnMessage(ulong senderId, FastBufferReader reader) { //IL_0002: 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) string text = null; try { text = Read(reader); string text2 = ((text == null) ? null : Read(reader)); Action<ulong, string> value; if (text == null || text2 == null) { MelonLogger.Warning($"[POGLib] HostBridge: an unreadable message from {senderId}."); } else if (_handlers.TryGetValue(text, out value)) { value(senderId, text2); } else { MelonLogger.Warning("[POGLib] HostBridge: no handler for '" + text + "'."); } } catch (Exception ex) { MelonLogger.Warning($"[POGLib] HostBridge '{text}' from {senderId}: {ex.GetType().Name}: {ex.Message}"); } } } internal enum PluginStage { Boot, SceneLoaded, BeforeSessionStart, SessionStop, GamePrefabsLoaded } internal interface IPOGPlugin { string Name { get; } string Version { get; } void Build(PluginGraph graph); } internal static class ItemVisuals { private const string ModCollisionChild = "ModCollision"; public static void ReplaceMeshes(GameObject target, GameObject visualSource, string childName) { if ((Object)(object)target == (Object)null || (Object)(object)visualSource == (Object)null || string.IsNullOrEmpty(childName)) { return; } MeshFilter val = null; MeshRenderer val2 = null; foreach (MeshFilter componentsInChild in visualSource.GetComponentsInChildren<MeshFilter>(true)) { if (!((Object)(object)componentsInChild == (Object)null) && !((Object)(object)componentsInChild.sharedMesh == (Object)null) && ((Object)((Component)componentsInChild).gameObject).name.Contains(childName) && !((Object)((Component)componentsInChild).gameObject).name.Contains("Outline")) { val = componentsInChild; val2 = ((Component)componentsInChild).GetComponent<MeshRenderer>(); break; } } if ((Object)(object)val == (Object)null) { StringBuilder stringBuilder = new StringBuilder(); foreach (MeshFilter componentsInChild2 in visualSource.GetComponentsInChildren<MeshFilter>(true)) { if ((Object)(object)componentsInChild2 != (Object)null) { stringBuilder.Append("\n ").Append(((Object)((Component)componentsInChild2).gameObject).name); } } MelonLogger.Warning($"[POGLib] Reskin FAILED: no mesh child matching '{childName}' in '{((Object)visualSource).name}' — the item keeps its shell mesh. Meshes available:{stringBuilder}"); return; } int num = 0; foreach (MeshFilter componentsInChild3 in target.GetComponentsInChildren<MeshFilter>(true)) { if (!((Object)(object)componentsInChild3 == (Object)null) && !((Object)(object)componentsInChild3.sharedMesh == (Object)null) && !((Object)((Component)componentsInChild3).gameObject).name.Contains("Outline")) { componentsInChild3.sharedMesh = val.sharedMesh; MeshRenderer component = ((Component)componentsInChild3).GetComponent<MeshRenderer>(); if ((Object)(object)component != (Object)null && (Object)(object)val2 != (Object)null) { ((Renderer)component).sharedMaterials = ((Renderer)val2).sharedMaterials; } num++; } } try { InventoryItem component2 = target.GetComponent<InventoryItem>(); if (component2 != null) { component2.RefreshMeshInfo(); } } catch (Exception ex) { MelonLogger.Warning("[POGLib] RefreshMeshInfo failed: " + ex.Message); } MelonLogger.Msg($"[POGLib] Reskin: '{childName}' mesh applied to {num} renderer(s) on {((Object)target).name}."); } public static void ReplaceMeshes(GameObject target, Mesh mesh, Il2CppReferenceArray<Material> materials) { //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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: 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_00a2: 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_011d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)target == (Object)null || (Object)(object)mesh == (Object)null) { return; } int num = 0; foreach (MeshFilter componentsInChild in target.GetComponentsInChildren<MeshFilter>(true)) { if (!((Object)(object)componentsInChild == (Object)null) && !((Object)((Component)componentsInChild).gameObject).name.Contains("Outline")) { componentsInChild.sharedMesh = mesh; MeshRenderer component = ((Component)componentsInChild).GetComponent<MeshRenderer>(); if ((Object)(object)component != (Object)null && materials != null && ((Il2CppArrayBase<Material>)(object)materials).Length > 0) { ((Renderer)component).sharedMaterials = materials; } Quaternion val = Quaternion.Inverse(target.transform.rotation) * ((Component)componentsInChild).transform.rotation; if (Quaternion.Angle(val, Quaternion.identity) > 0.5f) { ((Component)componentsInChild).transform.rotation = target.transform.rotation; MelonLogger.Msg($"[POGLib] Custom mesh '{((Object)mesh).name}': '{((Object)((Component)componentsInChild).gameObject).name}' was turned {((Quaternion)(ref val)).eulerAngles} " + "from the item; set upright to the item."); } num++; } } try { InventoryItem component2 = target.GetComponent<InventoryItem>(); if (component2 != null) { component2.RefreshMeshInfo(); } } catch (Exception ex) { MelonLogger.Warning("[POGLib] RefreshMeshInfo failed: " + ex.Message); } if (num == 0) { MelonLogger.Warning($"[POGLib] Custom mesh '{((Object)mesh).name}': no renderer on {((Object)target).name} to apply it to."); } else { MelonLogger.Msg($"[POGLib] Custom mesh '{((Object)mesh).name}' applied to {num} renderer(s) on {((Object)target).name}."); } } public static void ApplyColliders(GameObject target, Mesh[] hulls, Mesh visualMesh) { if ((Object)(object)target == (Object)null) { return; } Il2CppArrayBase<Collider> componentsInChildren = target.GetComponentsInChildren<Collider>(true); if (componentsInChildren == null) { return; } List<Collider> list = new List<Collider>(); int num = 0; foreach (Collider item in componentsInChildren) { if (!((Object)(object)item == (Object)null)) { if (item.isTrigger) { num++; } else { list.Add(item); } } } if (hulls != null && hulls.Length != 0) { ReplaceWithHulls(target, list, hulls, num); } else if ((Object)(object)visualMesh != (Object)null) { RefitToBounds(target, list, visualMesh, num); } try { InventoryItem component = target.GetComponent<InventoryItem>(); if (component != null) { component.RefreshMeshInfo(); } } catch (Exception ex) { MelonLogger.Warning("[POGLib] RefreshMeshInfo failed: " + ex.Message); } } private static void ReplaceWithHulls(GameObject target, List<Collider> solid, Mesh[] hulls, int triggers) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown PhysicsMaterial val = ((solid.Count > 0 && (Object)(object)solid[0] != (Object)null) ? solid[0].sharedMaterial : null); int num = ((solid.Count > 0 && (Object)(object)solid[0] != (Object)null) ? ((Component)solid[0]).gameObject.layer : target.layer); Transform val2 = FindVisualAnchor(target); Transform val3 = val2.Find("ModCollision"); if ((Object)(object)val3 != (Object)null) { Object.Destroy((Object)(object)((Component)val3).gameObject); } GameObject val4 = new GameObject("ModCollision"); val4.transform.SetParent(val2, false); val4.layer = num; foreach (Collider item in solid) { if ((Object)(object)item != (Object)null) { Object.Destroy((Object)(object)item); } } int num2 = 0; foreach (Mesh val5 in hulls) { if (!((Object)(object)val5 == (Object)null)) { MeshCollider val6 = val4.AddComponent<MeshCollider>(); val6.convex = true; val6.sharedMesh = val5; if ((Object)(object)val != (Object)null) { ((Collider)val6).sharedMaterial = val; } num2++; } } MelonLogger.Msg($"[POGLib] Colliders: replaced {solid.Count} shell collider(s) with {num2} convex hull(s) under '{((Object)val2).name}/{"ModCollision"}' (layer={LayerMask.LayerToName(num)}, {triggers} trigger(s) left untouched)."); } private static Transform FindVisualAnchor(GameObject target) { MeshFilter val = null; foreach (MeshFilter componentsInChild in target.GetComponentsInChildren<MeshFilter>(true)) { if ((Object)(object)componentsInChild == (Object)null || (Object)(object)componentsInChild.sharedMesh == (Object)null || ((Object)((Component)componentsInChild).gameObject).name.Contains("Outline")) { continue; } if ((Object)(object)val == (Object)null) { val = comp