RacesOfValheim/JotunnModStub/Sverm/SvermClawSlot.cs
2026-08-11 16:30:20 +02:00

283 lines
13 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and
/// refusing to be moved.
///
/// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the
/// carapace beside it did not: the game rebuilds equipment visuals from what is ACTUALLY in
/// the slots, so every unequip wiped the lot and something had to put it back, one frame late
/// and visibly. A real item in a real slot removes the whole class of problem - there is
/// nothing to put back, because nothing was ever faked.
///
/// The trade, accepted deliberately: a real weapon occupies the right hand, so drawing a sword
/// puts the claws away. Three rules make that read as intended rather than as a bug:
///
/// 1. sheathe anything else and the claws come straight back (UnequipItem postfix);
/// 2. the holster key cannot put the claws away - a Sverm is never empty-handed
/// (HideHandItems prefix);
/// 3. the claws cannot be dragged, moved or dropped (SetupDragItem prefix, quest-item flag).
///
/// VISIBLE, NOT HIDDEN, and that is the second design this file has had. The first reserved
/// the rightmost column and switched its slots off in the inventory window - which meant
/// patching InventoryGrid.UpdateGui, a method that runs for every chest and every grid in the
/// game, to hide something in exactly one of them. It also cost the player four slots.
/// Showing the claws and refusing to let them move is less code, touches no UI, and tells the
/// player something true: they are carrying them, and they always will be.
///
/// The last resort behind all three rules is that Maintain re-issues the claws whenever they
/// are missing. However they get lost - a tombstone, a mod, a bug in this file - they are back
/// within half a second.
/// </summary>
public static class SvermClawSlot
{
public const string ItemName = "SvermMaulclaws";
public const string ItemDisplayName = "Vilebone Maulclaws";
/// <summary>Row in the reserved column the claws sit on. The other three await the carapace.</summary>
private const int ClawRow = 0;
private static bool registered;
// ─── Registration ────────────────────────────────────────────────────
/// <summary>
/// Clones whichever of the four candidate prefabs this build actually has. Deferred until
/// ObjectDB is up, so it is driven from the first player spawn rather than from Awake.
/// </summary>
public static void EnsureRegistered()
{
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
{
registered = true;
return;
}
GameObject source = SvermClaws.GetPrefab();
if (source == null) return; // already logged once by the resolver
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
if (clone == null)
{
Jotunn.Logger.LogWarning($"[Sverm] Could not clone '{source.name}'; the claws stay unregistered.");
return;
}
ItemDrop drop = clone.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
{
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = ItemDisplayName;
shared.m_description = "Grown, not forged. They do not come off.";
// Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest
// honest way to say "this is part of your body" without a patch per verb.
shared.m_questItem = true;
shared.m_teleportable = true;
shared.m_weight = 0f;
shared.m_maxQuality = 1;
// No recipe and no station: this item is never crafted, only issued.
}
ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
registered = true;
Jotunn.Logger.LogInfo($"[Sverm] Registered '{ItemName}' from '{source.name}'.");
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
/// Makes sure the player owns exactly one pair and is holding them whenever both hands are
/// free. Safe to call on a timer: every step checks first.
/// </summary>
/// <summary>
/// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash.
///
/// Maintain equips the claws. Humanoid.EquipItem unequips the right hand first, which
/// fires the UnequipItem postfix, which calls Maintain, which equips the claws... Mono
/// answers an unbounded recursion by killing the process outright, with no exception and a
/// log file that ends mid-word. Switching race was enough to trigger it every time.
///
/// The null check in the postfix closes the specific door; this closes the corridor.
/// </summary>
private static bool maintaining;
public static void Maintain(Player player)
{
if (maintaining) return;
if (player == null || player != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
maintaining = true;
try { MaintainInner(player); }
finally { maintaining = false; }
}
private static void MaintainInner(Player player)
{
EnsureRegistered();
Inventory inventory = player.GetInventory();
if (inventory == null) return;
ItemDrop.ItemData claws = Find(inventory);
if (claws == null)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
if (prefab == null) return;
// The GameObject overload, deliberately: it is the one that is public in the
// shipped assembly. The overloads that take a grid position are private there, and
// the project compiles against the shipped assembly rather than the publicized
// copy - so anything else would build on this machine and not on a clean one.
if (!inventory.AddItem(prefab, 1)) return;
claws = Find(inventory);
if (claws == null) return;
// Tidied into the bottom-right corner IF that corner is free, and left wherever
// the inventory put them otherwise. Nothing of the player's is ever displaced to
// make room: an item that cannot be moved has no business shoving one that can.
Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1);
if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null)
{
claws.m_gridPos = corner;
}
Jotunn.Logger.LogInfo("[Sverm] Issued the Maulclaws.");
}
// Empty-handed means clawed. Anything else in the right hand wins until it is put
// away, which is the whole compromise.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (held == null && !player.InAttack() && !player.IsDead())
{
player.EquipItem(claws, false);
}
}
/// <summary>
/// What is sitting at this grid position, read from the items themselves.
///
/// Inventory.GetItemAt is private in the shipped assembly, and every item already carries
/// its own m_gridPos, so a scan over GetAllItems answers the same question with nothing
/// but public members. An inventory holds a few dozen items; this is not a hot path.
/// </summary>
private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y)
{
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item;
}
return null;
}
public static ItemDrop.ItemData Find(Inventory inventory)
{
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return item;
if (item != null && item.m_shared != null && item.m_shared.m_name == ItemDisplayName) return item;
}
return null;
}
public static bool IsClaws(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return false;
if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true;
return item.m_shared.m_name == ItemDisplayName;
}
}
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Put anything else away and the claws come straight back.
///
/// A postfix rather than doing it inside UnequipItem's own flow: the game is mid-way through
/// tearing down the old item's visuals when the prefix would run, and equipping there leaves
/// the new item without a model.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
public static class Sverm_UnequipItem_Patch
{
public static void Postfix(Humanoid __instance, ItemDrop.ItemData item)
{
// NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before
// putting a weapon in the hand, and an empty hand means that argument is null. Without
// this line the postfix treats "nothing was unequipped" as "something was unequipped",
// calls Maintain, which equips the claws, which unequips null again - and Mono kills
// the process on the recursion, instantly and silently.
if (item == null) return;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (SvermClawSlot.IsClaws(item)) return; // do not re-equip what was just taken off
SvermClawSlot.Maintain(player);
}
}
/// <summary>
/// The holster key cannot put the claws away.
///
/// HideHandItems is what R calls. Refused only while the claws ARE the thing in hand: holding
/// a sword, R sheathes the sword normally, and the unequip postfix above hands the claws back
/// on the same action. So the key keeps working and simply never leaves a Sverm empty-handed.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
public static class Sverm_HideHandItems_Patch
{
public static bool Prefix(Humanoid __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
if (!SvermVisuals.IsSvermPlayer(player)) return true;
ItemDrop.ItemData held = Traverse.Create(__instance).Field<ItemDrop.ItemData>("m_rightItem").Value;
return !SvermClawSlot.IsClaws(held);
}
}
/// <summary>
/// The claws cannot be picked up with the mouse.
///
/// SetupDragItem is the single door every manual move goes through - within the inventory, out
/// to a chest, onto the ground, into a crafting slot. Refusing here closes all of them with
/// one prefix, instead of one patch per destination, and leaves every OTHER item's handling
/// completely untouched.
///
/// It replaces an earlier design that hid the rightmost column outright. That one had to patch
/// InventoryGrid.UpdateGui - a method that runs for every chest and every grid in the game -
/// in order to change exactly one of them, and it cost the player four slots. The claws are
/// visible now, which is also more honest: they are part of the character, and the character
/// can see them.
/// </summary>
[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
public static class Sverm_SetupDragItem_Patch
{
public static bool Prefix(ItemDrop.ItemData item)
{
if (!SvermClawSlot.IsClaws(item)) return true;
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
}
return false;
}
}
}