RacesOfValheim/JotunnModStub/Dvergar/DvergarRace.cs
Ferdinando 5c5b8c34d2 feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones
Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

132 lines
5.6 KiB
C#

using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Driver for the Dvergar: a short, stocky smith who trades a slice of health for an affinity
/// with hammer, bow, axe and crossbow, a knack for mining and the ear of Haldor and Hildir.
///
/// Only the per-frame upkeep lives here. Body scale is a Player.Update postfix in
/// DvergarPatches, since that is the one place it survives; the perks are the other patches in
/// that file; the two eitr abilities are in DvergarAbilities; and every number they use comes
/// from DvergarConfig by way of DvergarProgression.
/// </summary>
public class DvergarRace : MonoBehaviour
{
public static DvergarRace Instance;
// NaN so that the very first frame always counts as a change and pushes the malus through.
private float lastAppliedMalus = float.NaN;
private int lastAppliedStarTier = -1;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
DvergarStatusEffects.RegisterStatusEffects();
// The contract bank and every mercenary it can hire. Race-locked at placement, like the
// Trol's war totem and unlike every other station in the mod.
DvergarBanco.Register();
// The barrel the crews drink from. Separate piece, no dependency in either direction:
// it serves whatever RaisedThrall is standing near it.
DvergarBotte.Register();
}
/// <summary>
/// The race was called "Dvergur" before it was renamed, and that string is what got written
/// into m_customData and the ZDO. Without this, every character created under the old name
/// would come back with no race at all and be handed the selection menu again.
/// </summary>
public const string LegacyRaceId = "Dvergur";
public static void MigrateLegacyRaceId(Player player)
{
if (player == null || player.m_customData == null) return;
if (!player.m_customData.TryGetValue("Race", out string race) || race != LegacyRaceId) return;
player.m_customData["Race"] = DvergarConfig.RaceId;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_Race", DvergarConfig.RaceId);
}
Jotunn.Logger.LogInfo($"[Dvergar] Migrated '{LegacyRaceId}' to '{DvergarConfig.RaceId}' for {player.GetPlayerName()}.");
}
public static bool IsDvergar()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == DvergarConfig.RaceId;
}
private void Update()
{
Player player = Player.m_localPlayer;
if (player == null) return;
bool isDvergar = IsDvergar();
DvergarVisuals.ApplyHood(player);
// Every frame, because the eyes are placed onto the head bone in world space rather
// than parented to it - see ApplyEyes for why.
DvergarVisuals.ApplyEyes(player);
// Max health is recomputed by Player.UpdateFood, which runs on its own schedule. Left
// to itself the malus would only take effect at the next food tick, so a change of
// race or of tier is pushed through immediately - this is also what makes the health
// bar and the number agree the instant a player becomes (or stops being) a Dvergar.
float desiredMalus = isDvergar ? DvergarProgression.Current.HealthMalus : 0f;
if (!Mathf.Approximately(desiredMalus, lastAppliedMalus))
{
lastAppliedMalus = desiredMalus;
Traverse.Create(player).Method("UpdateFood", 0f, true).GetValue();
}
if (!isDvergar || player.IsDead()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
// Keep the passive carrier attached. It is re-added rather than assumed because a
// respawn, a death or a world load all clear the player's status effects.
if (DvergarStatusEffects.StatsSE != null)
{
int hash = DvergarConfig.StatsSE.GetStableHashCode();
if (!player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().AddStatusEffect(hash, true);
}
}
// Published for remote clients, matching how the Skeleton replicates its tier.
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set(DvergarConfig.StateZdoKey, state);
}
// The skin tint is only written from the UpdateColors postfix, which Valheim runs on
// its own schedule - so crossing into a new star tier would otherwise not show until
// something else happened to refresh the visuals. Push one through, the same way the
// health malus above pushes a food update.
int starTier = DvergarVisuals.GetStarTier(state);
if (starTier != lastAppliedStarTier)
{
lastAppliedStarTier = starTier;
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq != null) Traverse.Create(visEq).Method("UpdateColors").GetValue();
}
DvergarAbilities.Tick(player, state);
}
}
}