RacesOfValheim/JotunnModStub/Dvergar/DvergarPatches.cs
kanym 32c49a8af0 fix(dvergar): build pieces accept the smithing discount
The build menu showed the discounted metal cost, but Player.HaveRequirements(Piece)
read m_amount directly, so placing a piece still needed the full vanilla amount.
It now goes through GetAmount like the rest of the cost path.

Piece.DropResources also read m_amount, which would have refunded 10 tin for a
cauldron that cost 6. A piece placed by a Dvergar now stores the discount paid,
and dismantling it drops that amount.
2026-10-19 14:20:28 +02:00

514 lines
25 KiB
C#

using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every hook the Dvergar needs. The patches only ever decide *whether* a perk applies; *how
/// much* it applies always comes from DvergarProgression, which in turn reads DvergarConfig.
/// </summary>
public static class DvergarPatches
{
// ─── Health malus ────────────────────────────────────────────────────
/// <summary>
/// The Dvergar 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 Dvergar_GetTotalFoodValue_Patch
{
public static void Postfix(Player __instance, ref float hp)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!DvergarRace.IsDvergar()) return;
float malus = DvergarProgression.Current.HealthMalus;
if (malus <= 0f) return;
hp = Mathf.Max(DvergarConfig.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 Dvergar on equal footing, and RaceScale keeps the
/// two from undoing each other.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergar_PlayerUpdate_Scale_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
DvergarVisuals.ApplyScale(__instance, DvergarVisuals.IsDvergarPlayer(__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 Dvergar is at home with these
/// weapons, not faster at learning them.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class Dvergar_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 (!DvergarRace.IsDvergar()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
// Runic Spark, before the weapon check: the lightning rides every blow the Dvergar
// lands, favoured weapon or not, exactly as Skadi's frost does in SkadiDamagePatch.
float elemental = DvergarProgression.GetRules(state).ElementalDamage;
if (elemental > 0f)
{
AddFlat(hit, DvergarConfig.ElementalDamageType, elemental);
}
DvergarConfig.WeaponAffinity? found = DvergarProgression.GetAffinity(hit.m_skill, state);
if (!found.HasValue) return;
DvergarConfig.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 (DvergarProgression.GetRules(state).RunicOvercharge &&
DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer))
{
ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier);
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_dvergar_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;
case HitData.DamageType.Fire: hit.m_damage.m_fire += amount; break;
case HitData.DamageType.Frost: hit.m_damage.m_frost += amount; break;
case HitData.DamageType.Lightning: hit.m_damage.m_lightning += amount; break;
case HitData.DamageType.Poison: hit.m_damage.m_poison += amount; break;
case HitData.DamageType.Spirit: hit.m_damage.m_spirit += 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 isDvergarMining = 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 (!DvergarRace.IsDvergar()) return false;
if (!DvergarProgression.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 *= DvergarConfig.MiningDamageMultiplier;
isDvergarMining = true;
return true;
}
private static void EndMiningHit(bool began)
{
if (began) isDvergarMining = false;
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Dvergar_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 Dvergar_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 Dvergar_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 Dvergar_DropTable_GetDropList_Patch
{
public static void Postfix(ref List<GameObject> __result)
{
if (!isDvergarMining || __result == null) return;
if (DvergarConfig.MiningExtraDropChance <= 0f) return;
List<GameObject> extra = new List<GameObject>();
foreach (GameObject drop in __result)
{
if (drop == null || !IsOre(drop.name)) continue;
if (Random.value <= DvergarConfig.MiningExtraDropChance) extra.Add(drop);
}
__result.AddRange(extra);
}
private static bool IsOre(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string ore in DvergarConfig.OreDropNames)
{
if (lower.Contains(ore)) return true;
}
return false;
}
}
// ─── Smithing and jewelry ────────────────────────────────────────────
/// <summary>
/// Metal saved when crafting, upgrading and building. Requirement.GetAmount is what the
/// crafting panel, the build menu and Player.ConsumeResources all read, so the figure the
/// player is quoted and the figure they are charged can never drift apart.
///
/// Two vanilla paths read m_amount directly and skip GetAmount, both for build pieces:
/// Player.HaveRequirements(Piece) and Piece.DropResources. The two transpilers below route
/// them through the discount too.
///
/// Scoped to the metals and gems in DvergarConfig.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 Dvergar_Requirement_GetAmount_Patch
{
public static void Postfix(Piece.Requirement __instance, ref int __result)
{
if (Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
__result = DiscountedAmount(__instance, __result, DvergarProgression.Current.SmithingDiscount);
}
}
/// <summary>
/// The single rounding rule for the smithing discount. The price a Dvergar pays and the
/// refund their piece drops both go through here, so they can't end up one ingot apart.
/// </summary>
internal static int DiscountedAmount(Piece.Requirement requirement, int amount, float discount)
{
if (amount <= 1 || discount <= 0f) return amount;
if (requirement == null || requirement.m_resItem == null) return amount;
if (!IsDiscounted(requirement.m_resItem.gameObject.name)) return amount;
return Mathf.Max(1, Mathf.RoundToInt(amount * (1f - discount)));
}
private static bool IsDiscounted(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string resource in DvergarConfig.DiscountedResourceNames)
{
if (lower == resource || lower.Contains(resource)) return true;
}
return false;
}
private static readonly FieldInfo RequirementAmountField =
AccessTools.Field(typeof(Piece.Requirement), nameof(Piece.Requirement.m_amount));
/// <summary>
/// The build check. Vanilla compares the inventory against requirement.m_amount here, so
/// the menu quoted 6 tin for a cauldron while the hammer still refused to place it with
/// fewer than 10. Every m_amount read becomes GetAmount(1), which returns m_amount for
/// everyone else and the discounted figure for a Dvergar.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), typeof(Piece), typeof(Player.RequirementMode))]
public static class Dvergar_HaveRequirements_Piece_Patch
{
private static readonly MethodInfo GetAmountMethod =
AccessTools.Method(typeof(Piece.Requirement), nameof(Piece.Requirement.GetAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldc_I4_1).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Callvirt, GetAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] HaveRequirements(Piece) no longer reads m_amount; build discount check not patched.");
}
}
/// <summary>
/// ZDO key holding the discount a Dvergar paid for a piece. Stored rather than read off
/// the builder at teardown, because anyone can smash the piece and the builder's discount
/// grows with progression.
/// </summary>
private const string PaidDiscountKey = "Dvergar_PaidDiscount";
/// <summary>
/// Stamps the discount on a piece the local Dvergar just placed. Player.PlacePiece calls
/// SetCreator on the new instance right after spawning it, and ConsumeResources charges
/// the discounted price straight after.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_Piece_SetCreator_Patch
{
public static void Postfix(Piece __instance, long uid)
{
Player player = Player.m_localPlayer;
if (player == null || uid != player.GetPlayerID()) return;
if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.SmithingDiscount;
if (discount <= 0f) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(PaidDiscountKey, discount);
}
}
/// <summary>
/// The refund. Vanilla drops requirement.m_amount when a piece is removed or destroyed,
/// which handed a Dvergar back 10 tin for a cauldron that cost 6: build, smash, repeat.
/// The drop now uses the discount stamped on the piece, so it returns what was paid.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_Piece_DropResources_Patch
{
private static readonly MethodInfo PaidAmountMethod =
AccessTools.Method(typeof(Dvergar_Piece_DropResources_Patch), nameof(PaidAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Call, PaidAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] DropResources no longer reads m_amount; build discount refund not patched.");
}
public static int PaidAmount(Piece.Requirement requirement, Piece piece)
{
int amount = requirement.m_amount;
ZNetView nview = piece.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return amount;
float discount = nview.GetZDO().GetFloat(PaidDiscountKey, 0f);
return DiscountedAmount(requirement, amount, discount);
}
}
// ─── 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, Dvergar or not.
/// </summary>
[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
public static class Dvergar_Trader_GetAvailableItems_Patch
{
public static void Postfix(ref List<Trader.TradeItem> __result)
{
if (__result == null || Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.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;
// A full copy, not a hand-picked one: Valheim 1.0 hangs name, tooltip, icon,
// buy/increment keys and buy effects off TradeItem, and StoreGui reads some
// of them without null checks. Only the price is ours to change.
var copy = (Trader.TradeItem)MemberwiseCloneMethod.Invoke(item, null);
copy.m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount)));
discounted.Add(copy);
}
__result = discounted;
}
private static readonly System.Reflection.MethodInfo MemberwiseCloneMethod =
AccessTools.Method(typeof(object), "MemberwiseClone");
}
/// <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 Dvergar_ItemData_GetValue_Patch
{
public static void Postfix(ref int __result)
{
if (__result <= 0 || Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
float bonus = DvergarProgression.Current.TraderSellBonus;
if (bonus <= 0f) return;
__result = Mathf.RoundToInt(__result * (1f + bonus));
}
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>
/// Tints the Dvergar 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 Dvergar.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Dvergar_VisEquipment_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
// Before the race check, because it takes the eyes off anyone who has stopped
// being a Dvergar as well as putting them on anyone who is one. Here rather than
// in the UpdateVisuals postfix so that the tier refresh DvergarRace forces on a
// boss kill recolours them at the same moment it recolours the skin.
DvergarVisuals.ApplyEyes(player);
if (!DvergarVisuals.IsDvergarPlayer(player)) return;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
// Not the flat config colour any more: it carries the star shift a dverger of
// this standing would wear, so the race visibly ages at Bonemass and again at
// Fader.
__instance.m_bodyModel.material.SetColor("_SkinColor", DvergarVisuals.GetSkinColor(player));
}
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", DvergarConfig.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 Dvergar_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;
DvergarVisuals.ApplyHood(player);
}
}
}
}