RacesOfValheim/JotunnModStub/Dvergur/DvergurPatches.cs
kanym 3ec51aeb45 feat(dvergur): add the Dvergur race scaffold
An eighth race built on the existing per-race pattern: a MonoBehaviour driver
registered from Awake, a progression table keyed on the boss state, an SE_Stats
carrier, and Harmony patches for the individual perks.

The helmet slot stays free. Whatever the player equips keeps every one of its
stats and only its mesh is swapped for the dvergr hood, which is the Skeleton's
helmet handling turned into a replacement rather than a plain hide.

Every percentage the spec left open lives in DvergurConfig as a named value and
is marked TODO there, so tuning the race never means touching the logic. The
knobs are static readonly rather than const so that switching a perk off with a
zero does not fold its guard into dead code.
2026-08-02 21:45:44 +02:00

297 lines
13 KiB
C#

using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every hook the Dvergur needs. The patches only ever decide *whether* a perk applies; *how
/// much* it applies always comes from DvergurProgression, which in turn reads DvergurConfig.
/// </summary>
public static class DvergurPatches
{
// ─── Health malus ────────────────────────────────────────────────────
/// <summary>
/// The Dvergur is a small frame, and carries less health for it. The target is resolved
/// with AccessTools rather than named against a type, because GetMaxHealth may be declared
/// on Character or overridden on Player depending on the game version - AccessTools walks
/// up to whichever one actually runs, and the local-player guard makes either correct.
/// </summary>
[HarmonyPatch]
public static class Dvergur_GetMaxHealth_Patch
{
public static MethodBase TargetMethod() => AccessTools.Method(typeof(Player), "GetMaxHealth");
public static void Postfix(Character __instance, ref float __result)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!DvergurRace.IsDvergur()) return;
float malus = DvergurProgression.Current.HealthMalus;
if (malus <= 0f) return;
__result = Mathf.Max(DvergurConfig.MinMaxHealth, __result - malus);
}
}
// ─── Weapon affinity: damage ─────────────────────────────────────────
/// <summary>
/// Bonus damage with hammer, bow, axe and crossbow as each is unlocked, and the payoff for
/// a held Runic Overcharge. Neither touches skill XP: the Dvergur is at home with these
/// weapons, not faster at learning them.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class Dvergur_WeaponAffinity_Damage_Patch
{
public static void Prefix(Character __instance, HitData hit)
{
if (hit == null || Player.m_localPlayer == null) return;
if (hit.GetAttacker() != Player.m_localPlayer) return;
if (!DvergurRace.IsDvergur()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
DvergurConfig.WeaponAffinity? found = DvergurProgression.GetAffinity(hit.m_skill, state);
if (!found.HasValue) return;
DvergurConfig.WeaponAffinity affinity = found.Value;
if (affinity.DamagePercent > 0f)
{
ScalePhysical(hit, 1f + affinity.DamagePercent);
}
if (affinity.FlatDamage > 0f)
{
AddFlat(hit, affinity.FlatDamageType, affinity.FlatDamage);
}
// Overcharge only ever discharges into a favoured weapon, which is why it is
// spent here rather than on the first hit of any kind.
if (DvergurProgression.GetRules(state).RunicOvercharge &&
DvergurAbilities.ConsumeOvercharge(Player.m_localPlayer))
{
ScalePhysical(hit, DvergurConfig.RunicOverchargeMultiplier);
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "Runic Overcharge discharges");
}
}
private static void ScalePhysical(HitData hit, float multiplier)
{
hit.m_damage.m_blunt *= multiplier;
hit.m_damage.m_slash *= multiplier;
hit.m_damage.m_pierce *= multiplier;
}
private static void AddFlat(HitData hit, HitData.DamageType type, float amount)
{
switch (type)
{
case HitData.DamageType.Blunt: hit.m_damage.m_blunt += amount; break;
case HitData.DamageType.Slash: hit.m_damage.m_slash += amount; break;
case HitData.DamageType.Pierce: hit.m_damage.m_pierce += amount; break;
default: hit.m_damage.m_damage += amount; break;
}
}
}
// ─── Mining affinity ─────────────────────────────────────────────────
/// <summary>
/// Set for the duration of a mining hit so the drop patch below can tell an ore roll made
/// by this player apart from every other DropTable call in the world. Same flag-around-the
/// -call approach the Furling uses for its doubled ore.
/// </summary>
private static bool isDvergurMining = false;
private static bool BeginMiningHit(HitData hit)
{
if (hit == null || Player.m_localPlayer == null) return false;
if (hit.GetAttacker() != Player.m_localPlayer) return false;
if (!DvergurRace.IsDvergur()) return false;
if (!DvergurProgression.Current.MiningAffinity) return false;
// A pickaxe swing is what the affinity is about - chopping and combat hits on the same
// objects go through here too and must be left alone.
if (hit.m_damage.m_pickaxe <= 0f) return false;
hit.m_damage.m_pickaxe *= DvergurConfig.MiningDamageMultiplier;
isDvergurMining = true;
return true;
}
private static void EndMiningHit(bool began)
{
if (began) isDvergurMining = false;
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Dvergur_MineRock5_DamageArea_Patch
{
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
public static void Postfix(bool __state) => EndMiningHit(__state);
}
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
public static class Dvergur_MineRock_RPC_Hit_Patch
{
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
public static void Postfix(bool __state) => EndMiningHit(__state);
}
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
public static class Dvergur_Destructible_RPC_Damage_Patch
{
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
public static void Postfix(bool __state) => EndMiningHit(__state);
}
[HarmonyPatch(typeof(DropTable), "GetDropList", new System.Type[] { typeof(int) })]
public static class Dvergur_DropTable_GetDropList_Patch
{
public static void Postfix(ref List<GameObject> __result)
{
if (!isDvergurMining || __result == null) return;
if (DvergurConfig.MiningExtraDropChance <= 0f) return;
List<GameObject> extra = new List<GameObject>();
foreach (GameObject drop in __result)
{
if (drop == null || !IsOre(drop.name)) continue;
if (Random.value <= DvergurConfig.MiningExtraDropChance) extra.Add(drop);
}
__result.AddRange(extra);
}
private static bool IsOre(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string ore in DvergurConfig.OreDropNames)
{
if (lower.Contains(ore)) return true;
}
return false;
}
}
// ─── Smithing and jewelry ────────────────────────────────────────────
/// <summary>
/// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both
/// the crafting panel and Player.ConsumeResources go through, so the figure the player is
/// quoted and the figure they are charged can never drift apart.
///
/// Scoped to the metals and gems in DvergurConfig.DiscountedResourceNames, which is what
/// keeps this a smithing perk rather than a blanket discount on every wooden wall.
/// </summary>
[HarmonyPatch(typeof(Piece.Requirement), "GetAmount")]
public static class Dvergur_Requirement_GetAmount_Patch
{
public static void Postfix(Piece.Requirement __instance, ref int __result)
{
if (__result <= 1 || Player.m_localPlayer == null) return;
if (!DvergurRace.IsDvergur()) return;
float discount = DvergurProgression.Current.SmithingDiscount;
if (discount <= 0f) return;
if (__instance == null || __instance.m_resItem == null) return;
if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return;
__result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount)));
}
private static bool IsDiscounted(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string resource in DvergurConfig.DiscountedResourceNames)
{
if (lower == resource || lower.Contains(resource)) return true;
}
return false;
}
}
// ─── Haldor and Hildir's favour ──────────────────────────────────────
/// <summary>
/// The buying half. Both traders are Trader components, so patching the shared source of
/// the stock list covers Haldor and Hildir at once.
///
/// The discounted entries are fresh TradeItem instances rather than edited originals: the
/// list Valheim hands back holds the trader's own objects, and rewriting their prices in
/// place would permanently mark down the shop for everyone, Dvergur or not.
/// </summary>
[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
public static class Dvergur_Trader_GetAvailableItems_Patch
{
public static void Postfix(ref List<Trader.TradeItem> __result)
{
if (__result == null || Player.m_localPlayer == null) return;
if (!DvergurRace.IsDvergur()) return;
float discount = DvergurProgression.Current.TraderBuyDiscount;
if (discount <= 0f) return;
List<Trader.TradeItem> discounted = new List<Trader.TradeItem>(__result.Count);
foreach (Trader.TradeItem item in __result)
{
if (item == null) continue;
discounted.Add(new Trader.TradeItem
{
m_prefab = item.m_prefab,
m_stack = item.m_stack,
m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount))),
m_requiredGlobalKey = item.m_requiredGlobalKey
});
}
__result = discounted;
}
}
/// <summary>
/// The selling half - trophies and hunting rewards fetch more. GetValue is what the sell
/// button both displays and pays out, and it is not consulted for purchases, so the bonus
/// lands on exactly the side of the counter it is meant to.
/// </summary>
[HarmonyPatch(typeof(ItemDrop.ItemData), "GetValue")]
public static class Dvergur_ItemData_GetValue_Patch
{
public static void Postfix(ref int __result)
{
if (__result <= 0 || Player.m_localPlayer == null) return;
if (!DvergurRace.IsDvergur()) return;
float bonus = DvergurProgression.Current.TraderSellBonus;
if (bonus <= 0f) return;
__result = Mathf.RoundToInt(__result * (1f + bonus));
}
}
// ─── Cosmetic hood ───────────────────────────────────────────────────
/// <summary>
/// Runs for every player, local and remote, whenever Valheim rebuilds their visuals - the
/// point at which a newly equipped helmet has just been instantiated and needs hiding
/// again behind the hood.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Dvergur_VisEquipment_UpdateVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
DvergurVisuals.Apply(player);
}
}
}
}