RacesOfValheim/JotunnModStub/Sverm/SvermPatches.cs
kanym b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00

481 lines
23 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every Harmony hook the Sverm body needs.
///
/// What is NOT here is worth saying, because it looked like it would be:
///
/// - "the carapace never slows you down" needs no patch at all. In vanilla the pieces that
/// carry a movement penalty ARE the chest, the legs and the helmet, and a Sverm cannot
/// wear any of them. Sealing the slots delivers the perk for free; a
/// GetEquipmentMovementModifier patch would have been a hook that changed nothing.
///
/// - carry weight, stamina on running and jumping, fall damage, eitr regeneration and the
/// discrete damage modifiers all live on SE_SvermStats, because Valheim already routes
/// them through status effects.
///
/// So what is left is the four things the game gives no other way in to: the armour value, the
/// sealed slots, exact damage scaling, and the per-frame cosmetic upkeep.
/// </summary>
public static class SvermPatches
{
// ─── Armour ──────────────────────────────────────────────────────────
/// <summary>
/// The carapace's armour, added on top of whatever the player is actually wearing - which
/// for the three sealed slots is nothing, so in practice this IS the player's armour.
/// Cape and trinket still count normally, and still stack, which is deliberate: they are
/// the two slots the race is allowed to shop for.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.GetBodyArmor))]
public static class Sverm_GetBodyArmor_Patch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == null || !SvermVisuals.IsSvermPlayer(__instance)) return;
float carapace = SvermCarapace.GetArmor(SvermVisuals.GetRenderState(__instance));
// Ravager Strain's whole benefit: the carapace is worth double for as long as the
// form holds. Multiplying only the carapace's own contribution, not the total,
// keeps a cape or trinket's armour honest instead of doubling gear the form had
// nothing to do with.
if (SvermRavagerForm.IsActive)
{
carapace *= SvermConfig.RavagerArmorMultiplier;
}
__result += carapace;
}
}
// ─── Sealed slots ────────────────────────────────────────────────────
/// <summary>
/// Chest, legs and helmet cannot be worn. The carapace is already in them.
///
/// A prefix that refuses rather than a filter on the inventory, so the item stays where it
/// is and the player gets told why. Returning false also stops the equip effects and the
/// visual rebuild, which is what keeps the carapace on screen.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.EquipItem))]
public static class Sverm_EquipItem_Patch
{
public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item, ref bool __result)
{
if (item == null || item.m_shared == null) return true;
Player player = __instance as Player;
if (player == null || !SvermVisuals.IsSvermPlayer(player)) return true;
if (!SvermCarapace.IsSealedSlot(item.m_shared.m_itemType)) return true;
if (player == Player.m_localPlayer)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_carapace_has_no_room_that"));
}
__result = false;
return false;
}
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// Both directions of the Sverm's combat maths, in one prefix because both are edits to
/// the same HitData before Valheim reads it.
///
/// OUTGOING - a bare-handed blow is rewritten into a claw blow, and Venom Glands adds
/// poison to every hit whatever is in your hands.
///
/// INCOMING - blunt and fire are scaled by an exact fraction. They are NOT in the status
/// effect's m_mods for a concrete reason: HitData.DamageModifier is a discrete enum whose
/// nearest rung, Weak, is a flat +50%, and the race is specced at +40%. Annealed Chitin
/// then flips the fire term negative at Fader, so one number walks the whole arc.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class Sverm_Damage_Patch
{
// Acid Hemolymph answers a blow with a blow, and that answer re-enters this same
// prefix. Harmless today - the attacker is not usually a Sverm - but a Sverm hitting
// a Sverm would ping-pong, so the reflection is switched off while it is being dealt.
private static bool reflecting;
public static void Prefix(Character __instance, HitData hit)
{
if (hit == null) return;
Character attacker = hit.GetAttacker();
// ── Seeker Workers bite at half a Seeker's weight. Scaled on the blow and not on the
// weapon, because the blow comes from the Seeker's default weapon and that weapon's
// shared data is every Seeker's in the world.
if (attacker != null && SvermWorker.IsWorker(attacker))
{
hit.m_damage.Modify(SvermConfig.WorkerDamageFraction);
}
// ── Outgoing
if (attacker is Player attackingPlayer && SvermVisuals.IsSvermPlayer(attackingPlayer))
{
int state = SvermVisuals.GetRenderState(attackingPlayer);
SvermProgression.SvermRules rules = SvermProgression.GetRules(state);
// Unarmed only - the claws' own tier-scaled blow. Ravager Strain's own hits
// (RavagerFormBehavior.ExecuteDamage) are built with Skills.SkillType.Swords
// on purpose, specifically so they never reach this branch and get overwritten
// by the claws' numbers - the Brute's own damage is meant to stand as-is.
if (hit.m_skill == Skills.SkillType.Unarmed)
{
SvermClaws.ApplyToUnarmedHit(hit, state);
}
if (rules.VenomOnHit > 0f)
{
hit.m_damage.m_poison += rules.VenomOnHit;
}
}
// ── Incoming
Player victim = __instance as Player;
if (victim == null || !SvermVisuals.IsSvermPlayer(victim)) return;
SvermProgression.SvermRules victimRules = SvermProgression.GetRules(SvermVisuals.GetRenderState(victim));
// Ravager Strain no longer touches incoming damage directly - its whole benefit is
// the doubled carapace armour applied in Sverm_GetBodyArmor_Patch below, which
// Valheim's own armour formula turns into reduced damage the normal way.
if (victimRules.BluntWeakness != 0f && hit.m_damage.m_blunt > 0f)
{
hit.m_damage.m_blunt *= 1f + victimRules.BluntWeakness;
}
// Negative once Annealed Chitin inverts it, which turns the same multiply into a
// resistance without a second branch.
if (victimRules.FireWeakness != 0f && hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1f + victimRules.FireWeakness;
}
// ── Acid Hemolymph
if (victimRules.AcidHemolymph <= 0f || reflecting) return;
if (attacker == null || attacker == victim) return;
if (Vector3.Distance(attacker.transform.position, victim.transform.position) > SvermConfig.HemolymphRange) return;
reflecting = true;
try
{
HitData splash = new HitData();
splash.m_damage.m_poison = victimRules.AcidHemolymph;
splash.m_point = attacker.GetCenterPoint();
splash.m_dir = (attacker.transform.position - victim.transform.position).normalized;
splash.SetAttacker(victim);
attacker.Damage(splash);
}
finally
{
reflecting = false;
}
}
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>
/// The only thing that actually colours a player.
///
/// DvergarPatches documents the dead end this avoids: SetSkinColor followed by
/// UpdateColors does nothing, because UpdateColors is what REBUILDS the body material from
/// Valheim's own values and throws any earlier write away. Writing _SkinColor here, after
/// it has run, is the only order that survives.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Sverm_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || __instance.m_bodyModel == null) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !SvermVisuals.IsSvermPlayer(player)) return;
Material material = __instance.m_bodyModel.material;
if (material != null && material.HasProperty("_SkinColor"))
{
material.SetColor("_SkinColor", SvermVisuals.GetSkinColor(player));
}
}
}
/// <summary>
/// Puts the carapace back the same frame the game takes it off.
///
/// Valheim rebuilds the equipment instances on every equipment change, from the REAL
/// contents of the slots - which for a Sverm are empty. Waiting for the throttled cosmetic
/// pass in Player.Update meant up to half a second of bare chest every time anything was
/// unequipped, which is precisely the flicker that got reported.
///
/// This is a mitigation and not the cure. The cure is real items in reserved inventory
/// slots, so the game is rebuilding from something that is actually there and there is
/// nothing to put back; until that lands, this closes the window to a single frame.
///
/// The guard is not optional: SetChestItem and its siblings mark the visuals dirty, so
/// ApplyCarapace can re-enter this postfix through the game's own refresh.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Sverm_UpdateVisuals_Patch
{
private static bool reentering;
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || reentering) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !SvermVisuals.IsSvermPlayer(player)) return;
reentering = true;
try { SvermVisuals.ApplyCarapace(player); }
finally { reentering = false; }
}
}
// ─── Per-frame upkeep ────────────────────────────────────────────────
/// <summary>
/// Scale, eyes, claws, wings and the carapace, kept in step.
///
/// On Player.Update because that is the one place body scale survives - Trol's own postfix
/// forces every non-Trol player's visual back to 1 on the same frame, so a scale applied
/// from anywhere else is simply overwritten. RaceScale keeps the two from undoing each
/// other.
///
/// The cosmetics are throttled rather than run every frame: each of them walks a renderer
/// tree, and Valheim rebuilds equipment instances only on an equipment change. Half a
/// second is well under the time it takes to notice a stale tint and well over the cost of
/// doing it sixty times a second.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Sverm_PlayerUpdate_Patch
{
private static readonly Dictionary<Player, float> nextCosmeticPass = new Dictionary<Player, float>();
private const float CosmeticInterval = 0.5f;
public static void Postfix(Player __instance)
{
if (__instance == null) return;
bool isSverm = SvermVisuals.IsSvermPlayer(__instance);
SvermVisuals.ApplyScale(__instance, isSverm);
if (!nextCosmeticPass.TryGetValue(__instance, out float due) || Time.time >= due)
{
nextCosmeticPass[__instance] = Time.time + CosmeticInterval;
SvermVisuals.ApplyEyes(__instance);
SvermVisuals.ApplyClaws(__instance); // cleanup of the retired cosmetic path
SvermVisuals.ApplySpines(__instance);
SvermVisuals.ApplyGlideMotes(__instance);
// Unconditional, like the four above it: ApplyCarapace takes the carapace OFF
// whoever is no longer a Sverm, and it cannot do that from behind an
// `if (isSverm)`. That gate is why the chitin stayed on after a race change
// until the player happened to equip something. For anyone who never wore it
// this returns on the first line.
SvermVisuals.ApplyCarapace(__instance);
// Issues the claws if they are missing and puts them back in hand whenever
// both hands are free. On the same throttle rather than every frame: it is a
// handful of checks that all short-circuit once the claws exist.
if (isSverm) SvermClawSlot.Maintain(__instance);
}
if (!isSverm || __instance != Player.m_localPlayer) return;
// Carapace Regeneration. A flat trickle rather than a multiplier on the vanilla
// regeneration, so it keeps working while the player is starving - which is the
// whole point of a shell that knits itself back together.
float regen = SvermProgression.Current.CarapaceRegenPerSecond;
if (regen > 0f && !__instance.IsDead() && __instance.GetHealth() < __instance.GetMaxHealth())
{
__instance.Heal(regen * Time.deltaTime, false);
}
}
}
// ─── Ravager Strain (remote observers) ──────────────────────────────
/// <summary>
/// Mirrors SvermRavagerForm.Enter/Exit for every OTHER client, the same way
/// Skadi_MultiplayerVisuals_Patch mirrors SkadiRace's dragon forms. SvermRavagerForm itself
/// only ever touches Player.m_localPlayer - Tick(), Enter() and RavagerFormBehavior are all
/// built around it - so without this an observer's client never knew the form was up at
/// all: no model, no hidden human body, nothing standing in for the Brute.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Sverm_RavagerRemoteVisuals_Patch
{
private const string RemoteModelName = "SvermRavagerRemoteModel";
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || player.IsOwner()) return; // Local player: SvermRavagerForm handles itself.
if (!SvermVisuals.IsSvermPlayer(player)) return;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
bool active = nview.GetZDO().GetBool(SvermRavagerForm.ActiveKey, false);
Transform existing = player.transform.Find(RemoteModelName);
Transform playerVisual = player.transform.Find("Visual");
if (!active)
{
if (existing != null)
{
Object.Destroy(existing.gameObject);
PlayerVisualHider.Show(playerVisual, "sverm-ravager-remote-revert");
}
return;
}
if (existing == null)
{
GameObject model = SvermRavagerForm.SpawnRemoteModel(player.transform);
if (model != null)
{
model.name = RemoteModelName;
model.AddComponent<RemoteRavagerAnimator>();
}
}
PlayerVisualHider.Hide(playerVisual, "sverm-ravager-remote");
}
}
/// <summary>
/// RemoteSkadiAnimator's counterpart for the Ravager Strain: locomotion off the replicated
/// Character, plus the bite/ram/slam/taunt trigger RavagerFormBehavior publishes through
/// SvermRavagerForm.PublishAttackTrigger. LateUpdate re-hides the player's own Visual every
/// frame for the same reason RavagerFormBehavior does on the local client - any nearby
/// equipment rebuild (VisEquipment's own refresh path) makes a hidden body visible again.
/// </summary>
public class RemoteRavagerAnimator : MonoBehaviour
{
private Animator anim;
private Player player;
private ZNetView nview;
private bool hasForwardSpeed;
private bool hasOnGround;
// Seeded from the ZDO's current value in Start, not "", so a trigger left over from an
// earlier Ravager Strain on this same player does not replay the instant this
// component is built.
private string lastAttackTrigger;
private void Start()
{
anim = GetComponentInChildren<Animator>();
player = GetComponentInParent<Player>();
nview = player != null ? player.GetComponent<ZNetView>() : null;
if (anim != null)
{
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Float && p.name == "forward_speed") hasForwardSpeed = true;
else if (p.type == AnimatorControllerParameterType.Bool && p.name == "onGround") hasOnGround = true;
}
}
if (nview != null && nview.IsValid())
{
lastAttackTrigger = nview.GetZDO().GetString(SvermRavagerForm.AttackTriggerKey, "");
}
}
private void LateUpdate()
{
if (player == null) return;
PlayerVisualHider.Hide(player.transform.Find("Visual"), "sverm-ravager-remote");
}
private void Update()
{
if (anim == null || player == null) return;
if (hasForwardSpeed)
{
Vector3 vel = player.GetVelocity();
vel.y = 0f;
anim.SetFloat("forward_speed", vel.magnitude);
}
if (hasOnGround) anim.SetBool("onGround", player.IsOnGround());
if (nview == null || !nview.IsValid()) return;
string current = nview.GetZDO().GetString(SvermRavagerForm.AttackTriggerKey, "");
if (string.IsNullOrEmpty(current) || current == lastAttackTrigger) return;
lastAttackTrigger = current;
int seqAt = current.LastIndexOf('#');
string trigger = seqAt >= 0 ? current.Substring(0, seqAt) : current;
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger)
{
anim.SetTrigger(trigger);
break;
}
}
}
}
// ─── Spawn ───────────────────────────────────────────────────────────
/// <summary>
/// Puts the passive back on after a load or a death, and publishes the tier on the ZDO so
/// other clients can render a remote Sverm at ITS tier rather than at theirs.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class Sverm_OnSpawned_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(__instance)) return;
__instance.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true);
PublishState(__instance);
}
}
public static void PublishState(Player player)
{
if (player == null) return;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
if (nview.GetZDO().GetInt(SvermConfig.StateZdoKey, 0) != state)
{
nview.GetZDO().Set(SvermConfig.StateZdoKey, state);
}
}
}
}