RacesOfValheim/JotunnModStub/RaceClaws.cs
kanym 6db21b9d96 fix(fenrir): register the claw set from a live object, not a half-built singleton
The Cursed Claws were never issued because FenrirClaws was never in the
roster. RaceClawSet's static constructor registers the two singletons by
reading AswidClaws.Instance and FenrirClaws.Instance - but constructing
a derived type runs the base type's static constructor first, so the
race that triggers it is still mid-construction when its own Instance is
read, and reads null. Register(null) returns silently and that race is
left out for the rest of the session: For() never matches it, Maintain
never runs, no claws, no claw damage.

It was the Fenrir and not the Aswid only because FenrirRace runs first in
CreateAllModAssets - whichever race gets there first is the one that is
half-built.

EnsureRegistered now calls Register(this) before anything else. `this` is
a live object by definition, so there is nothing left to be null, and
every race puts itself in the roster at startup. The static constructor
stays as a harmless backstop with the trap written down next to it.

Damage scaling checked while here and needs no change: all three races
run the same SvermClaws.GetReferenceDamage/GetDamagePercent pair over the
one shared per-state table, so the same tier is worth the same damage.
2026-08-12 17:05:58 +02:00

630 lines
29 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Claws that are part of the body, for the races that grow a pair.
///
/// This is SvermClawSlot generalised, not reinvented: the Sverm's Vilebone Maulclaws worked out
/// the whole shape of the problem, and the Aswid and the Fenrir are asking for the same object
/// with a different face. So the machinery moved here and each race supplies only what is
/// genuinely its own - the item name, the model to wear, and whether it is currently a wolf.
/// The Sverm still runs its own copy, untouched, because it also carries a carapace, a stinger
/// form and a fire term at Fader that none of this knows about.
///
/// WHY A REAL ITEM AND NOT A COSMETIC. Bolting a model to the hand bones works right up until
/// the game rebuilds equipment visuals - which it does on every equip - and wipes it. A real
/// item in a real slot has nothing to put back. The trade is that a real weapon occupies the
/// right hand, so three rules keep that reading as intended rather than as a bug: sheathe
/// anything else and the claws come back, the holster key cannot put them away, and they
/// cannot be dragged, moved or dropped.
///
/// BALANCE IS SHARED ON PURPOSE. The damage is not read from the model each race wears - the
/// Fenrir's flesh rippers and the Bjorn claw are not worth the same, and a race should not be
/// stronger because its claws are prettier. Every set reads the Sverm's own reference weapon at
/// quality 4 and the Sverm's own per-tier percentages, so all three races hit for identical
/// numbers at identical tiers. What differs here is the shape of the damage: these two land it
/// entirely as slash, where the Sverm splits it three ways and lights it on fire at Fader.
/// </summary>
public abstract class RaceClawSet
{
// ─── What a race has to say about its own claws ──────────────────────
/// <summary>The race string in the ZDO, e.g. "Aswid".</summary>
public abstract string RaceId { get; }
/// <summary>Prefab id of the cloned item. Never seen by a player.</summary>
public abstract string ItemName { get; }
/// <summary>What the item is called in the inventory.</summary>
public abstract string DisplayName { get; }
public abstract string Description { get; }
/// <summary>
/// Models to clone, in order of preference. A list rather than a name because the install's
/// manifest carries several near-identical claw ids and only some of them resolve - see
/// SvermConfig.ClawPrefabFallbacks, which is where that lesson was learned. The winner is
/// logged; a miss is a warning rather than two empty hands and silence.
/// </summary>
public abstract string[] ModelPrefabs { get; }
/// <summary>ZDO key carrying this race's progression state, or null if it publishes none.</summary>
public virtual string StateZdoKey => null;
/// <summary>Multiplied into the model's own colours. Null leaves the model as authored.</summary>
public virtual Color? Tint => null;
/// <summary>
/// True while the player is wearing another body entirely - a bat, mist, a wolf. Claws are
/// neither issued nor counted while that is the case: the form does its own damage and has
/// its own hands, and a weapon equipped underneath it is at best invisible and at worst the
/// thing the game decides to swing.
/// </summary>
public abstract bool IsTransformed(Player player);
// ─── Registry ────────────────────────────────────────────────────────
private static readonly List<RaceClawSet> sets = new List<RaceClawSet>();
/// <summary>
/// The roster. Kept here rather than in RacesOfValheim.Awake so the whole feature is this
/// file plus one short file per race, and adding a third clawed race is one line - not one
/// line here and another one three hundred lines away in the plugin's startup.
///
/// A BACKSTOP ONLY - EnsureRegistered is what actually fills this list, and it has to be.
/// This constructor cannot be trusted to register a race that is still being constructed,
/// and one of them always is:
///
/// FenrirRace.CreateModAssets touches FenrirClaws.Instance
/// -> the CLR begins FenrirClaws' static init: Instance = new FenrirClaws()
/// -> constructing a derived type runs the BASE type's static ctor first, i.e. this one
/// -> this one reads FenrirClaws.Instance... which is still null, because the static
/// init that will assign it is the thing waiting on us
/// -> Register(null) returns silently, and the Fenrir is left out of the roster for the
/// rest of the session: For() never matches it, so Maintain never runs, so the
/// Cursed Claws are never issued and never do their damage.
///
/// It bit the Fenrir and not the Aswid purely because FenrirRace.CreateModAssets runs
/// first in RacesOfValheim.CreateAllModAssets - whichever race gets there first is the one
/// that is half-built when this runs. Register(this) in EnsureRegistered closes it for
/// good: `this` is a live object by definition, so there is nothing to be null.
/// </summary>
static RaceClawSet()
{
Register(AswidClaws.Instance);
Register(FenrirClaws.Instance);
}
public static void Register(RaceClawSet set)
{
if (set == null || sets.Contains(set)) return;
sets.Add(set);
}
/// <summary>The set that belongs to this player's race, or null for everyone else.</summary>
public static RaceClawSet For(Player player)
{
if (player == null) return null;
string race = GetRace(player);
foreach (RaceClawSet set in sets)
{
if (set.RaceId == race) return set;
}
return null;
}
/// <summary>True if the item is any registered race's claws.</summary>
public static RaceClawSet SetOwning(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return null;
foreach (RaceClawSet set in sets)
{
if (set.IsClaws(item)) return set;
}
return null;
}
/// <summary>
/// Reads the race off the ZDO, falling back to m_customData - the same order every visual
/// in this mod reads it in, so a remote player and the menu preview both answer correctly.
/// </summary>
private static string GetRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
// ─── Registration of the item ────────────────────────────────────────
private bool registered;
private bool warnedModel;
private bool loggedMaterials;
private readonly List<Material> ownedMaterials = new List<Material>();
/// <summary>
/// Clones whichever of the candidate models this build actually has. Deferred until ObjectDB
/// is up, so it is driven from the maintain tick rather than from Awake.
/// </summary>
public void EnsureRegistered()
{
// BEFORE the early return, and before anything else: this is the one place the roster
// is filled reliably. See the static constructor for why it cannot do this itself.
// Idempotent, so calling it on every tick as well as at startup costs nothing.
Register(this);
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
{
registered = true;
return;
}
GameObject source = ResolveModel();
if (source == null) return; // already warned once by the resolver
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
if (clone == null)
{
Jotunn.Logger.LogWarning($"[{RaceId}] 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 = DisplayName;
shared.m_description = Description;
// 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.
}
TakeOwnershipOfMaterials(clone);
ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
registered = true;
Jotunn.Logger.LogInfo($"[{RaceId}] Registered '{ItemName}' from '{source.name}'.");
RefreshTint();
}
private GameObject ResolveModel()
{
foreach (string name in ModelPrefabs)
{
// PrefabManager's cache first, ObjectDB second: the cache answers earlier in the
// load, and ObjectDB is still empty when the plugin wakes.
GameObject candidate = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (candidate == null && ObjectDB.instance != null)
{
candidate = ObjectDB.instance.GetItemPrefab(name);
}
if (candidate != null)
{
Jotunn.Logger.LogInfo($"[{RaceId}] Claw model resolved to '{name}'.");
return candidate;
}
}
// Warned once, but NOT latched: a later call may run when more of the game is loaded,
// and a race with no hands is worth retrying for.
if (!warnedModel)
{
warnedModel = true;
Jotunn.Logger.LogWarning($"[{RaceId}] None of " + string.Join(", ", ModelPrefabs) +
" resolved yet; retrying as the game loads.");
}
return null;
}
/// <summary>
/// Gives the clone its own copies of every material it draws with.
///
/// A cloned prefab still points at the ORIGINAL material assets, so tinting them straight
/// would repaint the vanilla weapon in every hand in the world - a thing that would show up
/// as "why are the flesh rippers black now" and take an hour to trace back here. Copies
/// also make the tint live: an instantiated item shares these same material objects, so
/// writing a colour on them reaches the pair already in the player's hands.
/// </summary>
private void TakeOwnershipOfMaterials(GameObject clone)
{
ownedMaterials.Clear();
foreach (Renderer renderer in clone.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
if (materials == null) continue;
for (int i = 0; i < materials.Length; i++)
{
if (materials[i] == null) continue;
Material copy = new Material(materials[i]);
copy.name = materials[i].name + "_" + ItemName;
materials[i] = copy;
ownedMaterials.Add(copy);
}
renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Repaints the claws. Called on the maintain tick as well as at registration, so a tint
/// driven by config moves while the game is running.
///
/// Every colour property the shader turns out to have is written rather than guessing which
/// one it uses: writing a property a shader does not have is an error, writing all the ones
/// it does is free.
/// </summary>
public void RefreshTint()
{
if (Tint == null || ownedMaterials.Count == 0) return;
Color tint = Tint.Value;
foreach (Material material in ownedMaterials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", tint);
if (material.HasProperty("_MainColor")) material.SetColor("_MainColor", tint);
// A claw is not a lamp. Whatever the source model glowed with goes out, or the
// tint fights a bloom it cannot win against.
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
}
if (loggedMaterials) return;
loggedMaterials = true;
foreach (Material material in ownedMaterials)
{
if (material == null) continue;
List<string> properties = new List<string>();
foreach (string name in new[] { "_Color", "_BaseColor", "_MainColor", "_EmissionColor" })
{
if (material.HasProperty(name)) properties.Add(name);
}
Jotunn.Logger.LogInfo(
$"[{RaceId}] Claw material '{material.name}' shader " +
$"'{(material.shader != null ? material.shader.name : "none")}' " +
$"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
}
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
/// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash the
/// Sverm hit first. Maintain equips the claws; Humanoid.EquipItem unequips the right hand
/// first, which fires the UnequipItem postfix, which calls Maintain... Mono answers an
/// unbounded recursion by killing the process outright, with no exception and a log file
/// that ends mid-word.
/// </summary>
private static bool maintaining;
/// <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>
public void Maintain(Player player)
{
if (maintaining) return;
if (player == null || player != Player.m_localPlayer) return;
if (For(player) != this) return;
if (player.IsDead() || IsTransformed(player)) return;
maintaining = true;
try { MaintainInner(player); }
finally { maintaining = false; }
}
private void MaintainInner(Player player)
{
EnsureRegistered();
RefreshTint();
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)
{
// The failure that cost the first version of this feature an evening. The item
// registers, logs its success, tints its materials - and is not in ObjectDB,
// because Jotunn only takes new items at OnVanillaPrefabsAvailable and this ran
// afterwards. It looked from the log exactly like everything had worked.
WarnOnce("missing-from-objectdb",
$"'{ItemName}' is registered but not in ObjectDB, so it cannot be issued. " +
"It has to be registered from CreateModAssets (PrefabManager.OnVanillaPrefabsAvailable), not later.");
return;
}
// The GameObject overload, deliberately: it is the one that is public in the
// shipped assembly, and this project compiles against that rather than against the
// publicized copy - so anything else would build here and not on a clean machine.
if (!inventory.AddItem(prefab, 1))
{
WarnOnce("inventory-full", $"No room in the inventory for the {DisplayName}; retrying.");
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: 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($"[{RaceId}] Issued the {DisplayName}.");
}
// 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.EquipItem(claws, false);
}
}
private readonly HashSet<string> warned = new HashSet<string>();
/// <summary>
/// Says a thing once. The maintain tick runs twice a second, so a plain warning here is a
/// log file rather than a message - which is the other half of why this failure was silent.
/// </summary>
private void WarnOnce(string key, string message)
{
if (!warned.Add(key)) return;
Jotunn.Logger.LogWarning($"[{RaceId}] {message}");
}
/// <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 answers the same question with nothing but public members.
/// </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 ItemDrop.ItemData Find(Inventory inventory)
{
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (IsClaws(item)) return item;
}
return null;
}
public 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 == DisplayName;
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// The tier this player is fighting at. Remote players answer from their own ZDO where the
/// race publishes one; where it does not, this falls back to the local player's progression
/// - the same compromise SvermVisuals.GetRenderState makes, and it only ever matters for
/// somebody else's claws on a shared world.
/// </summary>
private int GetState(Player player)
{
if (player != null && player != Player.m_localPlayer && !string.IsNullOrEmpty(StateZdoKey))
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
int remote = nview.GetZDO().GetInt(StateZdoKey, 0);
if (remote > 0)
{
return Mathf.Clamp(remote, BossProgressionManager.MinState, BossProgressionManager.MaxState);
}
}
}
return BossProgressionManager.GetCurrentProgressionState();
}
/// <summary>
/// Rewrites a bare-handed blow into a claw blow, as slash and nothing else.
///
/// The figure is the Sverm's - its reference weapon at quality 4, times its percentage for
/// this tier - but where the Sverm keeps the weapon's own three-way split, this collapses
/// the whole physical total into slash. Claws cut. The total is preserved rather than the
/// slash component copied, so the three races stay worth the same and only the damage type
/// differs, which is the entire point of the exercise.
/// </summary>
public void ApplyToUnarmedHit(HitData hit, Player attacker)
{
if (hit == null || attacker == null) return;
if (IsTransformed(attacker)) return; // the form is doing its own damage
HitData.DamageTypes reference = SvermClaws.GetReferenceDamage();
float percent = SvermClaws.GetDamagePercent(GetState(attacker));
if (percent <= 0f) return;
float total = (reference.m_slash + reference.m_pierce + reference.m_blunt) * percent;
// Nothing to give: the reference item did not resolve. Leave vanilla's fist alone
// rather than zeroing the player's only attack.
if (total <= 0f) return;
hit.m_damage.m_slash = total;
hit.m_damage.m_pierce = 0f;
hit.m_damage.m_blunt = 0f;
}
}
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Issues the claws and puts them back in hand. On a throttle rather than every frame: it is a
/// handful of checks that all short-circuit once the claws exist.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class RaceClaws_PlayerUpdate_Patch
{
private const float Interval = 0.5f;
private static float next;
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (Time.time < next) return;
next = Time.time + Interval;
RaceClawSet set = RaceClawSet.For(__instance);
if (set != null) set.Maintain(__instance);
}
}
/// <summary>
/// Put anything else away and the claws come straight back. A postfix rather than a prefix: the
/// game is mid-way through tearing down the old item's visuals when a prefix would run, and
/// equipping there leaves the new item without a model.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
public static class RaceClaws_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",
// and the recursion that follows kills the process silently.
if (item == null) return;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
RaceClawSet set = RaceClawSet.For(player);
if (set == null) return;
if (set.IsClaws(item)) return; // do not re-equip what was just taken off
set.Maintain(player);
}
}
/// <summary>
/// The holster key cannot put the claws away. Refused only while the claws ARE the thing in
/// hand: holding a sword, R sheathes the sword normally and the unequip postfix hands the claws
/// back on the same action. So the key keeps working and simply never leaves the race
/// empty-handed.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
public static class RaceClaws_HideHandItems_Patch
{
public static bool Prefix(Humanoid __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
RaceClawSet set = RaceClawSet.For(player);
if (set == null) return true;
ItemDrop.ItemData held = Traverse.Create(__instance).Field<ItemDrop.ItemData>("m_rightItem").Value;
return !set.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 - so refusing here closes all of them with one prefix.
///
/// Only refused while the item is CURRENTLY that race's claws - checked against SetOwning
/// (whose set the item is) against RaceClawSet.For (what race the player is right now), not
/// merely "is this any race's claws at all". A player who has since switched race carries a
/// pair that RaceItemCleanup should have already removed, but if it has not run yet for any
/// reason, this is the difference between an item merely undraggable and one undraggable
/// forever: without the race check, nothing the player does - not death, not a tombstone, not
/// closing the item's own quest-item flag - would ever let them shed it again.
/// </summary>
[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
public static class RaceClaws_SetupDragItem_Patch
{
public static bool Prefix(ItemDrop.ItemData item)
{
RaceClawSet owner = RaceClawSet.SetOwning(item);
if (owner == null) return true;
if (Player.m_localPlayer == null || owner != RaceClawSet.For(Player.m_localPlayer)) return true;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
return false;
}
}
/// <summary>
/// The tier's damage, on any bare-handed blow. Fist weapons report Unarmed, so this covers both
/// the equipped claws and an actually empty hand - which is what keeps the two halves of the
/// feature agreeing with each other.
/// </summary>
[HarmonyPatch(typeof(Character), nameof(Character.Damage))]
public static class RaceClaws_Damage_Patch
{
public static void Prefix(HitData hit)
{
if (hit == null || hit.m_skill != Skills.SkillType.Unarmed) return;
Player attacker = hit.GetAttacker() as Player;
if (attacker == null) return;
RaceClawSet set = RaceClawSet.For(attacker);
if (set == null) return;
set.ApplyToUnarmedHit(hit, attacker);
}
}
}