RacesOfValheim/JotunnModStub/Dvergur/DvergurPatches.cs
kanym 8df7681cea fix(dvergur): tint the skin from UpdateColors, and raise the height
The tint was applied the way the race-selection menu appears to do it, with
VisEquipment.SetSkinColor followed by UpdateColors, and had no visible effect.
That pair is not what colours a player: UpdateColors rebuilds the body material
from Valheim own state each refresh, so a tint only survives if it is written
after it runs. Every race here that visibly changes colour already has a
postfix on UpdateColors setting _SkinColor on the material, and the SetSkinColor
calls in the menu are decorative on their own. The Dvergur now follows the Trol.

Reading the race from the ZDO with a m_customData fallback and no local-player
check covers the main-menu preview and the first spawn frame, where
Player.m_localPlayer is still null. Nothing needs saving or restoring either,
since the tint stops being applied the moment the race changes.

Beard and hair go pale to match; the hood hides most of the hair but the beard
shows.

Height goes from 0.70 to 0.78. The spec asked for at least -30% but that read as
too small beside a human on screen.
2026-08-02 23:08:12 +02:00

370 lines
17 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 malus is taken off the food total rather than off Character.GetMaxHealth, which is
/// what the first attempt did and what produced the bug where the bar shrank but the
/// number stayed put and the border flashed. Patching the getter makes it lie to the rest
/// of the game: Character.SetMaxHealth is the only thing that clamps current health down
/// to the new maximum, and it never saw a lower number, so m_health stayed at 58. Worse,
/// Player.SetMaxHealth flashes the bar whenever the new maximum is above GetMaxHealth() -
/// against a getter that always read low, every food tick looked like a health *increase*
/// and re-triggered the flash.
///
/// GetTotalFoodValue is upstream of both: UpdateFood feeds its result straight into
/// SetMaxHealth, so Valheim does its own clamping and its own flash logic on an honest
/// number and bar, value and animation all agree.
/// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Dvergur_GetTotalFoodValue_Patch
{
public static void Postfix(Player __instance, ref float hp)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!DvergurRace.IsDvergur()) return;
float malus = DvergurProgression.Current.HealthMalus;
if (malus <= 0f) return;
hp = Mathf.Max(DvergurConfig.MinMaxHealth, hp - malus);
}
}
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// Sizing runs off Player.Update, which is where the Trol does it and the only place it
/// holds: Trol's own postfix forces every non-Trol player's visual back to scale 1 on the
/// same frame, so a scale applied from anywhere else was simply overwritten. Being a
/// postfix on the same method puts the Dvergur on equal footing, and RaceScale keeps the
/// two from undoing each other.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergur_PlayerUpdate_Scale_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
DvergurVisuals.ApplyScale(__instance, DvergurVisuals.IsDvergurPlayer(__instance));
}
}
// ─── 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));
}
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>
/// Tints the Dvergur ashen grey.
///
/// The first attempt did this the way the race-selection menu appears to - VisEquipment's
/// SetSkinColor followed by UpdateColors - and nothing happened, because that pair is not
/// what actually colours a player. UpdateColors rebuilds the body material from Valheim's
/// own state on every refresh, so any tint has to be written *after* it runs. That is why
/// every race in this mod that visibly changes colour has a postfix here writing
/// _SkinColor onto the material directly, and why the SetSkinColor calls in the selection
/// menu are, on their own, decorative.
///
/// No local-player check and no saved original: the race is read from the ZDO with a
/// m_customData fallback so the main-menu preview and the first spawn frame are covered
/// too, and the tint simply stops being applied once the player is no longer a Dvergur.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Dvergur_VisEquipment_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !DvergurVisuals.IsDvergurPlayer(player)) return;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
__instance.m_bodyModel.material.SetColor("_SkinColor", DvergurConfig.SkinColor);
}
TintRenderers(Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>());
TintRenderers(Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>());
}
private static void TintRenderers(GameObject instance)
{
if (instance == null) return;
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>())
{
if (renderer.material != null) renderer.material.SetColor("_SkinColor", DvergurConfig.HairColor);
}
}
}
// ─── 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.ApplyHood(player);
}
}
}
}